What best practices should be followed when handling user input from URLs in PHP to prevent vulnerabilities like SQL injection?
To prevent vulnerabilities like SQL injection when handling user input from URLs in PHP, it is important to sanitize and validate the input before using it in database queries. One way to achieve this is by using prepared statements with parameterized queries, which separate the SQL query from the user input.
// Sanitize and validate user input from URL
$user_input = filter_input(INPUT_GET, 'user_input', FILTER_SANITIZE_STRING);
// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $user_input, PDO::PARAM_STR);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);