How can one securely handle user input in PHP to prevent vulnerabilities like SQL injection, considering the use of filter_var with FILTER_SANITIZE_STRING is now deprecated?
To securely handle user input in PHP and prevent vulnerabilities like SQL injection after the deprecation of FILTER_SANITIZE_STRING, you can use prepared statements with parameterized queries. This method separates SQL code from user input, preventing malicious code injection.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the prepared statement
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();