How can PHP scripts be vulnerable to attacks like PHP injection or cross-site scripting?

PHP scripts can be vulnerable to attacks like PHP injection or cross-site scripting when user input is not properly sanitized or validated. To prevent these vulnerabilities, always use prepared statements when interacting with databases to avoid SQL injection attacks, and use functions like htmlspecialchars() to escape user input to prevent cross-site scripting attacks. Example PHP code snippet to prevent SQL injection:

// Establish database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind parameters
$stmt->bindParam(':username', $_POST['username']);

// Execute the statement
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll();