CAPTCHA is a simple test to determine if a user is a computer or a human. It is used to prevent spam abuse on the websites. So if you use PHP CAPTCHA on your web site forms, this can help in stopping some bots and making life harder for other bots in accessing or using your forms. In brief the CAPTCHA protection works by generating a random string, writing it to an image, then storing the string inside of a session or by some other method. This is then checked when the form is submitted.

When allowing users to enter data into our website, we’d like to see whether the info is entered by the human. Otherwise, people will use robots to push the majority of unwanted data into the web site. By allowing malicious access, it’ll cause tons of problems. for instance, XSS attack or SQL injection and more. Sometimes it’ll increase server load and let it down. it’s going to annoy your regular users thanks to the unavailability of the web site. Captcha is one among the simplest remedies for this hazard. It prevents anonymous access and stops robots from sending data.

We need to create 4 files

ajax_captcha.js // This file process ajax post for form.
captcha.php // This will check if captcha submitted is valid or not
create_image.php // This file will create an image from session string
index.php // This is demo file, will show a captcha image and form to test

Demo: PHP AJAX CAPTCHA

So, here we go:

Captcha element in Javascript

/*
* Shared by BienThuy.Com
* www.BienThuy.Com
* @ 2020. All Rights Reserved.
*/
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
 if (window.XMLHttpRequest) {
    return new XMLHttpRequest(); //Mozilla, Safari ...
 } else if (window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP"); //IE
 } else {
    //Display our error message
    alert("Your browser doesn't support the XmlHttpRequest object.");
 }
}
 
//Our XmlHttpRequest object
var receiveReq = getXmlHttpRequestObject();
 
//Initiate the AJAX request
function makeRequest(url, param) {
//If our readystate is either not started or finished, initiate a new request
 if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
   //Set up the connection to captcha_test.html. True sets the request to asyncronous(default)
   receiveReq.open("POST", url, true);
   //Set the function that will be called when the XmlHttpRequest objects state changes
   receiveReq.onreadystatechange = updatePage;
 
   receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   receiveReq.setRequestHeader("Content-length", param.length);
   receiveReq.setRequestHeader("Connection", "close");
 
   //Make the request
   receiveReq.send(param);
 }  
}
 
//Called every time our XmlHttpRequest objects state changes
function updatePage() {
 //Check if our response is ready
 if (receiveReq.readyState == 4) {
   //Set the content of the DIV element with the response text
   document.getElementById('result').innerHTML = receiveReq.responseText;
   //Get a reference to CAPTCHA image
   img = document.getElementById('imgCaptcha');
   //Change the image
   img.src = 'create_image.php?' + Math.random();
 }
}
 
//Called every time when form is perfomed
function getParam(theForm) {
 //Set the URL
 var url = 'captcha.php';
 //Set up the parameters of our AJAX call
 var postStr = theForm.txtCaptcha.name + "=" + encodeURIComponent( theForm.txtCaptcha.value );
 //Call the function that initiate the AJAX request
 makeRequest(url, postStr);
}

Validating Captcha code in server-side

<?
/*
* Shared by BienThuy.Com
* www.BienThuy.Com
* @ 2020. All Rights Reserved.
*/
//Continue the session
session_start();
 
//Make sure that the input come from a posted form. Otherwise quit immediately
if ($_SERVER["REQUEST_METHOD"] <> "POST")
 die("You can only reach this page by posting from the html form");
 
//Check if the securidy code and the session value are not blank
//and if the input text matches the stored text
if ( ($_REQUEST["txtCaptcha"] == $_SESSION["security_code"]) &&
    (!empty($_REQUEST["txtCaptcha"]) && !empty($_SESSION["security_code"])) ) {
  echo "<h1>Test successful!</h1>";
} else {
  echo "<h1>Test failed! Try again!</h1>";
}
?>

PHP code to create captcha

<?
/*
* Shared by BienThuy.Com
* www.BienThuy.Com
* @ 2020. All Rights Reserved.
*/
 
//Start the session so we can store what the security code actually is
session_start();
 
//Send a generated image to the browser
create_image();
exit();
 
function create_image()
{
    //Let's generate a totally random string using md5
    $md5_hash = md5(rand(0,9999));
    //We don't need a 32 character long string so we trim it down to 5
    $security_code = substr($md5_hash, 15, 7);
 
    //Set the session to store the security code
    $_SESSION["security_code"] = $security_code;
 
    //Set the image width and height
    $width = 120;
    $height = 20; 
 
    //Create the image resource
    $image = ImageCreate($width, $height); 
 
    //We are making three colors, white, black and gray
    $white = ImageColorAllocate($image, 255, 255, 255);
    $black = ImageColorAllocate($image, 242, 106, 47);
    $grey = ImageColorAllocate($image, 242, 106, 47);
 
    //Make the background black
    ImageFill($image, 0, 0, $black);
 
    //Add randomly generated string in white to the image
    ImageString($image, 3, 30, 3, $security_code, $white);
 
    //Throw in some lines to make it a little bit harder for any bots to break
    ImageRectangle($image,0,0,$width-1,$height-1,$grey);
   // imageline($image, 0, $height/2, $width, $height/2, $grey);
   // imageline($image, $width/2, 0, $width/2, $height, $grey);
  
    //Tell the browser what kind of file is come in
    header("Content-Type: image/jpeg");
 
    //Output the newly created image in jpeg format
    ImageJpeg($image);
     
    //Free up resources
    ImageDestroy($image);
}
?>

Output Captcha element in HTML contact form

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
/*
* Shared by BienThuy.Com
* www.BienThuy.Com
* @ 2020. All Rights Reserved.
*/ 
-->
<html>
    <head>
     
  <style>
 #baotrang { margin:0 auto; width: 900px; }
  </style>
  <script language="JavaScript" type="text/javascript" src="/ht/ajax_captcha.js"></script>
    </head>
    <body>
    <div id="baotrang">
    <form id="frmCaptcha" name="frmCaptcha">
        <table>
            <tr>
                <td align="left">
                    <label for="captcha">Captcha</label>
                </td>
                <td>
                    <input id="txtCaptcha" type="text" name="txtCaptcha" value="" maxlength="10" size="32" />
                </td>
                <td>
                    <img id="imgCaptcha" src="/ht/create_image.php" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input id="btnCaptcha" type="button" value="Captcha Test" name="btnCaptcha"
                        onclick="getParam(document.frmCaptcha)" />
                </td>
            </tr>
        </table>
 
        <div id="result">&nbsp;</div>
    </form>
    </div>
    </body>
</html>

Download Fullcode:

https://yyen.info/rRjMrLlFZB

4.6/5 - (4847 bình chọn)

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *