<?php
session_start();
//Nói cho trình duyệt biết, tôi là ảnh, ko phải là text/html…
header (“Content-Type: image/gif”);
//Khởi tạo giá trị ngẫu nhiên
$md5_hash = md5(rand(0,9999));
//Kích cỡ ảnh
$width = 45; $height = 20;
$image = imagecreate($width, $height);
$textcolor = imagecolorallocate($image, 255, 255, 255);//màu trắng (cho chữ)
$bgcolor = imagecolorallocate($image, 255, 0, 0);//màu đỏ (cho nền)
$font = 3;
$font_width = imagefontwidth($font);
$font_height = imagefontheight($font);
//Lấy 4 kí tự đầu tiên
$str = substr($md5_hash, 0, 4);
//Lưu vào session để dùng cho verify…
$_SESSION[‘SEC’] = $str;
imagefill($image, 0, 0, $bgcolor);
//Căn cho chữ ở giữa theo cả 2 chiều rộng và cao
imagestring($image, $font, ($width – strlen($str) * $font_width)/2, ($height – $font_height)/2, $str, $textcolor);
imagegif($image);//Có thể xuất ra Jpeg, Png thay vì Gif
imagedestroy($image);//Giải phóng bộ nhớ
?>
Demo: http://demo.summerhost.info/public/captcha.php