How can PHP developers protect their websites from spam bots using AJAX requests?
Spam bots can be prevented from submitting forms on websites by implementing a CAPTCHA system. This can be done by using Google reCAPTCHA, which requires users to verify that they are not a robot before submitting a form. This can be easily integrated into a website by adding the necessary HTML and JavaScript code provided by Google.
<?php
// Your PHP form handling code here
// Verify the reCAPTCHA response
$recaptcha_secret = 'YOUR_RECAPTCHA_SECRET_KEY';
$recaptcha_response = $_POST['g-recaptcha-response'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$recaptcha_secret&response=$recaptcha_response");
$responseKeys = json_decode($response, true);
if(intval($responseKeys["success"]) !== 1) {
// Handle invalid reCAPTCHA response
exit('Invalid reCAPTCHA verification');
}
// Continue processing the form submission
Keywords
Related Questions
- Is it recommended to render data in the view or the controller in PHP?
- In what situations should PHP variables be stored as strings in separate variables for easier manipulation and output in HTML elements?
- What are the implications of modifying the DocumentRoot and Directory paths in the httpd.conf file in relation to PHP include paths?