PHP Tutorial

PHP Flow Control

PHP Functions

PHP String

PHP Array

PHP Date Time

PHP Object Oriented

Regular Expression

PHP Cookie & Session

PHP Error & Exception handling

MySQL in PHP

PHP File Directory

PHP Image Processing

PHP Generates Graphic Verification Code

Here's a simple tutorial on how to generate a graphic verification code, often known as a CAPTCHA, using PHP.

  • Create a new PHP file (let's call it captcha.php) and open it in your favorite text editor.
  • First, start a session. It's necessary because we'll store the CAPTCHA text in a session variable.
<?php
session_start();
?>
  • Then, define the basic parameters for your CAPTCHA image:
<?php
$width = 200;
$height = 60;
$font_size = 20;
$total_characters = 5;
  • Next, create an image using the imagecreatetruecolor() function, and define the color for the background and the text:
$image = imagecreatetruecolor($width, $height);

$background_color = imagecolorallocate($image, 255, 255, 255); // white
$text_color = imagecolorallocate($image, 0, 0, 0); // black

imagefilledrectangle($image, 0, 0, $width, $height, $background_color);
  • Now, generate a random string and draw it on the image. Here we are using a simple alphanumeric string:
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_string = '';
for ($i = 0; $i < $total_characters; $i++) {
    $random_string .= $characters[rand(0, strlen($characters) - 1)];
}

// Save the CAPTCHA string into a session variable
$_SESSION['captcha_text'] = $random_string;

$font = 'arial.ttf'; // Path to your font file

imagettftext($image, $font_size, 0, 15, 30, $text_color, $font, $random_string);

Remember, the path to the font file is relative to the script generating the image.

  • Finally, output the image with proper headers:
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

Put all together:

<?php
session_start();

$width = 200;
$height = 60;
$font_size = 20;
$total_characters = 5;

$image = imagecreatetruecolor($width, $height);

$background_color = imagecolorallocate($image, 255, 255, 255); // white
$text_color = imagecolorallocate($image, 0, 0, 0); // black

imagefilledrectangle($image, 0, 0, $width, $height, $background_color);

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_string = '';
for ($i = 0; $i < $total_characters; $i++) {
    $random_string .= $characters[rand(0, strlen($characters) - 1)];
}

$_SESSION['captcha_text'] = $random_string;

$font = 'arial.ttf'; 

imagettftext($image, $font_size, 0, 15, 30, $text_color, $font, $random_string);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

You can then include this CAPTCHA image in your HTML form by using an image tag:

<img src="captcha.php" />

And when the form is submitted, you can check the user's input against the $_SESSION['captcha_text'] value to verify if they entered the correct CAPTCHA.

  1. Creating graphic verification codes in PHP:

    • Use the GD library to generate random verification codes.
    <?php
    session_start();
    
    $verificationCode = generateVerificationCode();
    $_SESSION['verification_code'] = $verificationCode;
    
    $image = createCaptchaImage($verificationCode);
    header('Content-Type: image/png');
    imagepng($image);
    imagedestroy($image);
    
    function generateVerificationCode($length = 6) {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $code;
    }
    
    function createCaptchaImage($text) {
        $imageWidth = 150;
        $imageHeight = 50;
        $image = imagecreate($imageWidth, $imageHeight);
        $backgroundColor = imagecolorallocate($image, 255, 255, 255);
        $textColor = imagecolorallocate($image, 0, 0, 0);
    
        // Add noise or distortion effects if desired
    
        imagettftext($image, 20, 0, 10, 30, $textColor, 'arial.ttf', $text);
        return $image;
    }
    
  2. Using GD library to generate captcha in PHP:

    • Utilize the GD library functions to create captcha images.
    <?php
    $verificationCode = generateVerificationCode();
    $image = createCaptchaImage($verificationCode);
    header('Content-Type: image/png');
    imagepng($image);
    imagedestroy($image);
    
    // Functions from the previous example
    
  3. Adding security with graphic verification in PHP forms:

    • Implement a captcha system to enhance form security.
    <?php
    session_start();
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $userInput = $_POST['captcha'];
        $verificationCode = $_SESSION['verification_code'];
    
        if ($userInput === $verificationCode) {
            // Captcha verification successful
        } else {
            // Captcha verification failed
        }
    }
    
  4. Customizing and styling captcha images in PHP:

    • Adjust colors, fonts, and other parameters for customization.
    <?php
    function createCaptchaImage($text) {
        $imageWidth = 150;
        $imageHeight = 50;
        $image = imagecreate($imageWidth, $imageHeight);
        $backgroundColor = imagecolorallocate($image, 200, 220, 230);
        $textColor = imagecolorallocate($image, 0, 0, 0);
    
        imagettftext($image, 20, 0, 10, 30, $textColor, 'arial.ttf', $text);
        return $image;
    }
    
  5. PHP captcha code examples:

    • Examples of using captcha in PHP for form protection.
    <?php
    // Example HTML form
    ?>
    <form method="post" action="process_form.php">
        <label for="captcha">Enter the code:</label>
        <img src="captcha.php" alt="Captcha Image">
        <input type="text" name="captcha" required>
        <button type="submit">Submit</button>
    </form>
    <?php
    // PHP processing code
    
  6. Refreshing or reloading captcha images in PHP:

    • Allow users to refresh the captcha if needed.
    <?php
    session_start();
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $verificationCode = generateVerificationCode();
        $_SESSION['verification_code'] = $verificationCode;
    
        $image = createCaptchaImage($verificationCode);
        header('Content-Type: image/png');
        imagepng($image);
        imagedestroy($image);
    }
    
  7. Integrating captcha with user registration in PHP:

    • Enhance user registration with captcha verification.
    <?php
    session_start();
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $userInput = $_POST['captcha'];
        $verificationCode = $_SESSION['verification_code'];
    
        if ($userInput === $verificationCode) {
            // Captcha verification successful, process user registration
        } else {
            // Captcha verification failed
            echo "Captcha verification failed.";
        }
    }
    
  8. Verifying user input with PHP captcha codes:

    • Validate user input against the captcha code.
    <?php
    session_start();
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $userInput = $_POST['captcha'];
        $verificationCode = $_SESSION['verification_code'];
    
        if ($userInput === $verificationCode) {
            // Captcha verification successful
        } else {
            // Captcha verification failed
        }
    }
    
  9. Anti-bot techniques using graphic verification in PHP:

    • Use captcha to prevent automated bot submissions.
    <?php
    // Add captcha to forms to prevent bot submissions
    // Example HTML form
    ?>
    <form method="post" action="process_form.php">
        <label for="captcha">Enter the code:</label>
        <img src="captcha.php" alt="Captcha Image">
        <input type="text" name="captcha" required>
        <button type="submit">Submit</button>
    </form>
    <?php
    // PHP processing code