A contact form is a web page element that allows users to send messages or inquiries to website administrators. In PHP, contact forms are commonly used for user engagement and feedback collection. In this blog, we will discuss how can we create a custom captcha and contact form using PHP.
What is a CAPTCHA?
A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a security measure designed to distinguish between human users and automated bots. It typically involves challenges like deciphering distorted text, solving puzzles, or recognizing objects in images.
Why Use a Custom CAPTCHA?
Custom CAPTCHAs are essential because they can be tailored to your website’s specific needs and are often more secure than generic solutions.
Building the Custom CAPTCHA
A CAPTCHA typically requires users to solve a challenge that is easy for humans but difficult for bots. Here’s how to create a custom CAPTCHA:
Generating a Random String
To begin, generate a random string of characters that will serve as the CAPTCHA challenge. You can use PHP’s rand() function to create a random alphanumeric string of a specified length.
Storing the CAPTCHA
Store the generated CAPTCHA string in a session variable. This will allow you to compare the user’s input with the stored CAPTCHA later.
Displaying the CAPTCHA
Create an image or text representation of the CAPTCHA and display it to the user. You can use the GD library to generate CAPTCHA images or simply render the text on the page.
Verifying the User’s Input
When the user submits the form, compare their input with the stored CAPTCHA. If they match, the user is verified as a human.
Setting Up the HTML Structure
To begin, create a basic HTML structure that includes the necessary form fields such as Name, Email, Phone, and Message.
<div class="container mt-3 mb-3"> <div class="row d-flex justify-content-center"> <div class="col-xxl-5 col-lg-5 col-md-5 col-sm-12 mb-5 mb-lg-0"> <div class="hire-box-form"> <div class="p-5 shadow-5"> <h2 class="fw-bold h4">Let's all work together to win!</h2> <h5 class="mb-5 h6">Let's talk about your ideal project.</h5> <form id="contact-form"> <!-- Name input --> <div class="form-outline mb-4"> <label class="form-label" for="form3Example3">Name <span class="fw-bold text-danger">*</span></label> <div class="input-group"> <span class="input-group-text" id="basic-addon1"> <i class="fa-solid fa-user"></i> </span> <input type="text" id="name" class="form-control" placeholder="Name" autocomplete="off" /> </div> </div> <!-- Email input --> <div class="form-outline mb-4"> <label class="form-label" for="form3Example3">Email address <span class="fw-bold text-danger">*</span></label> <div class="input-group"> <span class="input-group-text" id="basic-addon1"> <i class="fa-solid fa-envelope"></i> </span> <input type="text" id="email" class="form-control" placeholder="Email address" autocomplete="off" /> </div> </div> <!-- Phone input --> <div class="form-outline mb-4"> <label class="form-label" for="form3Example3">Phone Number <span class="fw-bold text-danger">*</span></label> <div class="input-group"> <span class="input-group-text" id="basic-addon1"> <i class="fa-solid fa-phone"></i> </span> <input type="text" id="phone" class="form-control" placeholder="Phone Number" autocomplete="off" /> </div> </div> <!-- Counry Select --> <div class="mb-3"> <label class="form-label" for="form3Example3">Service <span class="fw-bold text-danger">*</span></label> <select class="form-select form-control" id="service"> <option selected value="">Select Service</option> <option value="Web Development">Web Development</option> <option value="Web Designing">Web Designing</option> <option value="WordPress Development">WordPress Development</option> <option value="SEO">SEO</option> <option value="Digital Marketing">Digital Marketing</option> </select> </div> <div class="mb-3"> <label class="mb-1">Your Message <span class="fw-bold text-danger">*</span></label> <textarea class="form-control" placeholder="Mesage" rows="4" id="msg"></textarea> </div> <div class="mb-3 d-flex"> <?php $random = substr(md5(mt_rand()), 0, 7); ?> <input type="text" name="" class="form-control" id="div-to-refresh" value="<?php echo $random; ?>" readonly> <button class="btn-sm btn btn-secondary refresher "><i class="fa-solid fa-arrows-rotate text-white"></i></button> </div> <div class="mb-3 d-flex"> <input type="text" name="cc" id="cc" class="form-control" placeholder="Enter Captcha Code"> </div> <!-- Submit button --> <div class="d-flex justify-content-center mb-3"> <button type="submit" class="btn btn-outline-success w-75"> Send Message </button> </div> </form> </div> </div> </div> </div> </div>
CSS Styling:
<style type="text/css"> body{ margin: 0; padding: 0; background-image: url('bg.jpg'); background-size: cover; } :root { --lightGreen: #08ae8d; --darkGreen: #37ab75; --blue: #22388b; --dkbg: #13141c; --borderClr: #e6e6e6; } input[type="text"], input[type="email"], input[type="number"], input[type="search"], textarea { border: 1px solid var(--borderClr); border-radius: 5px; outline: none !important; box-shadow: none !important; } input[type="text"], input[type="email"], input[type="number"], textarea:focus { outline: none !important; } select.form-control { border: 2px solid var(--borderClr); border-radius: 3px; outline: none !important; box-shadow: none !important; } textarea { border: 1px solid var(--borderClr) !important; border-radius: 30px; outline: none !important; box-shadow: none !important; } .hire-box-form { border-radius: 3px; overflow: hidden; box-shadow: 0px 0px 15px rgb(0 0 0 / 10%); background-color: #ffffff; transition: 0.5s ease-in; border: 2px solid #eee; color: #000; transform: translateY(5px); height: 100%; } .hire-box-form h2 { color: var(--blue); } .hire-box-form label { color: var(--blue); font-weight: 700; } .hire-box-form .cntry-code { font-size: 13px; } .hire-box-form i { color: var(--blue); font-weight: 700; } .hire-box-form h5 { color: var(--darkGreen); } .hire-box-form input { border: 1px solid var(--borderClr); outline: none !important; font-size: 14px; padding: 10px 6px 10px 7px; } .hire-box-form select { border: 1px solid var(--borderClr); outline: none !important; font-size: 14px; padding: 10px 6px 10px 7px; box-shadow: none !important; } .hire-box-form select:focus { outline: var(--borderClr) !important; border: 1px solid var(--borderClr) !important; } .hire-box-form input:focus { outline: var(--borderClr) !important; border: 1px solid var(--borderClr) !important; } .hire-us-data { padding: 20px; } .hire-us-data h1 { color: var(--blue); font-weight: 700; } .hire-us-data span { color: var(--darkGreen); } .hire-us-data p { text-align: justify; text-justify: inter-word; } </style>
PHP Backend Configuration
Create a PHP script to process the form data and send it to your desired email address.
<?php $to = "yourmail@gmail.com"; $from = $_POST['email']; $name = $_POST['name']; $phone = $_POST['phone']; $service = $_POST['service']; $cmessage = $_POST['msg']; $headers = "From: " . $from . "\r\n"; $headers .= "Reply-To: ". $from . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $subject = $from." Want ".$service ." service"; $body = '<html><body>'; $body .= "<h5>Name: <span style='font-weight: bold; '>" .$name. "</span></h5>"; $body .= "<h5>Email: <span style='font-weight: bold; '>" .$from. "</span></h5>"; $body .= "<h5>Phone: <span style='font-weight: bold; '>" .$phone. "</span></h5>"; $body .= "<h5>Service: <span style='font-weight: bold; '>" .$service. "</span></h5>"; $body .= "<h5>Message: <span style='font-weight: bold; '>" .$cmessage. "</span></h5>"; $body .= '</body></html>'; $send = mail($to, $subject, $body, $headers); if ($send) { echo json_encode(array("statusCode"=>200)); } else { echo json_encode(array("statusCode"=>201)); } ?>
Adding jQuery for Ajax Functionality
Integrate jQuery to make an Ajax request, allowing you to submit the form without refreshing the page. This results in a smoother user experience.
<script> $(document).ready(function() { $('#contact-form').on('submit', function(e) { e.preventDefault(); var name = $('#name').val(); var email = $('#email').val(); var service = $('#service').val(); var phone = $('#phone').val(); var msg = $('#msg').val(); var cc = $('#cc').val(); var code = $('#div-to-refresh').val(); if (name == "") { swal("Error", "Name Is Required!", "error"); }else if(email == ""){ swal("Error", "Email Is Required!", "error"); }else if(phone == ""){ swal("Error", "Phone No is Required!", "error"); }else if(service == ""){ swal("Error", "Select Product !", "error"); }else if(cc == ""){ swal("Error", "Captcha Code Is Rquired!", "error"); }else if(cc != code){ swal("Error", "Captcha Code Is Incorrect!", "error"); }else { $.ajax({ url: "contact-process", type: "POST", data: { name: name, email: email, type: type, stype: stype, cod: cod, dc: dc, msg: msg }, cache: false, success: function(dataResult) { var dataResult = JSON.parse(dataResult); if(dataResult.statusCode==200){ swal("Message Sent", "Message Sent Successfully!", "success"); $('#contact-form').trigger("reset"); } else if(dataResult.statusCode==201){ swal("Error", "Something Went Wrong!", "error"); } } }); } }); }); </script> <script type="text/javascript"> $(document).ready(function (e) { $(document).on('click', '.refresher', function (e) { e.preventDefault(); $.ajax({ url: 'result-div-refresh.php', method: "GET", dataType: 'json', success: function(response) { $('#div-to-refresh').val(response); } }); }); }); </script>
Conclusion
Implementing a custom CAPTCHA and contact form in PHP is a proactive step towards fortifying your website’s defenses against automated spam and ensuring a smooth user experience. So, roll up your sleeves, follow the steps outlined in this guide, and watch your website’s security and user engagement levels soar.
For a comprehensive guide on creating a contact form with PHP and jQuery AJAX, check out this PHP Contact Us Form with jQuery AJAX tutorial.
Libraries Used in Project:
Source Code: