What are some best practices for preventing spam abuse in PHP contact forms?
Spam abuse in PHP contact forms can be prevented by implementing CAPTCHA verification, input validation, and form submission limits. By adding these measures, you can reduce the likelihood of spam submissions and protect your website from malicious activities.
// Verify CAPTCHA input
if(isset($_POST['g-recaptcha-response'])){
$captcha = $_POST['g-recaptcha-response'];
$secretKey = 'YOUR_SECRET_KEY';
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha);
$responseKeys = json_decode($response, true);
if(intval($responseKeys["success"]) !== 1) {
// CAPTCHA verification failed
// Handle error here
}
}
// Validate input fields
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])){
// Handle empty fields error here
}
// Limit form submissions
if(isset($_SESSION['form_submissions'])){
$_SESSION['form_submissions']++;
if($_SESSION['form_submissions'] > 3){
// Limit exceeded, handle error here
}
} else {
$_SESSION['form_submissions'] = 1;
}
// Process form submission
// Your code to send email or save data to database goes here
Related Questions
- Are there any best practices for designing HTML forms that are compatible with various devices in PHP development?
- What is the difference between using require_once to include code and directly embedding it in a PHP page?
- What is the difference between using file, readfile, and file_get_contents for reading file contents in PHP?