What potential security risks are associated with using $_GET in PHP for passing variables in URLs?
Using $_GET in PHP for passing variables in URLs can lead to security risks such as SQL injection attacks and cross-site scripting (XSS) vulnerabilities. To mitigate these risks, it is important to properly sanitize and validate any input received from $_GET before using it in your application.
// Example of sanitizing and validating input from $_GET
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// Use htmlspecialchars to prevent XSS
$name = isset($_GET['name']) ? htmlspecialchars($_GET['name']) : '';