How to Create your own Captcha System on User SignUp using PHP and Ajax

PHP, jQuery and HTML Code

<?php
session_start();
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "whatsappdwld_db");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);


if (isset($_POST['submit_form'])) {
    $user_captcha = $_POST['captcha_text'];
    if ($user_captcha == $_SESSION['captcha']) {
        $name = $_POST['username'];
        $email = $_POST['useremail'];
        $password = $_POST['userpass'];
        $insertdata = " INSERT INTO user (name,email,password) VALUES( '$name','$email','$password' ) ";
        mysqli_query($con,$insertdata);
    } 
    else 
    {
        echo "Wrong Captcha Please Try Again";
    }
}
?>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">

            function getcaptcha()
            {
                $.ajax({
                    type: 'post',
                    url: 'captcha.php',
                    success: function (response) {
                        $('#captcha').attr('src', 'captcha.php');
                    }
                });
            }
        </script>

    </head>
    <body>

        <form method="POST" action="" >
            <input type="text" name="username" >
            <input type="text" name="useremail" >
            <input type="password" name="userpass" >
            <img src="captcha.php" width="150" height="100" id="captcha">
            <input type="button" value="Reload Captcha" onclick="getcaptcha();" >
            <input type="text" name="captcha_text">
            <input type="submit" name="submit_form" value="SignUp">
        </form>

    </body>
</html>

PHP Code (captcha.php)

<?php
    session_start();
    header('Content-type: image/png');
    $chars = "012345678901234567abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $captcha_text = '';
    for ($i = 0; $i < 6; $i++) {
        $captcha_text .= $chars[rand(0, strlen($chars) - 1)];
    }
    $captcha_bg = @imagecreatefrompng("images/captcha.png");
    imagettftext($captcha_bg, 30, 0, 0, 40, imagecolorallocate($captcha_bg, 0, 0, 0), 'larabiefont.ttf', $captcha_text);
    $_SESSION['captcha'] = $captcha_text;
    imagepng($captcha_bg, NULL, 0);
    imagedestroy($captcha_bg);

?>

Leave a Reply

Your email address will not be published. Required fields are marked *