captcha code in php example with code


Before start working with user input by accessing HTML forms, we need to ensure that these inputs are entered manually by a human. Or else, people can submit bulk unwanted data through “cron” like program execution or any tools, which will create serious issues like, increasing server load, getting spam data and etc.

For that, we can create special code called captcha using a PHP script to get rid of these issues. This article deals with some simple steps for creating such PHP captcha code.

Steps in Creating PHP captcha

  • Create captcha
  • Add captcha into HTML form
  • Compare captcha code

Now, we are going to get into the above steps one by one. For that, we have taken PHP contact form in which the captcha code is to be put to prevent from getting spam data.

Create captcha

For ease understanding, We can further split this step into the following list of functionalities we need to perform.

  • Start session to get PHP session_id before sending a header to the browser. This is for using PHP global variable, $_SESSION to store captcha code with an appropriate array index.

Generate random alphanumeric character string using PHP features.

Creating new image as target layer as we have done on resizing image using PHP. On top of this layer, we need to fill the random alphanumeric character string we have generated.

Fill captcha code into the image layer after adding properties like image background, text color and etc.

Sending image header with mime type to the browser.

So, the entire code to return captcha code to the target is shown below by recollecting the above steps. And, save this code as captcha_code.php

Add captcha into HTML Contact Form

To add PHP captcha code into the required HTML form, we need to refer the corresponding PHP file for the image tag src property. Here, we should add an image tag which refers captcha_code.php file, for the contact form. So, the HTML code for the contact form can be modified as follows.

Compare captcha Code

On form submit, we should verify user-entered the captcha code, by comparing it with the corresponding $_SESSION entry we have set while creating captcha. If match found, then, the user is recognized as human and allowed further to get access to the page. Otherwise, some negative acknowledgment will be sent. So, the following code should be added on top of the HTML code shown above.

On successful form submission, user feedback, query or anything entered by this contact form will be stored into the database table. For that, we need to fulfill the corresponding database requirements before executing this program.

Leave A Reply

Your email address will not be published.