Form Validation with captcha using jquery Validation and PHP

Updated on ... 04th February 2023

In this tutorial, we will show you the jquery validation and PHP gd library captcha image to prevent the form from session hijacking.

To check a PHP GD library CAPTCHA in jQuery validation and submit a form using AJAX after validation, you can follow these steps:

  • First, create a simple HTML form with html validation using bootstrap 5
  • Create a captcha using the gd library with preventing session hijacking and call it to HTML form
  • create a captcha regenerate function using jquery
  • Validate form using  jquery validation 
  • create a check-capthca.php file for checking the captcha
  • create submit.php code  with data sanitization 

Letter on this tutorial we also see these points:

  • Why you need to use jquery validation:
  • PHP input data filter and sanitization

Create a simple HTML form with html validation:

In the first step, we will create a simple html form using bootstrap. we are using bootstrap 5, only for good-looking design purposes.



                                                    

                                                    

                                                    <!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div class="container">
        <div class="row">
            <div class="col-md-6">
                <h1>Jquery validation and PHP </h1>
                <form id="cnt_myform" method="post" >
                    <div class="form-group mb-3">
                        <label for="exampleInputEmail1" class="form-label">Name</label>
                        <input class="form-control" type="text" name="name" id="name" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="exampleInputEmail1" class="form-label">Email </label>
                        <input class="form-control" type="email" name="email" id="email" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="mobile" class="form-label">Contact </label>
                        <input class="form-control" type="text" name="mobile" id="mobile" required>
                    </div>

                    <div class="form-group mb-3">
                        <label for="exampleInputEmail1" class="form-label">Gender</label>
                        <select class="form-control" name="gender" id="gender" required>
                            <option value="">Select Gender</option>
                            <option value="male">Male</option>
                            <option value="female">Female</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="mb-3 ">
                        <input type="checkbox"  name="terms" id="terms" required>
                        <label class="form-check-label" for="terms">I accept the terms and conditions</label>
                    </div>

                    <div class="form-group">
                        <div class="row">
                            <div class="col-lg-4">
                            <label for="captcha_text" class="form-label">Enter Captcha</label>
                                <input type="text" id="captcha_text" name="captcha_text" class="form-control" required>
                            </div>
                            <div class="col-lg-2" style="margin-top:32px;">
                            <img id="captcha" src="captcha.php" alt="CAPTCHA" style="width:190px">


                            </div>
                            <div class="col-lg-4" style="margin-top:32px;">
                            <button type="button" class=" btn  btn-primary" onclick="captcha_refresh()">Regenerate captcha</button>

                            </div>
                        </div>
                    </div>
                    </div>
                   
                    <div class="mb-3 ">
                       <input class="btn btn-primary" type="submit" value="Submit">
                    </div>
                   
                </form>
            </div>
        </div>
    </div>

                                                    

                                                

Create captcha using the gd library with preventing session hijacking

In this step, we will create a captcha image named captcha.php using PHP gd library with preventing session hijacking and call it to html form.



                                                    

                                                    

                                                    <?php
session_start();
header("Content-type: image/png");

// Create the image
$image = imagecreate(120, 40);

// Set the background color
$bg = imagecolorallocate($image, 255, 255, 255);

// Generate a random string for the CAPTCHA
$captcha_string = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);

// Store the captcha string in a session variable
$_SESSION['captcha'] = $captcha_string;

// Set the text color
$text_color = imagecolorallocate($image, 0, 0, 0);
$line_color = imagecolorallocate($image, 140,140,140); 
for($i=0;$i<40;$i++) {
    imageline($image,0,rand()%25,60,rand()%25,$line_color);
}

// Write the captcha string on the image
imagestring($image, 12, 5, 2, $captcha_string, $text_color);

// Output the image
imagepng($image);

// Destroy the image
imagedestroy($image);

                                                    

                                                

You Should Also Read

GD Library:

In the above code we have used GD Library for captcha image creation The GD Library is a PHP open-source software library for the dynamic creation of images (so that you don't need to install it separately), primarily used for creating graphics and charts on the web. It is written in C and provides a simple way to create images on the fly, including charts, graphs, and other dynamic images.

The GD Library supports various image formats, including PNG, JPEG, GIF, and WBMP, and provides a range of image manipulation functions, such as resizing, cropping, and rotating. It can also be used to generate dynamic images, such as CAPTCHAs, for use in forms and other web applications.

In PHP, the GD Library is an extension that can be installed and enabled to provide the functionality required to create and manipulate images. The GD Library is widely used in PHP and provides a fast and convenient way to create dynamic images for web applications.

Create a captcha regenerate function using jquery

Sometimes when filling out the form user is not able to understand the captcha text so it is important to regenerate the captcha text. now you can use the below jquery function to regenerate the captcha on the click event.


                                                    

                                                    

                                                    function captcha_refresh(){
            $("#captcha").attr('src', 'captcha.php');
             return false;
}

                                                    

                                                

Validate form using  jquery validation:

jQuery Validation Plugin is a popular plugin that can be used to validate forms on the client side.

To use the jQuery Validation plugin for form validation, you will need to include the jQuery library and the validation plugin in your HTML file. You can either download the files from the official website and host them on your server or include them from a CDN. here I will use CDN. After including jquery validation you can write the validation rule then you can write the ajax function on validation submitHandler to submit the form.

Here is an example of the jquery validation rule  and ajax function put it into your form page:


                                                    

                                                    

                                                    <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU="  crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js" integrity="sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP+Tr04hbtA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    function captcha_refresh(){
        $("#captcha").attr('src', 'captcha.php');
            return false;
    }

    $.validator.addMethod("mobile", function(value, element) {
        return this.optional(element) || /^(?:\+\d{2}[- ]?)?\d{10}$/.test(value);
    }, "Please enter a valid mobile number (10 digits only)");

    $.validator.addMethod("terms", function (value, element) {
        return $(element).is(":checked");
    }, "Please accept the terms and conditions");

    $(document).ready(function () {
        var captchaText = $("#captcha_text").val();
        //var captcha_var = "<?php //echo $_SESSION['captcha']; ?>";
        $("#cnt_myform").validate({
            rules: {
                name: {
                    required: true,
                    minlength: 3
                },
                terms: {
                    required: true,
                    terms:true
                },
                email: {
                    required: true,
                    email: true
                },
                mobile: {
                    required: true,
                    mobile: true
                },
                gender: {
                    required: true
                },
                
                captcha_text: {
                    required: true,
                    remote: {
                        url: "check-captcha.php",
                        type: "post",
                        data: {
                            captcha: function() {
                                return $("#captcha_text").val();
                            }
                        }
                    }
                },
                
            },
            messages: {
                name: {
                    required: "Please enter your name",
                    minlength: "Name must be at least 3 characters long"
                },
                email: {
                    required: "Please enter your email",
                    email: "Please enter a valid email address"
                },
                captcha_text: {
                    required: "Please Enter Captcha",
                    remote: "The code you entered does not match the captcha"

                },
                gender: {
                    required: "Please select your gender"
                },
                terms: {
                    required: "Please accept the terms and conditions"
                }
            },
            submitHandler: function (form) {
                //form is valid, now submit it using ajax
                $.ajax({
                    type: "POST",
                    url: "submit.php",
                    data: $(form).serialize(),
                    success: function (response) {
                        //handle the response
                        alert(response);
                        window.location.reload();
                    }
                });
            }
        });
    });
</script>

                                                    

                                                

create a check-capthca.php file for checking the captcha:

You need to create a check-captcha.php file that will check the user input with the correct captcha code stored in the server-side session.

And the remote: URL will point to this check-captcha.php file.

In the check-captcha.php file, you can access the session variable, where you have stored the correct captcha code and compared it with the user input.


                                                    

                                                    

                                                    <?php
session_start(); 
if ($_POST['captcha_text'] == $_SESSION['captcha']) {
  echo 'true';
} else {
  echo 'false';
}

                                                    

                                                

Create submit.php code  with data sanitization:

Finally, you have to create submit.php and create mysqli connection and then sanitize the data then write insert query after successful data insert you can show a success message to the user according to you I am showing an alert message you can also retire page to thank you page.

You can also use session_destroy() after the user successfully submits the form or after a certain time to avoid the user using the same captcha multiple times. You can also use the session_regenerate_id() function after the user successfully submits the form or after a certain time to avoid session hijacking.



                                                    

                                                    

                                                    <?php
$host = "localhost"; 
$username = "root"; // your database username
$password = ""; // your database password
$db_name = "contact";  // your database name
//php_captcha
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if($_SERVER["REQUEST_METHOD"] == "POST"){
    $name = $_POST["name"];
    $email = $_POST["email"];
    $phone = $_POST["mobile"];
    $gender = $_POST["gender"];
    $terms = $_POST["terms"];
    // filter the data
    $name = $conn->real_escape_string(filter_var($name, FILTER_SANITIZE_STRING));
    $email = $conn->real_escape_string(filter_var($email, FILTER_SANITIZE_EMAIL));
    $phone = $conn->real_escape_string(filter_var($phone, FILTER_SANITIZE_NUMBER_INT));
    // insert the data into the database
    $sql = "INSERT INTO php_captcha (name, email, phone, gender, terms) VALUES ('$name', '$email', '$phone', '$gender', '$terms')";
    if ($conn->query($sql) === TRUE) {
        echo "Data inserted successfully";
        session_regenerate_id();
    } else {
        echo "Error inserting data: " . $conn->error;
    }
    $conn->close();
}
//echo "Data submitted";

                                                    

                                                

PHP input data filter and sanitization

In the above example code:

  • The filter_var function:  is used to filter the form data before inserting it into the database. 
  • The FILTER_SANITIZE_STRING filter: is used to sanitize the name and message fields, and 
  • the FILTER_SANITIZE_EMAIL filter is used to sanitize the email field. 
  • the FILTER_SANITIZE_NUMBER_INT filter is used to sanitize the number field. 
  • The real_escape_string function is used to escape any special characters in the data, which can help to prevent SQL injection attacks


Why you need to use jquery validation:

There are several reasons why you might want to use jQuery Validation for your forms:

User experience: Form validation helps ensure that users enter correct and complete information in the form fields. This enhances the user experience by providing instant feedback and preventing incorrect data from being submitted.

Data accuracy: By validating the form fields, you can ensure that the data entered into the form is accurate and meets specific criteria. This helps prevent errors and improve the quality of data collected.

Save server resources: With client-side form validation, you can save server resources by reducing the number of invalid submissions that need to be processed.

Customization: jQuery Validation provides a flexible and customizable framework for validating forms. You can define your own validation rules and error messages, and customize the plugin's behavior to fit your application's needs.

Cross-browser compatibility: jQuery Validation is a cross-browser-compatible plugin, which means it will work in most modern browsers, including Internet Explorer, Firefox, Chrome, and Safari. This helps ensure a consistent user experience across different devices and browsers.

Overall, jQuery Validation can help improve your forms' user experience, data accuracy, and efficiency.

Related Post

Leave a comment