Create simple captcha in PHP easily, simple tutorial to create image captcha using PHP, form captcha, example code & download script.

How To Create Simple Captcha In PHP

Very easy, using PHP Session and some PHP functions like rand() we will create simple captcha.

Live Demo

Simple Captcha.

Create Simple Captcha

We need 3 PHP files:

  1. index.php
  2. image.php
  3. form.php

Create “index.php” file and enter this code:

<?php

    // By Qassim Hassan, wp-time.com

    session_start(); // important

    $captcha = rand(111111,999999); // create random numbers

    $_SESSION['captcha'] = $captcha; // save random numbers inside captcha session

?>

<form method="post" action="form.php">
    <p>Captcha:</p>
    <p><img src="image.php?captcha_text=<?php echo $_SESSION['captcha']; ?>"></p>
    <p><input type="text" value="" name="my-captcha"></p>
    <p><input type="submit" value="Submit" name="submit"></p>
</form>

Now we have form and image, and we need to create “image.php” file, this file to create a new image, enter this code in “image.php” file:

<?php

    // By Qassim Hassan, wp-time.com

    session_start(); // important

    if( isset($_GET['captcha_text']) and isset($_SESSION['captcha']) ){ // if get captcha text and captcha session

        // Create Image

        $captcha_text = $_GET['captcha_text']; // get text from "captcha_text" parameter

        $image = imagecreate( 100, 32 ); // create new image, width is 100, and height is 32

        $background_color = imagecolorallocate( $image, 0, 0, 0 ); // background color RGB, black: 0, 0, 0

        $text_color = imagecolorallocate( $image, 255, 255, 255 ); // text color RGB, white: 255, 255, 255

        imagestring( $image, 4, 25, 8, $captcha_text, $text_color ); // font size is 4, and position from left is 25, and position from top is 8

        // Display Image

        header( "Content-type: image/png" );

        imagepng( $image );

        imagecolordeallocate( $text_color );

        imagecolordeallocate( $background_color );

        imagedestroy( $image );

    }

?>

Finally, create “form.php” file and enter this code:

<?php

    // By Qassim Hassan, wp-time.com

    session_start(); // important

    if( isset($_SESSION['captcha']) and $_POST['my-captcha'] == $_SESSION['captcha'] ){ // check if has captcha session and input "my-captcha" value equal captcha session value
        unset($_SESSION['captcha']); // remove captcha session, so the user cannot use the same number again!
        echo "Correct captcha! Thank you.";
    }

    else{ // if no captcha session or input "my-captcha" value is not equal captcha session value
        echo "Sorry! Captcha is invalid.";
    }

?>

Done.

To know the idea, read the instructions in all code.

Download

Download example script.