57 lines
1.5 KiB
Markdown
57 lines
1.5 KiB
Markdown
|
Here is some example code for implementing a CAPTCHA, using the gd extension to create a server-rendered, randomized image.
|
||
|
|
||
|
```php
|
||
|
<?php
|
||
|
// Start the session to store the CAPTCHA answer
|
||
|
session_start();
|
||
|
|
||
|
// Define the image dimensions
|
||
|
$width = 200;
|
||
|
$height = 60;
|
||
|
|
||
|
// Create the image resource
|
||
|
$image = imagecreatetruecolor($width, $height);
|
||
|
|
||
|
// Define colors
|
||
|
$bg_color = imagecolorallocate($image, 255, 255, 255); // White background
|
||
|
$text_color = imagecolorallocate($image, 0, 0, 0); // Black text
|
||
|
$noise_color = imagecolorallocate($image, 100, 100, 100); // Gray for noise
|
||
|
|
||
|
// Fill the background
|
||
|
imagefill($image, 0, 0, $bg_color);
|
||
|
|
||
|
// Generate a random math equation (e.g., 3 + 5)
|
||
|
$num1 = rand(1, 9);
|
||
|
$num2 = rand(1, 9);
|
||
|
$operator = rand(0, 1) ? '+' : '-'; // Randomly choose addition or subtraction
|
||
|
$equation = "$num1 $operator $num2 = ?";
|
||
|
$answer = $operator == '+' ? ($num1 + $num2) : ($num1 - $num2);
|
||
|
|
||
|
// Store the answer in the session
|
||
|
$_SESSION['captcha'] = $answer;
|
||
|
|
||
|
// Add noise to the image (random dots)
|
||
|
for ($i = 0; $i < 1000; $i++) {
|
||
|
imagesetpixel($image, rand(0, $width), rand(0, $height), $noise_color);
|
||
|
}
|
||
|
|
||
|
// Set the path to the ZXX font
|
||
|
$font = __DIR__ . '/fonts/ZXX-Regular.ttf'; // Path to the ZXX font file
|
||
|
|
||
|
// Add the math equation using ZXX font
|
||
|
$font_size = 30;
|
||
|
$x = 20;
|
||
|
$y = 40;
|
||
|
imagettftext($image, $font_size, rand(-10, 10), $x, $y, $text_color, $font, $equation);
|
||
|
|
||
|
// Output the image as PNG
|
||
|
header('Content-Type: image/png');
|
||
|
imagepng($image);
|
||
|
|
||
|
// Free the image resource
|
||
|
imagedestroy($image);
|
||
|
?>
|
||
|
```
|
||
|
|
||
|
https://github.com/kawaiidesune/zxx
|