一分鐘學會使用PHP產生網頁驗證碼

來源:互聯網
上載者:User

    現在Web頁面上的表單一般都會內嵌一條驗證碼輸入,以防止伺服器被惡意DoS攻擊或者不法之徒利用機器程式自動貼牛皮癬廣告。

在PHP裡的簡單實現方法如下:

1. 首先在表單頁面展現之前,產生一副圖片,並添加上一些幹擾像素或線段(防止OCR程式自動識別)

再由PHP程式自動產生隨機的待驗證的一串數字和字母組合的字元, 調用imagettftext()函數畫到圖片中,

並把這串字元儲存到Session級變數中。

以下為產生驗證碼的檔案authcode.php (需要php gd庫的支援,否則無法正常顯示驗證碼圖片)

<?php
 session_start();
 header("Content-type:image/PNG");
 
 srand((double)microtime() * 1000000);
 $imagewidth = 60;
 $imageheight = 20;
 $authimage = imagecreate($imagewidth, $imageheight);
 $black = ImageColorAllocate($authimage, 0, 0, 0);
 $white = ImageColorAllocate($authimage, 255, 255, 255);
 $red = ImageColorAllocate($authimage, 255, 0, 0);
 $gray = ImageColorAllocate($authimage, 200, 200, 200);
 //背景顏色為灰色
 imagefill($authimage, 0, 0, $gray);

 //隨機的產生一些幹擾像素
 for($i = 0; $i < 400; $i++)
 {
    $randcolor = ImageColorallocate($authimage, rand(10, 255), rand(10, 255), rand(10, 255));
    imagesetpixel($authimage, rand()%$imagewidth, rand()%$imageheight, $randcolor); 
 }
 
 //隨機的畫幾條線段
 for($i = 0; $i < 6; $i++)
 {
  imageline($authimage, rand()%$imagewidth, rand()%$imageheight,
   rand()%$imagewidth, rand()%$imageheight, $black);
 }
 
 //產生驗證串
 $array = "0123456789abcdefghijklmnopqrstuvwxyz";
 for($i = 0; $i < 4; $i++)
 {
  $authcode .=substr($array, rand(0, 35), 1);
 }
 imagettftext($authimage, 20, 0, 0, $imageheight, $red, 'arial.ttf', $authcode);

 ImagePNG($authimage);
 ImageDestroy($authimage);
 $_SESSION['authcode'] = $authcode;
?>

2. 在form表單中添加顯示驗證碼圖片

驗證碼:<input type="text" name="authcode" id="textfield"/>
 <img src = "authcode.php" /><br />

3. 當使用者提交輸入後,就可以驗證所輸入的驗證碼與伺服器端儲存的驗證碼是否一致。

  if(strcmp($_SESSION['authcode'], $_POST['authcode']))
  {
   echo "<script>alert('驗證碼輸入錯誤!');</script>";
  }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.