What are the best practices for accessing and handling query parameters in PHP scripts?

When accessing and handling query parameters in PHP scripts, it is important to properly sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One common practice is to use the $_GET superglobal array to access query parameters and then sanitize them using functions like filter_input() or htmlspecialchars(). Additionally, it is recommended to validate the input against expected values or patterns before using it in any database queries or outputting it to the user.

// Accessing and handling query parameters in PHP script

// Get the value of a query parameter named 'id' and sanitize it
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

// Validate the input against expected values or patterns
if (!is_numeric($id) || $id <= 0) {
    // Handle invalid input (e.g., display an error message or redirect)
    die("Invalid ID parameter");
}

// Use the sanitized and validated input in your script (e.g., database query)
$query = "SELECT * FROM users WHERE id = $id";
// Execute the query and handle the results accordingly