Home > Article > Backend Development > How to use PHP to implement human-machine verification code
Human-machine verification code is a commonly used form of verification code, which can effectively prevent malicious robot attacks and malicious registration. As a server-side language, PHP is very suitable for implementing human-machine verification code functions. In this article, we will introduce how to implement human-machine verification code using PHP.
The following is a code example for generating a verification code image:
<?php session_start(); $code = rand(1000, 9999); $_SESSION["code"] = $code; $width = 100; $height = 50; $image = imagecreatetruecolor($width, $height); $textColor = imagecolorallocate($image, 0, 0, 0); //设置文本颜色 $bgColor = imagecolorallocate($image, 255, 255, 255); //设置背景颜色 imagefilledrectangle($image, 0, 0, $width, $height, $bgColor); //绘制矩形背景 //绘制验证码字符串 $font = 'arial.ttf'; //字体 $fontSize = 24; //字体大小 $x = 20; //x轴位置 $y = 30; //y轴位置 for ($i = 0; $i < 4; $i++) { $char = substr(str_shuffle("ABCDEFGHJKMNPQRSTUVWXYZ23456789"), 0, 1); imagettftext($image, $fontSize, rand(-15, 15), $x, $y, $textColor, $font, $char); $x += 20; } header('Content-type: image/png'); imagepng($image); imagedestroy($image); ?>
This code will generate a verification code image on the server side and output it to the browser for display.
The following is a code example to verify user input:
<?php session_start(); if($_POST["code"] != $_SESSION["code"]) { echo "验证码输入错误"; } else { echo "验证码输入正确"; } ?>
This code will verify whether the verification code submitted by the user is the same as the verification code saved in the Session. If they are not the same, an error message will be output; if they are the same, it means the user input is correct.
The following is a code example for embedding the human-machine verification code into the form:
<form method="post" action="verify.php"> <p>用户名:</p> <input type="text" name="username"> <p>密码:</p> <input type="password" name="password"> <p>验证码:</p> <input type="text" name="code"> <img src="code.php" alt="验证码"> <input type="submit" value="提交"> </form>
This code will add an image to the form to display the verification code. Users need to enter the verification code shown in the image to submit the form. After clicking the submit button, the form will jump to the verification script code and perform verification.
Summary
This article introduces how to use PHP to implement human-machine verification code. By generating a verification code image and saving it to the Session, malicious attacks and registration can be effectively prevented. Embedding human-machine verification codes in forms can effectively improve website security and user experience.
The above is the detailed content of How to use PHP to implement human-machine verification code. For more information, please follow other related articles on the PHP Chinese website!