//the form
<form action="file.php" method="post" >
<input type="text" id="name" name="name" placeholder="Name" />
<input type="text" id="email" name="email" placeholder="Email" />
<!-- CAPTCHA -->
<label for="CaptchaTxt"><img src="captcha.php" alt="Captcha Code" /></label>
<input type="text" name="CaptchaTxt" id="CaptchaTxt" placeholder="Enter the code above"/>
<!-- CAPTCHA -->
<button type="submit"></button>
</form>
//captcha.php
<?php
session_start();
$alphanum = "arjaysonbarantez1234567890";
// generate the verication code
$random = substr(str_shuffle($alphanum), 0, 4);
// create the hash for the random number and put it in the session
$_SESSION['img_code_val'] = md5($random);
// create the image
$image = imagecreate(45, 18);
// use white as the background image
$bgColor = imagecolorallocate ($image, 246, 241, 230);
// the text color is black
$textColor = imagecolorallocate ($image, 0, 0, 0);
// write the random number
imagestring ($image, 5, 5, 1, $random, $textColor);
// send several headers to make sure the image is not cached
// taken directly from the PHP Manual
// Date in the past
header("Expires: Mon, 09 Dec 1900 04:00:00 GMT");
// always modified
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
// send the content type header so the image is displayed properly
header('Content-type: image/jpeg');
// send the image to the browser
imagejpeg($image);
// destroy the image to free up the memory
imagedestroy($image);
?>
// file.php
<?php session_start(); ?>
<?php if ($_SESSION['img_code_val'] != md5($_POST['CaptchaTxt'])) {
$validcaptcha = 0;
} else {
error_reporting(E_ALL ^ E_NOTICE);
$validcaptcha = 1;
<?php if ($validcaptcha == 1) {
// do somenthing
} else {
// do something else
}
?>
Generate a four character captcha
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.