紫气东来 | 2024-09-21 21:03:05 | 编程 | 2
php图片验证码
一个简单的php图片验证码,显示两个数字,随机进行加法或者减法运算,计算得到的结果。
结果保存到$_SESSION["yzm"]中,当需要验证时可以进行验证。
图片中另外加入了3条干扰线。
<?php session_start(); $width = 100; $height = 25; $image = imagecreate($width, $height); $bg = imagecolorallocate($image, 240, 240, 240); $color = imagecolorallocate($image, 0, 0, 0); imagefilledrectangle($image, 0, 0, $width, $height, $bg); $num1 = mt_rand(43, 66); $num2 = mt_rand(10, 33); $op = mt_rand(0, 1) ? '+' : "-"; $yzm0 = $num1 . $op . $num2 . "="; $_SESSION["yzm"] = $op == "+" ? $num1 + $num2 : $num1 - $num2; for ($i = 0; $i < 3; $i++) { imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color); } $font_size = 22; $current_x = 5; foreach (str_split($yzm0) as $char) { $random_offset = mt_rand(-5, 5); imagestring($image, $font_size, $current_x + $random_offset, 5, $char, $color); $current_x += (int)($width / 6); } header("Content-Type: image/png"); imagepng($image); imagedestroy($image);