Generate Captcha Image in PHP?
Generate CAPTCHA images in PHP for web security in 2025. Follow this easy guide.
How to Generate Captcha Image in PHP (Step by Step Guide for Beginners)
Do you want to protect your website from spam bots and fake submissions? Adding a Captcha is one of the easiest ways to make sure that only real humans can fill your forms. In this tutorial, we will learn how to generate a Captcha image in PHP step by step, even if you are a beginner.
This guide is written in very simple English so that anyone can follow. By the end of this article, you will be able to create your own Captcha system using PHP and the GD library.
1. What is a Captcha?
A Captcha is a small test that helps websites check if the visitor is a real human and not a computer bot. Bots are automatic programs that try to submit forms, create fake accounts, or post spam comments on websites.
The term CAPTCHA stands for:
Completely Automated Public Turing test to tell Computers and Humans Apart
In simple words, Captcha is a quick challenge like typing some letters from an image or solving a small puzzle. Humans can easily solve it, but bots usually fail.
2. Why Should You Use Captcha?
Captchas are very useful for many reasons:
- To stop spam comments on blogs and forums
- To protect website registration forms from fake accounts
- To secure online polls from automated votes
- To prevent dictionary attacks on login forms
- To reduce unwanted bot traffic and email spam
If your website has any kind of form (like contact form, sign-up form, or comment section), using a Captcha can save you from a lot of headache.
3. Types of Captcha
There are many types of Captcha tests, but the most common ones are:
- Image Captcha – User has to read letters/numbers from a distorted image and type them.
- Math Captcha – A small math question like “3 + 5 = ?” is shown.
- Audio Captcha – For visually impaired users, Captcha can be spoken as audio.
In this tutorial, we will focus on Image Captcha because it is the most popular and easy to implement in PHP.
4. How Captcha Works (Step by Step)
Before we jump into coding, let’s understand the basic flow of Captcha:
- Generate a random string (letters and/or numbers).
- Create an image and write the random string on it.
- Show the image to the user and ask them to type the text.
- Store the original text in a PHP session for verification.
- When the form is submitted, compare the typed text with the stored session text.
If both match, the user is human; otherwise, we reject the submission.
5. Step 1 – Create the Captcha Image (captcha.php)
First, create a new file called captcha.php. This file will generate a new Captcha image each time it is loaded.
<?php
session_start();
// Step 1: Generate random string with uppercase, lowercase, and numbers
// Ensure at least 1 uppercase, 1 lowercase, 1 number
$uppercase = chr(rand(65, 90)); // A-Z
$lowercase = chr(rand(97, 122)); // a-z
$number = chr(rand(48, 57)); // 0-9
// Remaining random characters from all types
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$ResultStr = $uppercase . $lowercase . $number;
for ($i = 0; $i < 3; $i++) { // 3 more chars for total 6
$ResultStr .= $characters[rand(0, strlen($characters) - 1)];
}
// Shuffle to randomize the position
$ResultStr = str_shuffle($ResultStr);
// Step 2: Create image background
$NewImage = imagecreatefromjpeg("captcha-background.jpg"); // Use a plain light image
$LineColor = imagecolorallocate($NewImage, 50, 50, 50); // Dark lines
$TextColor = imagecolorallocate($NewImage, 0, 0, 0); // Black text
// Step 3: Add some lines for extra security
imageline($NewImage, 1, 1, 40, 40, $LineColor);
imageline($NewImage, 1, 100, 60, 0, $LineColor);
// Step 4: Write random string on the image
imagestring($NewImage, 5, 30, 15, $ResultStr, $TextColor);
// Step 5: Save string in session
$_SESSION['captcha_key'] = $ResultStr;
// Step 6: Output the image
header("Content-type: image/jpeg");
imagejpeg($NewImage);
?>
Note: You need a background image like captcha-background.jpg for this example. It can be any simple light-colored image.

