<?php
  //11>設定session,必須處於指令碼最頂部
  session_start();
  
 
  $image = imagecreatetruecolor(120, 36);    //1>設定驗證碼圖片大小的函數
  //5>設定驗證碼顏色 imagecolorallocate(int im, int red, int green, int blue);
  $bgcolor = imagecolorallocate($image,255,255,255); //#ffffff
  //6>區域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的區域著色,col 表示欲塗上的顏色
  imagefill($image, 0, 0, $bgcolor);
  //10>設定變數
  $captcha_code = "";
  
  
    //7>生成亂數字
  for($i=0;$i<5;$i++){
    //設定字型大小
    $fontsize = 8;    
    //設定字型顏色，隨機顏色
    $fontcolor = imagecolorallocate($image, rand(0,60),rand(0,60), rand(0,60));      //0-120深顏色
    //設定數位
    $fontcontent = rand(0,9);
    //10>.=連續定義變數
    $captcha_code .= $fontcontent;  
    //設定座標
    $x = ($i*120/5)+rand(5,8);
    $y = 3+rand(5,8);
 
    imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
  }
  //10>存到session
  $_SESSION['captcha'] = $captcha_code;
  //8>增加干擾元素，設定雪花點
  for($i=0;$i<20;$i++){
    //設定點的顏色，50-200顏色比數位淺，不干擾閱讀
    $pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200));    
    //imagesetpixel — 畫一個單一畫素
    imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor);
  }
  //9>增加干擾元素，設定橫線
  for($i=0;$i<3;$i++){
    //設定線的顏色
    $linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220));
    //設定線，兩點一線
    imageline($image,rand(1,99), rand(1,29),rand(1,99), rand(1,29),$linecolor);
  }
 
  //2>設定頭部，image/png
  header('Content-Type: image/png');
  //3>imagepng() 建立png圖形函數
  imagepng($image);
  //4>imagedestroy() 結束圖形函數 銷燬$image
  imagedestroy($image);