本帖最后由 yaner 于 2024-11-30 17:06 编辑
Action.php 更新为汉字、数字随机显示一位数加法
- <?php
- namespace TypechoPlugin\LoginCaptcha;
- use Typecho\Widget;
- use Utils\Helper;
- use Widget\ActionInterface;
- class Action extends Widget implements ActionInterface
- {
- public function renderCaptcha()
- {
- Helper::security()->protect();
-
- // Ensure session is started
- if (session_status() == PHP_SESSION_NONE) {
- session_start();
- }
- $captcha = $this->generateCaptcha();
- $_SESSION['captcha'] = $captcha['code'];
- header('Content-type: image/png');
- imagepng($captcha['image']);
- imagedestroy($captcha['image']);
- exit;
- }
- private function generateCaptcha(): array
- {
- $num1 = rand(1, 9); // 一位数
- $num2 = rand(1, 9); // 一位数
- $code = $num1 + $num2;
- $num1Chinese = $this->numberToChinese($num1);
- $num2Chinese = $this->numberToChinese($num2);
- // 随机选择阿拉伯数字和汉字显示,保证至少有一个是汉字
- $rand = rand(0, 2);
- if ($rand == 0) {
- $question = "$num1 + $num2Chinese=?";
- } elseif ($rand == 1) {
- $question = "$num1Chinese + $num2=?";
- } else {
- $question = "$num1Chinese + $num2Chinese=?";
- }
- $width = 170; // Fixed width
- $height = 50; // Fixed height
- $image = imagecreatetruecolor($width, $height);
- // Enable transparency
- imagealphablending($image, false);
- imagesavealpha($image, true);
- // Allocate a transparent background
- $background_color = imagecolorallocatealpha($image, 255, 255, 255, 127);
- imagefill($image, 0, 0, $background_color);
- // Add noise to the background with random colors
- for ($i = 0; $i < 100; $i++) {
- $noise_color = imagecolorallocate($image, rand(100, 255), rand(100, 255), rand(100, 255));
- imagesetpixel($image, rand(0, $width), rand(0, $height), $noise_color);
- }
- // Add interference lines
- for ($i = 0; $i < 5; $i++) {
- $line_color = imagecolorallocate($image, rand(100, 255), rand(100, 255), rand(100, 255));
- imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color);
- }
- // Calculate the position to ensure the text is centered in the middle 80% area
- $textbox = imagettfbbox(20, 0, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'hylxjt.ttf', $question);
- $text_width = $textbox[2] - $textbox[0];
- $text_height = $textbox[7] - $textbox[1];
- $x = ($width - $text_width) / 2; // Center horizontally
- $y = ($height - $text_height) / 2; // Center vertically and adjust for font size
- $text_color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
- imagettftext($image, 20, 0, $x, $y, $text_color, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'hylxjt.ttf', $question);
- return array('image' => $image, 'code' => $code);
- }
- private function numberToChinese($num)
- {
- $chineseNumbers = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
- return $chineseNumbers[$num];
- }
- public function action()
- {
- // Empty action method
- }
- }
复制代码
感谢豆腐ru的基础代码,我就是瞎搞一下,不保证安全性,也不能自定义配置。
主要是记录在这,万一哪 天自用需要
|