-
Image Generation
I should be pleased to have explained -
what it is in this php code that generates the four letter alphanumeric validate code in the image?:o
Code:
session_start();
$string = $_SESSION['secc'];
$str1 = substr($string,0,2);
$str2 = substr($string,2,2);
header("Content-type: image/jpeg");
$guestimg = @imagecreate(40, 20) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($guestimg,150,150,150);
$text_color = imagecolorallocate($guestimg,0,0,0);
imagestring($guestimg,5,2,0,$str1,$text_color);
$text_color = imagecolorallocate($guestimg,255,255,255);
imagestring($guestimg,6,19,5,$str2,$text_color);
imagejpeg($guestimg);
imagedestroy($guestimg);
-
Use imagettftext(), and rand() generates a random string.
http://php.net/imagettftext
http://php.net/rand
-
Thanks JShor,
I note your comment but same does not explain to me what is producing the random image detail as produced by the code! I do not see the imagettftext(), or the rand(). I am trying to get an understanding of the working of this piece of PHP. I can see what is producing the image size, and colour etc but not the alphanumeric detail!:o
-
Sorry, I completely misunderstood this thread.
I'll explain line-by-line.
PHP Code:
// This starts the session (the cookie that stores the random string will generate).
session_start();
// This is the session variable.
$string = $_SESSION['secc'];
// This generates two random strings.
$str1 = substr($string,0,2);
$str2 = substr($string,2,2);
// This outputs what the MIME type is (in this case, a JPEG image).
header("Content-type: image/jpeg");
// This creates the canvas for the image (40 pixels by 20 pixels).
$guestimg = @imagecreate(40, 20) or die("Cannot Initialize new GD image stream");
// This sets the background color for the image.
$background_color = imagecolorallocate($guestimg,150,150,150);
// This sets the color of the text for the image.
$text_color = imagecolorallocate($guestimg,0,0,0);
// This takes the random string generated in $str1 and places it in the image. It accepts
six arguments: the canvas varialbe ($guestimg), the font # (can be 1-6, in this case, 5), the X-offset (2), the Y-offset (0), the string ($str1), and the color of the text ($text_color) in that respective order.
imagestring($guestimg,5,2,0,$str1,$text_color);
// This sets the text color for the second string ($str2).
$text_color = imagecolorallocate($guestimg,255,255,255);
// This takes the random string generated in $str1 and places it in the image. It accepts
six arguments: the canvas varialbe ($guestimg), the font # (can be 1-6, in this case, 6), the X-offset (19), the Y-offset (5), the string ($str1), and the color of the text ($text_color) in that respective order.
imagestring($guestimg,6,19,5,$str2,$text_color);
// Outputs the image to the browser.
imagejpeg($guestimg);
// Finishes the image.
imagedestroy($guestimg);
Hope this explanation helped.
-
Hi JShor,
Thanks, a super response and even more than I expected.