Tuesday, November 07, 2006

How to create security code image in PHP?

<?php
$string = rand ( 00000,99999 ) ;
$string = str_replace ( '2', 'F', $string ) ;
$string = str_replace ( '6', 'e', $string ) ;
$string = str_replace ( '7', 'L', $string ) ;
echo '<img src="securitycodeimage.php?code='.$string.'"/><br /> Code: '.$string;
?>

Securitycodeimage.php
---------------------
<?php
header ( "Content-type: image/gif" ) ;
$string = htmlspecialchars ( strip_tags ( stripslashes ( $_GET [ 'code' ] ) ) , ENT_QUOTES ) ;
$image = @imagecreate ( 50, 15 ) ;
$black = imagecolorallocate ( $image, 0, 0, 0 ) ;
$white = imagecolorallocate ( $image, 255, 255, 255 ) ;
imageline ( $image, 0, 7.5, 50, 7.5, $white ) ;
imagestring ( $image, 2, 10, 1, $string, $white ) ;
imagegif ( $image ) ;
imagedestroy ( $image ) ;
?>

No comments: