Skip to content

emka.web.id

menulis pengetahuan – merekam peradaban

Menu
  • Home
  • Tutorial
  • Search
Menu

Belajar PHP: Membuat Captcha dengan Font dan Sudut Tulis Sendiri

Posted on March 21, 2011

CAPTCHA atau Captcha adalah suatu bentuk uji tantangan-tanggapan (challange-response test) yang digunakan dalam perkomputeran untuk memastikan bahwa jawaban tidak dihasilkan oleh suatu komputer. Proses ini biasanya melibatkan suatu komputer (server) yang meminta seorang pengguna untuk menyelesaikan suatu uji sederhana yang dapat dihasilkan dan dinilai oleh komputer tersebut. Karena komputer lain tidak dapat memecahkan CAPTCHA, pengguna manapun yang dapat memberikan jawaban yang benar akan dianggap sebagai manusia. Oleh sebab itu, uji ini kadang disebut sebagai uji Turing balik, karena dikelola oleh mesin dan ditujukan untuk manusia, kebalikan dari uji Turing standar yang biasanya dikelola oleh manusia dan ditujukan untuk suatu mesin. CAPTCHA umumnya menggunakan huruf dan angka dari citra terdistorsi yang muncul di layar.

Kali ini kita akan belajar membuat captcha dengan class SimpleCaptcha yang dibuat oleh Ver Pangonilo. Source code dari simplecaptcha ini sbb:
[sourcecode language=”php”]
<?php

class SimpleCaptcha {

function SimpleCaptcha( $params = null )
{
$this->BackgroundImage = $params[‘BackgroundImage’]; //background image
$this->BackgroundColor = $params[‘BackgroundColor’];
$this->Height = $params[‘Height’]; //image height
$this->Width = $params[‘Width’]; //image width
$this->FontSize = $params[‘Font_Size’]; //text font size
$this->Font = $params[‘Font’]; //text font style
$this->TextMinimumAngle = $params[‘TextMinimumAngle’];
$this->TextMaximumAngle = $params[‘TextMaximumAngle’];
$this->TextColor = $params[‘TextColor’];
$this->TextLength = $params[‘TextLength’];
$this->Transparency = $params[‘Transparency’];

$this->generateCode();
//initially, png is used
header("Content-type: image/png");
$this->generateImage($this->Code);

}
//Background Images
function getBackgroundImage()
{
return $this->BackgroundImage;
}

function setBackgroundImage( $background_image = null )
{
$this->BackgroundImage = $background_image;
}

//Backgroung Color
function getBackgroundColor()
{
return $this->BackgroundColor;
}

function setBackgroundColor( $background_color )
{
$this->BackgroundColor = $background_color;

}

//Image Height
function getHeight()
{
return $this->Height;
}

function setHeight( $height = null )
{
$this->Height = $height;
}
//Image Width
function getWidth()
{
return $this->Width;
}

function setWidth( $width = null )
{
$this->Width = $width;
}
//Font size
function getFontSize()
{
return $this->FontSize;
}

function setFontSize( $size = null )
{
$this->FontSize = $size;
}

//Font
function getFont()
{
return $this->Font;
}

function setFont( $font = null )
{
$this->Font = $font;
}

//Text Minimum Angle
function getTextMinimumAngle()
{
return $this->TextMinimumAngle;
}

function setTextMinimumAngle( $minimum_angle = null )
{
$this->TextMinimumAngle = $minimum_angle;
}

//Text Maximum Angle
function getTextMaximumAngle()
{
return $this->TextMaximumAngle;
}

function setTextMaximumAngle( $maximum_angle = null )
{
$this->TextMaximumAngle = $maximum_angle;
}

//Text Color
function getTextColor()
{
return $this->TextColor;
}

function setTextColor( $text_color )
{
$this->TextColor = $text_color;
}

//Text Length
function getTextLength()
{
return $this->TextLength;
}

function setTextLength( $text_length = null )
{
$this->TextLength = $text_length;
}

//Transparency
function getTransparency()
{
return $this->Transparency;
}

function setTransparency( $transparency = null )
{
$this->Transparency = $transparency;
}

//get Captcha Code
function getCode()
{
return $this->Code;
}

//Generate Captcha
function generateCode()
{
$length = $this->getTextLength();
$this->Code = "";
while(strlen($this->Code)<$length){
mt_srand((double)microtime()*1000000);
$random=mt_rand(48,122);
$random=md5($random);
$this->Code .= substr($random, 17, 1);
}

return $this->Code;
}

function generateImage($text = null)
{
$im = imagecreatefrompng( $this->getBackgroundImage() );
$tColor = $this->getTextColor();
$txcolor = $this->colorDecode($tColor);
$bcolor = $this->getBackgroundColor();
$bgcolor = $this->colorDecode($bcolor);
$width = $this->getWidth();
$height = $this->getHeight();
$transprency = $this->getTransparency();
$this->im = imagecreate($width,$height);
$imgColor = imagecolorallocate($this->im, $bgcolor[red], $bgcolor[green], $bgcolor[blue]);
imagecopymerge($this->im,$im,0,0,0,0,$width,$height,$transprency);
$textcolor = imagecolorallocate($this->im, $txcolor[red], $txcolor[green], $txcolor[blue]);
$font = $this->getFont();
$fontsize=$this->getFontSize();
$minAngle = $this->getTextMinimumAngle();
$maxAngle = $this->getTextMaximumAngle();
$length = $this->getTextLength();

for($i=0;$i<$length;$i++){
imagettftext(
$this->im,
$fontsize,
rand(-$minAngle,$maxAngle),
$i*15+10,
$this->FontSize*1.2,
$textcolor,
$font,
substr($text, $i, 1));
}

imagepng($this->im);
imagedestroy($this->im);
}

function colorDecode( $hex ){

if(!isset($hex)) return FALSE;

$decoded[red] = hexdec(substr($hex, 0 ,2));
$decoded[green] = hexdec(substr($hex, 2 ,2));
$decoded[blue] = hexdec(substr($hex, 4 ,2));

return $decoded;

}
}
?>
[/sourcecode]

