What are common security risks associated with PHP contact forms, as seen in the provided code snippet?
One common security risk associated with PHP contact forms is the lack of input validation, which can lead to potential injection attacks. To mitigate this risk, it is important to sanitize and validate user input before processing it. Additionally, using prepared statements for database queries can help prevent SQL injection attacks. Lastly, implementing CSRF tokens can protect against cross-site request forgery attacks.
// Validate and sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Implement CSRF token
session_start();
$token = md5(uniqid(rand(), true));
$_SESSION['csrf_token'] = $token;
// Check CSRF token before processing form submission
if ($_POST['csrf_token'] === $_SESSION['csrf_token']) {
// Process form submission
// Use prepared statements for database queries
} else {
// Handle CSRF attack
echo "CSRF token validation failed";
}
Related Questions
- What steps should be taken to ensure smooth communication between JavaScript and PHP for tasks like reverse geocoding in a web application?
- What are the recommended methods for handling user input in PHP to prevent vulnerabilities and ensure secure execution of shell commands?
- What are some best practices for implementing a CAPTCHA code in PHP to prevent spam bots?