CuDemVN.Wap.Sh



![]() | ![]() ![]() ![]() |
Để xác nhận dữ form được gửi đi có phải là robot hay không, bài viết này sẽ hướng dẫn các bạn viết mã xác thực (captcha) bằng PHP để xác minh biểu mẫu được gửi đi từ người hay là một robot.
Đầu tiên chúng ta sẽ tạo một hình ảnh xác nhận
Đây là đoạn code php tạo ra hình ảnh xác nhận, hãy tạo một file tên captcha.php rồi dán đoạn code này vào rồi lưu lại.
<?php
session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165); //background color blue
$fg = imagecolorallocate($im, 255, 255, 255);//text color white
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5, $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165); //background color blue
$fg = imagecolorallocate($im, 255, 255, 255);//text color white
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5, $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Hình ảnh được tạo ra bởi hàm imagecreatetruecolor(), nếu bạn muốn thay đổi màu chữ hay màu nền thì hãy thay đổi giá trị ở dòng 6 và 7.
Sử dụng đoạn code này như thế nào?
Sau khi tạo xong file captcha.php, nếu bạn muốn xem thử hoạt động của nó hãy tạo một file html rồi dán nội dung sau vào rồi lưu lại
<html>
<head>
<title>Test Form</title>
</ head>
<body>
<form action="xacnhan.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
<head>
<title>Test Form</title>
</ head>
<body>
<form action="xacnhan.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
Tiếp tục, bạn hãy tạo file có tên xacnhan.php rồi dán đoạn php script sau vào
<?php
session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Captcha dung";
//Do you stuff
}
else
{
die("Captcha sai");
}
?>
session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Captcha dung";
//Do you stuff
}
else
{
die("Captcha sai");
}
?>
Chúc các bạn áp dụng thành công!
Nguồn: Kind.Vn
↓ Tập tin Đính kèm ↓

Đánh giá: 4.5/ 5, 1990 bình chọn
