How can PHP be utilized to prevent common security vulnerabilities like SQL injection and cross-site scripting when handling form data?
To prevent SQL injection, PHP can utilize prepared statements with parameterized queries to sanitize user input before executing SQL queries. To prevent cross-site scripting, PHP can use htmlspecialchars() function to encode user input before displaying it in HTML.
// SQL injection prevention using prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
// Cross-site scripting prevention using htmlspecialchars()
echo htmlspecialchars($_POST['input'], ENT_QUOTES, 'UTF-8');