jacopovalanzano / php-captcha
便携式验证码。
1.7.26
2022-05-04 14:28 UTC
Requires
- php: ^5.4|^7.0|^8.0
- ext-gd: ^7.0
README
一个便携式PHP类,用于创建简单的验证码。一个文件。非常适合简单项目。
注意:此验证码并非对抗机器人的最终解决方案,但可以阻止狂热的攻击者。
例如,以下为 tesla.com 使用的 验证码 示例
微软 (live.com)
安装
使用composer安装,或使用 src 文件夹的内容。
composer require jacopovalanzano/php-captcha
需要PHP ^5.4 和 PHP-GD。
用法
验证码是一个二进制的jpeg图像,可以使用“image/jpeg”内容类型头进行渲染。
// Create a new Captcha $captcha = new Captcha("My super difficult to read string."); // Add 3 lines over and 3 behind the text, // then build the image. $captcha->linesFront(3)->linesBack(3)->build(175,50); // width, height // Returns a string containing the captcha passphrase $captcha->getPassphrase(); // Returns "My super difficult to read string." // Renders the captcha. $captcha->out();
示例
以下是一个简单的示例,解释了发送/检索验证码及其口令的过程
// This file represents the "www.example.com/get_captcha_image" url that generates our captcha // ... // A list of words $attributes = [ "easy", "green", "digital" ]; // One more list of words $nouns = [ "compare", "dungeon", "clip" ]; // Compose a phrase $words = $attributes[array_rand($attributes)]." ".$nouns[array_rand($nouns)]; // Create a new captcha with some random words $captcha = new Captcha($words); // Add 2 lines over and 5 behind the text, // then build the image. $captcha->linesFront(2)->linesBack(5)->build(175,50); // width, height // Save the captcha passphrase to session, so it can be retrieved later... $_SESSION["captcha_passphrase"] = $captcha->getPassphrase(); // Render the actual captcha image $captcha->out();
以下是需要验证的表单示例,如登录表单
<!-- ... --> <input type="email" name="email"> <input type="password" name="password"> <!-- Render the actual captcha image using the URL of our captcha-generator (see example above): --> <img id="captcha_image" src="www.example.com/get_captcha_image" alt="captcha"> <input type="text" name="captcha_passphrase"> <input type="submit" value="send">
或
echo '<img src="' . $captcha->inline() . '">';
将 $_SESSION["captcha_passphrase"] 与上述示例中从输入“captcha_passphrase”传递的值进行匹配,例如
// Compare the captcha passphrase with the one submitted if($_POST["captcha_passphrase"] !== $_SESSION["captcha_passphrase"]) { die("Wrong captcha!"); }
测试
贡献
欢迎提交拉取请求。