Current Location: Home> Latest Articles> How to Use PHP's imagefontwidth Function to Create an Auto-Width Image CAPTCHA System?

How to Use PHP's imagefontwidth Function to Create an Auto-Width Image CAPTCHA System?

M66 2025-07-10

When developing a website, CAPTCHA systems are a key method to prevent malicious registrations and bot attacks. PHP comes with a powerful GD library that makes it easy to create custom image CAPTCHAs. The imagefontwidth function helps dynamically calculate character width, enabling a responsive CAPTCHA image design that looks cleaner and more balanced.

This article provides a detailed guide on how to use PHP's imagefontwidth function to create a dynamic-width CAPTCHA image system.


1. Introduction to imagefontwidth

imagefontwidth is a function in PHP’s GD library used to return the width (in pixels) of a single character from a built-in font. Here's the basic syntax:

imagefontwidth(int $font): int

The $font parameter is an integer representing the font size, ranging from 1 to 5. The larger the number, the larger the font.

This function is often used with imagefontheight to accurately measure the space characters occupy.


2. Design Concept

The main steps to create a dynamically-sized CAPTCHA image are:

  1. Generate a CAPTCHA string (usually a random mix of letters and numbers)

  2. Calculate total CAPTCHA width
    Use imagefontwidth to get the width of one character, then multiply by the number of characters to get the total image width

  3. Create the canvas based on the width
    Use imagecreatetruecolor to create an image with the calculated width and desired height

  4. Draw CAPTCHA characters
    Write characters to the image sequentially from left to right

  5. Output the image and free resources


3. Implementation Example

Below is a full example demonstrating how to create a dynamic-width CAPTCHA using imagefontwidth:

<?php
// Generate a random CAPTCHA string
function generateCaptchaCode($length = 5) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Avoid easily confused characters
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $code;
}
<p>// Main function to create CAPTCHA image<br>
function createCaptchaImage($code) {<br>
$font = 5; // Use built-in font size 5<br>
$charWidth = imagefontwidth($font);<br>
$charHeight = imagefontheight($font);<br>
$padding = 10; // Horizontal padding</p>
$width = $charWidth * strlen($code) + $padding * 2;
$height = $charHeight + $padding * 2;

// Create image resource
$image = imagecreatetruecolor($width, $height);

// Define colors
$bgColor = imagecolorallocate($image, 255, 255, 255); // White background
$textColor = imagecolorallocate($image, 0, 0, 0);     // Black text
$noiseColor = imagecolorallocate($image, 100, 120, 180); // Noise color

// Fill background
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);

// Add noise dots
for ($i = 0; $i < 50; $i++) {
    imagesetpixel($image, random_int(0, $width), random_int(0, $height), $noiseColor);
}

// Draw CAPTCHA characters one by one
$x = $padding;
$y = $padding;
for ($i = 0; $i < strlen($code); $i++) {
    imagestring($image, $font, $x, $y, $code[$i], $textColor);
    $x += $charWidth;
}

// Output image header
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);

}

// Generate CAPTCHA string
$captchaCode = generateCaptchaCode(6);

// Output CAPTCHA image
createCaptchaImage($captchaCode);
?>


4. Notes and Extensions

  • Dynamic width: The code calculates the total image width by multiplying the character width (via imagefontwidth) with the number of characters and adding padding, allowing the image size to adapt automatically.

  • Font size: The example uses built-in font size 5. For better visuals, you can use imagettftext to load TrueType fonts, but this requires additional width calculations.

  • Security: After generating the CAPTCHA, you can store the string in a session for verification upon form submission.

  • Styling: Add more noise, curves, or change font colors to increase resistance to automated recognition.


5. Conclusion

With PHP's imagefontwidth function, you can accurately get the width of individual characters to create a CAPTCHA image with dynamic width. This method is simple and efficient for building basic adaptive CAPTCHA systems.

For more complex CAPTCHA effects, consider using other GD drawing functions or third-party CAPTCHA libraries.