Duminda Chamara

Thursday, September 10, 2009

How to create validation image in php

How to Create Validation Image in PHP?

Following example shows you how to create a random validation image using PHP .
Sometimes you may have seen there are some web forms that prompt you to enter validation code before you submit the form. That image comtains a peice of text that somewhat difficult to read. It is a validation image.

Captcha image is use to to ensure that the response is not generated by a computer. The process asking a user to entera simple text which is generated by a computer, in the form of image file format (jpg or png format). This text only can recogize by a human but not computers. So that using Captcha images ensure that the request is made by a human and not by automated computer program. CAPTCHA stands for "Completely Automated Public Turing Test to tell Computers and Humans Apart."

Random validation image is an image that containing a little text, number or combination of numbers and letters. before you submit a form you have to enter the text in the image to make it valida submission. Random validation images are useful when avoid spammers troubles to your site. Think that your site has a forum, guest book or user registration form to intract with your website. If a spammeror robot submits that form automatically frequently, it makes your webserver bussy. Also it waste valuable server resources. You can protect your web application from spammers or robots by using random validation images. You can genereate a random validation image on the fly using simple PHP script.

1. Example code for create a random validation image in PHP.

PHP Code

<?php session_start();

$width=100; $height=40; $font_size=30; $image=imagecreate($width,$height); $black=imagecolorallocate($image,221,238,255); $border_color=imagecolorallocate($image,0,0,255); $font_color=imagecolorallocate($image,74,0,0); $font="fonts/Vrinda.ttf"; $text=rand(10000,90000); $_SESSION['validation_code']=$text; imagesetthickness ( $image, 1 );

//create a border of the validation image. imageline($image,0,1,$width,1,$border_color); imageline($image,($width-1),1,($width-1),($height-1),$border_color); imageline($image,0,($height-1),$width,($height-1),$border_color); imageline($image,0,1,0,($height-2),$border_color);

for($i=0;$i<10;$i++){ imageline($image,0,($i*4),$width,($i*5),imagecolorallocate($image,74+($i*2),(10+$i),($i*10))); } imagettftext($image,$font_size,0,8,30,$font_color,$font,$text); header("Content-Type: image/png"); imagepng($image); imagedestroy($image); ?>

©-Copyright By Duminda Chamara JavaScript Validation


Anonymous said...

Image is not loaded