What are the best practices for passing user-specific variables to a PHP script for dynamic content generation?
When passing user-specific variables to a PHP script for dynamic content generation, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One common practice is to use PHP's filter_input function to retrieve user input from GET or POST requests and validate it against a predefined filter. Additionally, using prepared statements for database queries can help prevent SQL injection attacks.
// Retrieve user-specific variable from GET request
$user_id = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
// Validate user_id against predefined filter
if ($user_id === false) {
die("Invalid user ID");
}
// Use prepared statement for database query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();