6. Step 2 – Display Captcha in HTML Form (index.php)
Now, create a simple form where the user will see the Captcha and enter the text.
<?php session_start(); ?>
<html>
<head><title>PHP Captcha Example</title></head>
<body>
<h2>Simple PHP Captcha Form</h2>
<form method="post" action="post.php">
<p>Type the text you see in the image below:</p>
<img src="captcha.php" alt="Captcha Image" /><br/><br/>
<input type="text" name="captcha" placeholder="Enter Captcha" required />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
Each time the page loads, a new Captcha image will appear automatically.
7. Step 3 – Validate Captcha Response (post.php)
Finally, we will check if the user typed the correct Captcha code.
<?php
session_start();
if (isset($_POST['Submit'])) {
$userInput = $_POST['captcha'];
$original = $_SESSION['captcha_key'];
if ($userInput === $original) {
echo "<h3>✅ Captcha Verified! You are a human.</h3>";
// Proceed with form actions (save data to database)
} else {
echo "<h3>❌ Wrong Code Entered! Please try again.</h3>";
}
}
?>
8. Make Your Captcha More Secure with Mixed Characters, Lines, and Dots
The basic Captcha works fine, but it can still be weak if:
- Lines are always in the same place
- Bots can guess the pattern easily
To create a more secure Captcha, we can:
- Add random lines in different positions each time
- Add random dots (noise) to confuse bots
- Randomize the text position on the image
- Make sure the string always has all three types of characters
Here’s an updated Captcha generation code:
<?php
session_start();
// Step 1: Generate random string with at least 1 uppercase, 1 lowercase, 1 number
$uppercase = chr(rand(65, 90)); // A-Z
$lowercase = chr(rand(97, 122)); // a-z
$number = chr(rand(48, 57)); // 0-9
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$ResultStr = $uppercase . $lowercase . $number;
for ($i = 0; $i < 3; $i++) { // 3 more chars for total 6
$ResultStr .= $characters[rand(0, strlen($characters) - 1)];
}
// Shuffle to randomize positions
$ResultStr = str_shuffle($ResultStr);
// Step 2: Create Captcha image
$NewImage = imagecreatefromjpeg("img.jpg");
$LineColor = imagecolorallocate($NewImage, 50, 50, 50); // Dark lines
$DotColor = imagecolorallocate($NewImage, 120, 120, 120); // Noise dots
$TextColor = imagecolorallocate($NewImage, 0, 0, 0); // Black text
$width = imagesx($NewImage);
$height = imagesy($NewImage);
// Step 3: Add random lines
for ($i = 0; $i < 6; $i++) {
imageline(
$NewImage, rand(0, $width), rand(0, $height),
rand(0, $width), rand(0, $height), $LineColor
);
}
// Step 4: Add random dots (noise)
for ($i = 0; $i < 300; $i++) {
imagesetpixel($NewImage, rand(0, $width), rand(0, $height), $DotColor);
}
// Step 5: Place text with font size 5 (max built-in)
imagestring($NewImage, 5, rand(30, 60), rand(15, 25), $ResultStr, $TextColor);
// Step 6: Store in session
$_SESSION['captcha_key'] = $ResultStr;
// Step 7: Output image
header("Content-type: image/jpeg");
imagejpeg($NewImage);
?>
🔹 Why This is Stronger
- Mixed characters (A-Z, a-z, 0-9) make it harder for bots to guess
- Guaranteed at least one of each type increases security
- Random lines and dots break automated text recognition (OCR)
- Random placement of text ensures Captcha is unpredictable
🔹 Things You Can Customize
- Captcha Length: Change loop to generate 5, 6, or 7 characters
- Lines: Increase/decrease the number of lines
- Dots: Adjust noise count for more/less difficulty
- Image Size: Use bigger background for larger fonts
- Colors: Change text/line colors for better readability
Remember, a Captcha should be easy for humans but hard for bots. Test different lengths, colors, and noise levels to balance security and user experience.
9. Common Issues and Tips
- Blank Image? Make sure the GD library is enabled in your PHP server.
- Captcha not changing? Clear your browser cache or add
?rand=to the image URL. - Session not working? Always call
session_start()at the top of all files.
10. Conclusion
That’s it! You have learned how to generate and validate a simple Captcha in PHP. This method can protect your website forms from spam bots and make your website more secure.
With small improvements like adding numbers, using better fonts, and adding noise, you can make your Captcha more effective. If you want even better security, you can also integrate services like Google reCAPTCHA in the future.
Happy Coding! 🎉
0 Comments