<?php

#
# Basic CAPTCHA example
#

// Initiate session support
session_start();

// Create a new captcha image
if (isset($_GET['captcha'])) {
    
// Construct an array of allowed characters
    
$characters array_merge(
        
range('a''z'),
        
range('A''Z'),
        
range(19)
    );

    
// Pick 5 random indices to construct the captcha string
    
$indices array_rand($characters5);
    
$captcha '';
    foreach (
$indices as $index) {
        
$captcha .= $characters[$index];
    }

    
// Create a 100*30 image
    
$im imagecreate(10030);

    
// White background and blue text
    
$bg imagecolorallocate($im255255255);
    
$textcolor imagecolorallocate($im00255);

    
// Write the string to the image
    
imagestring($im5256$captcha$textcolor);

    
// Update session with the captcha string
    
$_SESSION['captcha'] = $captcha;

    
// Output the image
    
header("Content-Type: image/gif");
    
imagegif($im);
    exit;
}

// Set response
$response '';

// Validate the input
if (isset($_SESSION['captcha']) && isset($_POST['mycaptcha'])) {
    if (
$_SESSION['captcha'] == $_POST['mycaptcha']) {
        
$response '<div style="color:green;font-weight:bold">CAPTCHA OK</div>';
    } else {
        
$response '<div style="color:red;font-weight:bold">CAPTCHA NOK</div>';
    }
}

?>
<html>
    <head>
        <title> CAPTCHA Demo </title>
        <style type="text/css">
            img { border: 1px solid black }
        </style>
    </head>
    <body>
        <?php print $response ?>
        <form method="post" action="<?php print $_SERVER['PHP_SELF'?>">
            <table>
                <tr>
                    <td>
                        <img src="<?php print $_SERVER['PHP_SELF'?>?rnd=<?php print time() ?>&captcha=1" 
                             width="100" height="30" />
                    </td>
                    <td>
                        Captcha: <input type="text" name="mycaptcha" />
                    </td>
                    <td>
                        <input type="submit" />
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>