Untuk menggunakannya, silakan buat satu file php baru (misalnya: img.php) dan isi dengan source sbb:
[sourcecode language=”php”]
<?php
session_start();
require_once(‘class.simplecaptcha.php’);
/*
*****CONFIGURATION STARTS*****
*/
//Background Image
$config[‘BackgroundImage’] = "white.png";

//Background Color- HEX
$config[‘BackgroundColor’] = "F5F5F5";

//image height – same as background image
$config[‘Height’]=30;

//image width – same as background image
$config[‘Width’]=100;

//text font size
$config[‘Font_Size’]=23;

//text font style
$config[‘Font’]="arial.ttf";

//text angle to the left
$config[‘TextMinimumAngle’]=5;

//text angle to the right
$config[‘TextMaximumAngle’]=15;

//Text Color – HEX
$config[‘TextColor’]=’000000′;

//Number of Captcha Code Character
$config[‘TextLength’]=6;

//Background Image Transparency
$config[‘Transparency’]=50;

/*
*******CONFIGURATION ENDS******
*/

//Create a new instance of the captcha
$captcha = new SimpleCaptcha($config);

//Save the code as a session dependent string
$_SESSION[‘string’] = $captcha->Code;

?>
[/sourcecode]

Untuk menggunakan captcha ini, silakan load sebagai image:
[sourcecode language=”html”]
<img src="http://localhost/latihan/img.php" />
[/sourcecode]

atau contoh lengkapnya dalam satu form:
[sourcecode language=”php”]
<?php
session start();
<html>
<head>
<title>Simple CAPTCHA Class Application</title>
</head>
<body>
<?php
if (!$_POST[‘code’])
{
?>
<form id="demo" action="<?php echo $_SERVER[‘PHP_SELF’]; ?>?goto=login" method="POST">

Message:
<br/>
<textarea name="message" cols="25" rows="5" id="message" ></textarea>
<br/>
Validation Code:
<br/>
<img src="./captcha.php" alt="CAPTCHA">
<br>
<input type="text" name="code" size="30">
<br>
<input type="submit" value="Go">
</form>
<?php
}else{

//Check if userinput and CAPTCHA Code are equal
if ($_SESSION[‘string’] == $_POST[‘code’])
{
echo ‘<script>alert("Correct Code.");history.go(-1);</script>’;
}
else
{
echo ‘<script>alert("Incorrect Code.");history.go(-1);</script>’;
}
}
?>
</body>

</html>
[/sourcecode]

Menggunakan Custom Font

Dengan class ini, secara default font yang digunakan untuk dirender pada image captcha adalah font Arial. Kita bisa mengganti jenis font tersebut dengan mengganti pada parameter $config[‘font’] dengan (misalnya) calibri.ttf. Untuk mendapatkan file font tersebut, silakan browse ke C:\windows\fonts\ atau download dari internet.

Mengubah sudut tulis (angle) dari Font Captcha

Untuk mengubah sudut tulis dari huruf/angka captcha, silakan ubah variabel $config[‘TextMinimumAngle’] atau $config[‘TextMaximumAngle’].

