A CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. Captcha is one of the needed function in every web application.

The idea of this example is first image will be called form a random_image file and then load in form. The number of the captcha will be save in session. To make it security, the number will be md5().
Here is the way.
Step 1: Create file random.php
<?php
session_start();
create_image();
exit(); 

function create_image()
{ 

    $md5_hash = md5(rand(0,999));
    $security_code = substr($md5_hash, 15, 5);
    $_SESSION["security_code"] = $security_code;
    $width = 100;
    $height = 30;
    $image = ImageCreate($width, $height);
    $white = ImageColorAllocate($image, 255, 255, 255);
    $black = ImageColorAllocate($image, 0, 0, 0);
    ImageFill($image, 0, 0, $black);
    ImageString($image, 5, 30, 6, $security_code, $white);
    header("Content-Type: image/jpeg");
    ImageJpeg($image);
    ImageDestroy($image);
}
?>

Step3: create file index.php

<?php
session_start();

if(isset($_POST['ok']))
{
 if($_POST['txtCaptcha'] == NULL)
 {
  echo "Please enter your code";
 }
 else
 {
  if($_POST['txtCaptcha'] == $_SESSION['security_code'])
  {
   echo "Captcha valid";
  }
  else
  {
   echo "Captcha invalid";
  }
 }
}

?>
<form action="form.php" method=post>
<table>
  <tr>
    <td align="left">
      <label for="captcha">Captcha</label>
    </td>
    <td>
      <input type="text" name="txtCaptcha" maxlength="10" size="32" />
    </td>
    <td>
      <img src="random.php" />
    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>
      <input type=submit name=ok value="Check" />
    </td>
  </tr>
</table>
</form>

The image creates with functions: ImageCreate(),ImageColorAllocate(), ImageFill(), ImageString() . And then assign to view with the header.
This image will be called in index.php to display and captcha code will be saved in session. Each time when we submit the code, this code will be md5() and check to match with md5 code in session.