Are there any security vulnerabilities present in the PHP code snippet for handling newsletter subscriptions?
The PHP code snippet for handling newsletter subscriptions is vulnerable to SQL injection attacks due to the use of unsanitized user input in the SQL query. To solve this issue, you should use prepared statements with parameterized queries to prevent SQL injection attacks.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize the email input
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("INSERT INTO newsletter_subscriptions (email) VALUES (:email)");
$stmt->bindParam(':email', $email);
// Execute the query
$stmt->execute();
// Display success message
echo "Thank you for subscribing to our newsletter!";
}
?>