How to create a captcha in PHP

Home > Search > How-to
  by

PHP must be configured with the GD module.

Create a page named captcha.php, and place the following PHP in the page.

<?php
	session_start();
	$random_string = substr( md5(rand()), 0, 7);
	$_SESSION["random_string"] = $random_string;
	$image = imagecreatetruecolor(75, 24);
	$background_color = imagecolorallocate($image, 238, 238, 238);
	$font_color = imagecolorallocate($image, 128, 128, 128);
	imagefill($image, 0, 0, $background_color);
	imagestring($image, 5, 5, 5,  $random_string, $font_color);
	header("Cache-Control: no-cache, must-revalidate");
	header("Content-type: image/png");
	imagepng($image);
	imagedestroy($image);
?>

 

Navigating to www.example.com/captcha.php will produce a page with a 5 character string of random data.

 

The captcha can be placed inside of a form that you want to protect.

<form method="post" action="form_data.php">
  <img src="captcha.php" />
  <input type="text" name="captcha">
</form>	

 

When the form data is being processed, the user supplie captcha can be compared to the system captcha.

<?php 
	session_start();
	$user_captcha = $_POST["captcha"];
	$system_captcha = $_SESSION["random_string"];

	if($user_captcha == $system_captcha)
	{
      //Success markup
	}
	
	else 
	{
      //Failure markup
	}
?>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments