What are the best practices for handling user input from URLs and forms in PHP to prevent unauthorized access or manipulation?

When handling user input from URLs and forms in PHP, it is crucial to validate and sanitize the input to prevent unauthorized access or manipulation. One of the best practices is to use PHP's built-in filtering functions like filter_input() or filter_var() to validate input data. Additionally, always use prepared statements or parameterized queries when interacting with a database to prevent SQL injection attacks.

// Example of validating and sanitizing user input from a form
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();