make a very good and safe captcha with with php
- User
make a very good and safe captcha with with php
- Assistant
make a very good and safe captcha with with php
Creating a CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) involves generating an image or challenge that is easy for humans to solve but difficult for bots. In PHP, you can create a simple CAPTCHA using the GD library to generate images. Below is an example code snippet to create a text-based CAPTCHA:
<?php
session_start();
// Settings
$width = 120;
$height = 40;
$length = 6;
$font_size = 18;
$captcha_text = '';
// Generate a random string for the CAPTCHA
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
for ($i = 0; $i < $length; $i++) {
$captcha_text .= $characters[rand(0, strlen($characters) - 1)];
}
// Store the CAPTCHA text in the session
$_SESSION['captcha'] = $captcha_text;
// Create the image
$image = imagecreatetruecolor($width, $height);
// Allocate colors
$background_color = imagecolorallocate($image, 255, 255, 255); // white
$text_color = imagecolorallocate($image, 0, 0, 0); // black
$line_color = imagecolorallocate($image, 64, 64, 64); // grey
// Fill the background
imagefilledrectangle($image, 0, 0, $width, $height, $background_color);
// Add some random lines for noise
for ($i = 0; $i < 5; $i++) {
imageline($image, rand(0, $width), rand(0, $height),
rand(0, $width), rand(0, $height), $line_color);
}
// Add the text to the image
$x = 10;
$y = 30;
imagestring($image, $font_size, $x, $y, $captcha_text, $text_color);
// Set the header for the image
header('Content-type: image/png');
// Output the image as a PNG
imagepng($image);
// Clean up
imagedestroy($image);
?>
Create a simple HTML form to display the CAPTCHA image and provide an input field for users to enter the text they see:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CAPTCHA Example</title>
</head>
<body>
<form action="verify_captcha.php" method="post">
<p>Please enter the text you see in the image below:</p>
<img src="captcha.php" alt="CAPTCHA Image">
<br><br>
<input type="text" name="captcha_input" required>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In the verify_captcha.php file, you will check if the input the user provided matches the text generated in captcha.php:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$user_input = $_POST['captcha_input'];
if ($user_input == $_SESSION['captcha']) {
echo 'CAPTCHA verification successful!';
} else {
echo 'CAPTCHA verification failed. Please try again.';
}
}
?>
phpinfo(); and looking for a section on GD support.This basic example should give you a good starting point for CAPTCHA implementation using PHP.
Not yet included in a published release.