<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tony Bhimani's Blog &#187; security images</title>
	<atom:link href="http://www.tonybhimani.com/tag/security-images/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.tonybhimani.com</link>
	<description>Where I Share my Linux and Programming Experiences</description>
	<lastBuildDate>Sun, 01 Jun 2008 02:48:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating Captcha Images with PHP and the GD Library</title>
		<link>http://www.tonybhimani.com/2008/02/01/creating-captcha-images-with-php-and-the-gd-library/</link>
		<comments>http://www.tonybhimani.com/2008/02/01/creating-captcha-images-with-php-and-the-gd-library/#comments</comments>
		<pubDate>Sat, 02 Feb 2008 06:34:01 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[HOWTOs]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[captcha]]></category>
		<category><![CDATA[gd]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[security images]]></category>

		<guid isPermaLink="false">http://www.tonybhimani.com/2008/02/01/creating-captcha-images-with-php-and-the-gd-library/</guid>
		<description><![CDATA[A long time ago I wrote some code to create captcha images using PHP. The goal was to create similar or exact representations of the captcha&#8217;s used on Yahoo&#8217;s Overture. I really don&#8217;t have an answer why I chose their style except that it&#8217;s possible I liked the way they looked. I am sharing this [...]]]></description>
			<content:encoded><![CDATA[<p>A long time ago I wrote some code to create <a href="http://en.wikipedia.org/wiki/Captcha" title="Captcha definition on Wikipedia" target="_blank">captcha</a> images using PHP. The goal was to create similar or exact representations of the captcha&#8217;s used on Yahoo&#8217;s Overture. I really don&#8217;t have an answer why I chose their style except that it&#8217;s possible I liked the way they looked. I am sharing this code for creating the images but it&#8217;s up to you to create some logic in applying their use with HTML forms (I&#8217;ll give some hints at the end of this post).</p>
<p>This is the code to create the image. It returns an image resource identifier.  Note the use of a custom TrueType font &#8212;  you&#8217;ll need to change that line to the path of a font on your system.</p>
<pre class="code">&lt;?php
// generate captcha image - returns image handle
function captcha_image($code_string, $img_width=150, $img_height=40) {
  // seed srand
  srand((double)microtime()*1000000);

  // create image
  $im = @imagecreate($img_width, $img_height) or die("Cannot Initialize new GD image stream");

  // security code
  $security_code = $code_string;

  // define font
  $font = "/usr/fonts/ttf/Georgia.ttf";

  // create some colors
  $black = imagecolorallocate($im, 0, 0, 0);
  $white = imagecolorallocate($im, 255, 255, 255);
  $grey = imagecolorallocate($im, 128, 128, 128);

  // randomness, we need lots of randomness <img src='http://www.tonybhimani.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
  // background color -&gt; 1=black, 2=white, 3=grey (more colors can be added)
  // lines -&gt; black bg (1=white or 2=grey), white bg (1=black or 2=grey), grey bg (black only)
  $randval = rand(1, 3);
  if ($randval == 1) {
    $bgcolor = $black;
    $fontcolor = $white;
    $linecolor = ((rand(0, 1) == 0) ? $black : $white);
  } elseif ($randval == 2) {
    $bgcolor = $white;
    $fontcolor = $black;
    $linecolor = ((rand(0, 1) == 0) ? $black : $white);
  } else {
    $bgcolor = $grey;
    $fontcolor = $black;
    $linecolor = ((rand(0, 1) == 0) ? $black : $grey);
  }

  // line positioning and increment
  $x_start = rand(0, 10);
  $x_size = rand(5, 10);
  $y_start = rand(0, 10);
  $y_size = rand(5, 10);

  // fill with background color
  imagefill($im, 0, 0, $bgcolor);

  // initial x position
  $font_x = 10;

  // write text
  for ($i = 0; $i &lt; strlen($security_code); $i++) {
    // font size -&gt; 20 to 35
    $font_size = rand(25, 35);
    // font angle -&gt; -20 to +20
    $font_angle = rand(0, 20);
    if ($font_angle != 0) { if (rand(0, 1) == 0) { $font_angle = -$fone_angle; } }
    // font y position -&gt; if font_size &lt;= 27 then 30 to 35, if font_size &gt; 27 then 30 to 35
    if ($font_size &lt;= 27) { $font_y = rand(25, 30); } else { $font_y = rand(30, 35); }
    // write the text
    imagettftext($im, $font_size, $font_angle, $font_x, $font_y, $fontcolor, $font, $security_code{$i});
    // one more time to make it bolder
    imagettftext($im, $font_size, $font_angle, $font_x+1, $font_y+1, $fontcolor, $font, $security_code{$i});
    // next font x position
    $font_x += ($font_size + 5);
  }

  // draw horizontal lines
  for ($y = $y_start; $y &lt; $img_height; $y += $y_size) {
    imageline($im, 0, $y, $img_width, $y, $linecolor);
  }
  // draw vertical lines
  for ($x = $x_start; $x &lt; $img_width; $x += $x_size) {
    imageline($im, $x, 0, $x, $img_height, $linecolor);
  }

  // return captcha image handle
  return $im;
}
?&gt;</pre>
<p>We need a method for generating random four character strings when the captcha is created and displayed to the user. This function will do the trick.</p>
<pre class="code">&lt;?php
function secret_key($length=4) {
  $salt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  srand((double)microtime()*1000000);
  $i = 0;
  $skey = "";
  while ($i &lt; $length) {
    $num = rand() % strlen($salt);
    $tmp = substr($salt, $num, 1);
    $skey .= $tmp;
    $i++;
  }
  return $skey;
}
?&gt;</pre>
<p>With everything in place, we can generate the secret key, create the captcha, and finally display it to the user using this code.</p>
<pre class="code">&lt;?php
// set headers
header("Content-type: image/png");
header("Cache-Control: no-cache");
header("Pragma: no-cache");

// generate secret
$skey = secret_key();

// create captcha and output to browser as PNG image
$im = captcha_image($skey);
@imagepng($im);
@imagedestroy($im);
?&gt;</pre>
<p>Here is an example of the code in action. The style looks very similar to the images used on <a href="https://secure.overture.com/login.do" title="Yahoo's Overture" target="_blank">Yahoo&#8217;s Overture</a>.</p>
<p><strong><font size="+1">Captcha Demo »</font></strong>   <img src="http://www.tonybhimani.com/files/captcha/captcha.php" alt="Captcha" /></p>
<p>Now you know how to create a captcha, so what about verifying the input against the captcha value? This can be accomplished a variety of ways and everyone tends to have their preference.</p>
<ul>
<li>One method is to save the secret key in a session variable. As the image is created, store the key in a session variable and once the form is submitted, check the user&#8217;s value against the one stored in the session. If they match, proceed but if they fail, return an error and don&#8217;t process the form data.</li>
<li>If you don&#8217;t want to use sessions, you could try using temp files. Store the key in a temp file and pass some value as a query string identifying to the script that the key is in that file. Read in the key and <a href="http://www.php.net/manual/en/function.md5.php" title="PHP: md5 function reference" target="_blank">MD5</a> or <a href="http://www.php.net/manual/en/function.sha1.php" title="PHP: sha1 function reference" target="_blank">SHA1</a> crypt the key and save it in a hidden form field. When the form is submitted, compare the hashed key against the user input (which you will also hash). Process the form data if the keys match.</li>
</ul>
<p>You can download the provided source file. Use the PHP file as an image source in your HTML IMG tag.</p>
<pre class="code">&lt;img src="<span style="background-color: #ffff00">http://www.yourdomain.com/captcha.php</span>"&gt;</pre>
<p>Don&#8217;t forget to edit the path to the TrueType font you want to use in the <em>captcha_image</em> function. Failure to do so will lead to missing image characters.</p>
<p><strong>Source Files:</strong> <a href="http://www.tonybhimani.com/files/2008/02/captcha.zip" title="Captcha PHP Source Code">captcha.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.tonybhimani.com/2008/02/01/creating-captcha-images-with-php-and-the-gd-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
