Skip to content Skip to sidebar Skip to footer

PHP creating and using captcha – Best and simple way

Reading Time: < 1 minute

How to create simple but powerful captcha code using php.Here is a example of use captcha code to the form to avoid spams.I’ll describes how to create & use captcha code using php.

This is the contact form.

'; ?> '.$success.'
'; ?>




Are you human?

Not readable? Change text.

This is the php code to handle the submit process.Add this code form submitted page.

Note: Every time captcha code is keeping as a session variable.Because in the form validation process, validate captcha is correct or not with comparing session captcha value and form submitted value.
You already noted captcha.php file.It is generated captcha code by creating image using php.

captcha.php file

If you want to change font in the captcha, keep your font file in the fonts folder.
If you want to put both letters and numbers into the captcha code you can do it using following function.
I’ll generate captcha code with mixing of letters and numbers.

	function generateCode($characters) {
		/* list all possible characters, similar looking characters and vowels have been removed */
		$possible = '123456789BCDGHJKMNPQRSTUVWXYZ';
		$code = '';
		$i = 0;
		while ($i < $characters) {
			$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
		return $code;

How to call to this function ?

$characters=5; // number of characters to display
$string = generateCode($characters);

That's only.
View Demo

Download PHP creating and using captcha Example (160 KB)