Hu?ng d?n t?o Captcha h�nh ?nh b?ng PHP

L� do d? t? vi?t hu?ng d?n n�y l� d? ch?ng minh l�m th? n�o d? t?o h�nh ?nh captcha trong ?ng d?ng c?a b?n b?ng c�ch s? d?ng PHP. CAPTCHA l� m?t ki?m tra don gi?n d? x�c d?nh xem ngu?i d�ng l� m�y t�nh hay con ngu?i. N� du?c s? d?ng d? ngan ch?n l?m d?ng spam tr�n c�c trang web. V� v?y, n?u b?n s? d?ng CAPTCHA tr�n trang web c?a b?n, di?u n�y c� th? gi�p ngan ch?n m?t s? chuong tr�nh d?c h?i.


1. T?o ?nh Captcha



B?n ph?i c�i d?t thu vi?n  m?t GD (Graphics Draw) tru?c khi ti?p t?c v?i b�i vi?t n�y. Thu vi?n n�y cho ph�p v? d? h?a v� h�nh ?nh th�ng qua ch?c nang PHP.

�i?u d?u ti�n b?n c?n t?o h�nh ?nh captcha. Captcha c?a b?n ph?i l� m?t chu?i ng?u nhi�n nh�!

 
<!-- captcha.php -->

<?php
session_start();
?>

<title>Generate captcha image</title>
<body style="background-color:#ccc;">

<?php
create_image();
display();
function display()
{
?>
<div style="text-align:center;">
<h3>TYPE THE TEXT YOU SEE IN THE IMAGE</h3>
<div style="display:block;margin-bottom:20px;margin-top:20px;">
<img src="captcha_image.png">
</div>
<form action=" <?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="submit" value="refresh captcha">
</form>
<form action=" <?php echo $_SERVER['PHP_SELF']; ?>" method="POST"/ >
<input type="text" name="input"/>
<input type="hidden" name="flag" value="1"/>
<input type="submit" value="submit" name="submit"/>
</form>

</div>


<?php
}

function create_image()
{
$image = imagecreatetruecolor(200, 50);
$background_color = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,200,50,$background_color);

$line_color = imagecolorallocate($image, 64,64,64);
$number_of_lines=rand(3,7);

for($i=0;$i<$number_of_lines;$i++)
{
imageline($image,0,rand()%50,250,rand()%50,$line_color);
}

$pixel = imagecolorallocate($image, 0,0,255);
for($i=0;$i<500;$i++)
{
imagesetpixel($image,rand()%200,rand()%50,$pixel);
}

$allowed_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$length = strlen($allowed_letters);
$letter = $allowed_letters[rand(0, $length-1)];
$word='';
$text_color = imagecolorallocate($image, 0,0,0);
$cap_length=6;// No. of character in image
for ($i = 0; $i< $cap_length;$i++)
{
$letter = $allowed_letters[rand(0, $length-1)];
imagestring($image, 5, 5+($i*30), 20, $letter, $text_color);
$word.=$letter;
}

$_SESSION['captcha_string'] = $word;

imagepng($image, "captcha_image.png");
}
?>
</body>

2. X�c nh?n h�nh ?nh Captcha


��y l� m?t th�ng b�o c?a ngu?i d�ng sau khi h? di?n captcha

  
if($_SESSION['captcha_string']==$_POST["input")
{
echo "Thank you. You can proceed";
}
else
{
echo "Sorry. Try again";
}
unset($_SESSION['captcha_string']);

Ph?n k?t lu?n

Vi?c t?o c�c lo?i captchas kh�c nhau trong PHP r?t d? d�ng. B�y gi? b?n c� th? d? d�ng t?o ra m?t h�nh ?nh captcha d? ngan ch?n spam tr�n trang web.

No comments:

Powered by Blogger.