Terbaru

  • Inilah Cara Dapat Saldo Cool Lady Tanpa Undang Teman, Ternyata Begini Trik Rahasianya!
  • Inilah Cara Main Watermelon Merge Fun Biar Dapat Saldo DANA, Apakah Benaran Membayar?
  • Inilah Kenapa Stok Penarikan Free Reels Sering Habis dan Cara Mengatasinya Agar Saldo Cair!
  • Inilah Alasan Kenapa Telat Lapor SPT 2026 Nggak Bakal Kena Denda, Cek Aturan Lengkapnya!
  • Inilah Cara Mematikan Koreksi Otomatis di WhatsApp Agar Nggak Salah Ketik Lagi
  • Apa itu Bujang Inam? Inilah Alasan Kenapa Kata Ini Jadi Makian Paling Kasar dalam Budaya Medan dan Batak!
  • Inilah Kenapa Link FF Kipas My ID Verify UID Beta Testing Sering Gagal dan Cara Menghadapinya
  • Gini Caranya Mulai Dropshipping Pake AI di Tahun 2026, Auto Cuan Tanpa Ribet!
  • Baterai Smartwatch Boros? Inilah Caranya Biar Baterai Smartwatch Kalian Bisa Awet Berhari-hari!
  • Belum Tahu? Inilah Fakta Cahaya Misterius di Lampung yang Ternyata Sampah Roket China CZ-3B!
  • Inilah Roblox Mod APK 2026, Fitur Premium Jadi Gratis dan Cara Pasangnya yang Perlu Kalian Tahu!
  • Inilah Panduan Lengkap UTUL UGM 2026, Cari Tahu Jadwal, Biaya Pendaftaran, Sampai Info Uang Pangkal IPI di Sini!
  • Inilah IGRS di Roblox dan Steam, Ternyata Ini Alasan Komdigi Kasih Aturan Ketat!
  • Inilah Makna Mendalam Regina Caeli: Kenapa Umat Katolik Wajib Doa Ratu Surga Selama Masa Paskah?
  • Inilah Kronologi Lengkap Kecelakaan Truk TNI di Kalideres: Simak Fakta dan Status Sopirnya Sekarang!
  • Inilah Rahasia Ambil Ide Youtube Lain, Tapi Konten Kalian Nggak Terlihat Membosankan
  • Studi Kasus SEO: Ellevest Dapat 14 Ribu Pengunjung Organik Per Bulan dengan Strategi SEO Niche dan Otomasi AI
  • Inilah Rahasia ReciMe, Potensi Sukses dari Aplikasi Resep Sederhana
  • Perkuat Kemandirian Industri Alat Kesehatan Nasional, Astra Komponen Indonesia Hadirkan Alat Kesehatan Berbasis Teknologi Digital
  • Vidrush, Solusi Produksi Video massal buat Channel Faceless
  • Inilah Higgsfield AI Audio, Trik Canggih Buat Voice Cloning dan Dubbing Video Youtube Otomatis!
  • Everything You Need to Know About Project X and the Rumored AI-Powered Remaster of The Sims 4
  • Inilah Trik Cuan dari Instagram Jadi Affiliator, Tapi Tanpa Perlu Jualan Produk!
  • Inilah 7 Ide Channel YouTube Aneh Tapi Sederhana yang Bisa Kalian Mulai Sekarang Juga!
  • Apa itu Umroh & Keutamaannya: Inspirasi dari pergiumroh.com
  • Belum Tahu? Gini Caranya Dapat Bisnis Sukses Cuma dari Clipping Video Pake AI
  • Inilah Rahasia Perbaiki Algoritma Video YouTube yang Mulai Sepi
  • Kenapa Cicilan di Bank Syariah Itu Tetap?
  • Inilah 7 Produk Digital Paling Realistis untuk Kalian yang Mau Jualan Online Tahun Ini!
  • Inilah 4 Strategi Memilih Niche SEO Terbaik Supaya Blog Kalian Cepat Ranking
  • How to Design a Services Like Google Ads
  • How to Fix 0x800ccc0b Outlook Error: Step-by-Step Guide for Beginners
  • How to Fix NVIDIA App Error on Windows 11: Simple Guide
  • How to Fix Excel Formula Errors: Quick Fixes for #NAME
  • How to Clear Copilot Memory in Windows 11 Step by Step
  • How to Use Orbax Checkpointing with Keras and JAX for Robust Training
  • How to Automate Any PDF Form Using the Power of Manus AI
  • How to Training Your Own YOLO26 Object Detection Model!
  • How to Build a Full-Stack Mobile App in Minutes with YouWare AI
  • How to Create Consistent Characters and Cinematic AI Video Production with Seedance
  • Apa itu Spear-Phishing via npm? Ini Pengertian dan Cara Kerjanya yang Makin Licin
  • Apa Itu Predator Spyware? Ini Pengertian dan Kontroversi Penghapusan Sanksinya
  • Mengenal Apa itu TONESHELL: Backdoor Berbahaya dari Kelompok Mustang Panda
  • Siapa itu Kelompok Hacker Silver Fox?
  • Apa itu CVE-2025-52691 SmarterMail? Celah Keamanan Paling Berbahaya Tahun 2025

©2026 emka.web.id | Design: Newspaperly WordPress Theme