Selasa, 19 Oktober 2010

PHP : Create a CAPTCHA with PHP and MySQL

A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a challenge-response test most often placed within web forms to determine whether the user is human.
The purpose of CAPTCHA is to ensure that executing truly human and to block form submissions by spambots, which are automated scripts that post spam content everywhere they can. Lots of facilities that provide a captcha and we can use it. But this time we will create a captcha. In this tutorial, concept of captcha is users will choose an appropriate image name with a picture beside, the picture will be displayed randomly.

how to make it ...
1. Prepare the database and create a table with the following code:
CREATE TABLE IF NOT EXISTS `captcha` (
  `id_captcha` int(11) NOT NULL AUTO_INCREMENT,
  `nama_captcha` varchar(50) NOT NULL,
  `gambar_captcha` varchar(50) NOT NULL,
  PRIMARY KEY (`id_captcha`)
)

2. Fill the table with the following code:
INSERT INTO `captcha` (`id_captcha`, `nama_captcha`, `gambar_captcha`) VALUES
(1, 'domba', '02.jpg'),
(2, 'kepala kuda', '03.jpg'),
(3, 'anak ayam', '04.jpg'),
(4, 'ayam jago', '06.jpg'),
(5, 'Tikus', '07.jpg');
3. download image files here. (We can add as needed)
4. Database connection can be viewed here or downloaded here
5. Make a php file as below
<?php
if(isset($_POST['captcha'])){
if($_POST["cap_cek"] != $_POST["pilihan"])
{
 die('{"salah nda..."}');
}
else
 die('{"bener nda..."}');
}

require_once('class.mysql.php');
$mysql = new Mysql();
$mysql->connect();

if($mysql->execute("select * from captcha order by rand() limit 1")){
   $data = $mysql->getDataSet();
  }else{
   $data = 0;
  }
$nama = $data[0][1];
$gambar = $data[0][2];
$id_c = $data[0][0];


if($mysql->execute("select * from captcha where id_captcha!=$id_c order by rand() limit 3 ")){
   $data = $mysql->getDataSet();
  }else{
   $data = 0;
  }
//gabungkan hasil dalam satu array
for($i=0;$i<4;$i++){
 if($i<3){
 
  $captcha_nama[$i] = $data[$i][1];
 }
 else{
 
  $captcha_nama[$i] = $nama;
 }
}

$rand_keys=array_rand($captcha_nama,4);

?>
<form method="post" action="" name="captcha">
<table border="0">
  <tr>
    <td colspan="3">Apakah nama Hewan Di Bawah ini: </td>
  </tr>
  <tr>
    <td ><img src="<?=$gambar?>" /></td>
    <td >&nbsp;</td>
    <td >
   <?php
   for($i=0;$i<4;$i++){
  ?>
  <input name="pilihan" type="radio" value="<?=$captcha_nama[$rand_keys[$i]] ?>" /> <?=$captcha_nama[$rand_keys[$i]] ?>   
  <?php
   }
   ?>     
  </td>
  </tr>
  <tr>
  <td colspan="3">
  <input type="hidden" name="cap_cek" value="<?=$nama ?>" >
  <input type="submit" name="captcha" value="cek captcha!">
  </td>
  </tr>
</table>
</form>
6. finish. you can download full code here.

Tidak ada komentar:

Posting Komentar