ตัวอย่างฟังก์ชั่นการสุ่มชุดอักขระ (rand_func.php)
<?php function randText($len=4) { $textSpace = "abcdefhjmnprtuwxyzABCDEFGHJKMNPRTVXYZ0123456789"; $textLen = strlen($textSpace)-1; $str = ""; for($i=0;$i<$len;$i++) { $str .= $textSpace[rand(0,$textLen)]; } return $str; } ?>
ตัวอย่างการสร้างภาพด้วย PHPGDI (image_capt.php)
<?php @session_start(); require_once("rand_func.php"); header("Content-Type: image/png"); $im = @imagecreate(40, 18) or die("Cannot Initialize new GD image stream"); $rt = randText(); $_SESSION['CAPTCHA'] = $rt; $background_color = imagecolorallocate($im, 0, 0, 0); $text_color = imagecolorallocate($im, 255, 255, 255); $line1_color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)); $line2_color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)); imagestring($im, 5, 2, 2, $rt , $text_color); imageline($im,rand(0,40),rand(0,18),rand(0,40),rand(0,18),$line2_color); imageline($im,rand(0,40),rand(0,18),rand(0,40),rand(0,18),$line1_color); imagepng($im); imagedestroy($im); ?>
ตัวอย่างฟอร์ม HTML และฟังก์ชั่น jQuery ที่เรียกใช้ (form.php)
<?php @session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CAPTCHA ทำเองเด้อ</title> <style type="text/css"> #capt { width: 42px; border: solid #CCC 1px; } </style> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(e) { $('#postBtn').click(function(e) { var cpt = $('#capt').val(); $.ajax({ type: 'GET' , data: {cpt: cpt }, url: 'chkcapt.php', success: function(data) { alert(data); } }); }); $('#changeCpt').click(function(e) { var v = Math.random(); $('#mycapt').attr('src','image_capt.php?v='+v); }); }); </script> </head> <body> ป้อนรหัสการโพสต์ : <input type="text" name="capt" id="capt" /> <img src="image_capt.php" id="mycapt" align="absmiddle" /><br /> <button id="postBtn">ตกลง</button> <button id="changeCpt">สุ่มรหัสใหม่</button> </body> </html>
ตัวอย่างไฟล์ตรวจสอบว่าถูกต้องหรือไม่ (chkcapt.php)
<?php @session_start(); $cpt = $_GET['cpt']; if($cpt == $_SESSION['CAPTCHA']) { echo "OK : รหัสถูกต้อง"; } else { echo "FAIL : รหัสไม่ถูกต้อง"; } ?>
ลองเอาไปทำแล้วอ่ะครับ เมื่อ captcha ถูกต้อง ก็จะขึ้น ok ให้กด ต่อจากนั้นจะลิ้งไปหน้าอื่นๆ ยังงัยครับ เห็นมันจบตรงนี้ success: function(data) {
ReplyDeletealert(data);
}
ต้องแก้หน้านี้ครับ chkcapt.php
Deleteให้โยงไปหน้าที่เราต้องการครับ
จะปรับตัวอักษร Captcha ให้ใหญ่ขี้น ปรับแก้ตรงใหนครับ
ReplyDeleteThis comment has been removed by the author.
Deleteคิดว่าน่าจะปรับตรงแบบทัดนี้ครับ ตรงตัวเลข 40,18
Delete$im = @imagecreate(40, 18)
ลองทำตามแล้วรูปไม่ขึ้นค่ะ
ReplyDelete