Web sitelerinde kullanıcı etkileşimli formlar yaygın olarak kullanılır. Ancak bu formlar, botlar ve kötü niyetli yazılımlar tarafından hedef alınabilir. Bu tür tehditlere karşı alınan en etkili önlemlerden biri CAPTCHA sistemidir. Bu yazıda, PHP ve JavaScript kullanarak basit bir güvenlik kodu (CAPTCHA) doğrulama sistemi nasıl yapılır, adım adım ele alacağız.
Sistemin Bileşenleri
Bu proje üç temel dosyadan oluşuyor:
index.php— Kullanıcı arayüzünü içerir.captcha.php— Rastgele görsel güvenlik kodu üretir.verify.php— Kullanıcının girdiği kodu doğrular.
Tam Örnek Kod
Aşağıda CAPTCHA doğrulama sisteminin tüm dosyalarını tek seferde bulabilirsiniz:
Önemli Not: LiberationSans-Italic.ttf Yazı Tipi Dosyasını Eklemeyi Unutmayın
CAPTCHA sistemimizin çalışabilmesi için PHP’nin imagettftext() fonksiyonu aracılığıyla yazıyı görsele basabilmesi gerekir. Bu işlem için bir TrueType Font (.ttf) dosyasına ihtiyaç duyulur. Bu yüzden LiberationSans-Italic.ttf dosyasını internet üzerinden aynı dizine indirmeniz gerekiyor.
index.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<title>Güvenlik Kodu</title>
<script>
function refreshCaptcha() {
fetch('captcha.php')
.then(response => response.json())
.then(data => {
document.getElementById('captchaContainer').innerHTML = `
<img src="${data.image}"
alt="Güvenlik Kodu"
style="height:100px;object-fit:contain;"
class="img-fluid border rounded p-2">`;
});
}
function submitForm(event) {
event.preventDefault();
var formArea = document.getElementById('form-area');
var userInput = document.getElementById('userInput');
var userValue = userInput.value;
fetch('verify.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'userInput=' + encodeURIComponent(userValue)
})
.then(response => response.json())
.then(data => {
userInput.value = "";
const messageDiv = document.getElementById('message');
if (data.success) {
formArea.innerHTML = '<p style="color:green;">' + data.message + '</p>';
} else {
refreshCaptcha();
messageDiv.innerHTML = '<p style="color:red;">' + data.message + '</p>';
}
});
}
document.addEventListener('DOMContentLoaded', function () {
refreshCaptcha();
});
</script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-dark w-75 mx-auto my-4">
<div class="card">
<div class="card-body">
<div class="container mt-5">
<div class="card shadow p-4">
<h5 class="card-title mb-4 text-center">Güvenlik Doğrulama</h5>
<form onsubmit="submitForm(event)" class="text-center" id="form-area">
<div class="mb-3" id="captchaContainer">
<!-- Captcha resmi buraya gelecek (innerHTML ile) -->
</div>
<div class="mb-3">
<button type="button" onclick="refreshCaptcha()" class="btn btn-outline-secondary btn-sm">
Yenile
</button>
</div>
<div class="mb-3">
<input type="text" id="userInput" class="form-control text-center" placeholder="Güvenlik kodunu girin" required>
</div>
<button type="submit" class="btn btn-primary w-100">Gönder</button>
</form>
<div id="message" class="mt-3 text-center"></div>
</div>
</div>
</div>
</div>
</body>
</html>
captcha.php
<?php
session_start();
function generateSecurityCode($length = 6) {
$chars = 'asdfgjkljeruo1346789';
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
return $code;
}
function createSecurityImage($code) {
$fontSize = 40;
$angle = 0;
// İşletim sistemine göre font yolu ayarla
$fontPath = __DIR__ . '/LiberationSans-Italic.ttf'; // Linux için
// Yazı tipi dosyası kontrolü
if (!file_exists($fontPath)) {
die('Yazı tipi dosyası bulunamadı: ' . $fontPath);
}
$bbox = imagettfbbox($fontSize, $angle, $fontPath, $code);
$textWidth = abs($bbox[2] - $bbox[0]);
$textHeight = abs($bbox[7] - $bbox[1]);
$padding = 20;
$width = $textWidth + $padding * 2;
$height = $textHeight + $padding * 2;
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$gray = imagecolorallocate($image, 200, 200, 200);
imagefilledrectangle($image, 0, 0, $width, $height, $white);
for ($i = 0; $i < ($width * $height) / 300; $i++) {
imagesetpixel($image, rand(0, $width - 1), rand(0, $height - 1), $gray);
}
for ($i = 0; $i < 3; $i++) {
imageline($image, rand(0, $width), rand(0, $height),
rand(0, $width), rand(0, $height), $gray);
}
$x = intval(($width - $textWidth) / 2);
$y = intval(($height + $textHeight) / 2);
imagettftext($image, $fontSize, $angle, $x, $y, $black, $fontPath, $code);
ob_start();
imagepng($image);
$imageData = ob_get_clean();
imagedestroy($image);
return 'data:image/png;base64,' . base64_encode($imageData);
}
// Kod üret ve session'a kaydet
$securityCode = generateSecurityCode();
$_SESSION['security_code'] = $securityCode;
$imageSrc = createSecurityImage($securityCode);
header('Content-Type: application/json');
echo json_encode(['image' => $imageSrc]);
verify.php
<?php
session_start();
header('Content-Type: application/json');
$userInput = $_POST['userInput'] ?? '';
$savedCode = $_SESSION['security_code'] ?? '';
$response = [];
$_SESSION['security_code'] = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 6);
if (strtolower($userInput) === strtolower($savedCode)) {
// Yeni kod oluştur ve oturuma yaz
$_SESSION['security_code'] = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 6);
$response = [
'success' => true,
'message' => 'Doğrulama başarılı!'
];
} else {
$response = [
'success' => false,
'message' => 'Güvenlik kodu yanlış!'
];
}
echo json_encode($response);