Skip to content

Instantly share code, notes, and snippets.

@lidio601
Created June 3, 2014 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lidio601/e0eec572a16f23e3f2ef to your computer and use it in GitHub Desktop.
Save lidio601/e0eec572a16f23e3f2ef to your computer and use it in GitHub Desktop.
Single file PHP Captcha generator. You can use this to request a captcha image via the tag <img src="http://your.website/captcha.php" alt="captcha"> and a form to insert the captcha code. In your destination page you only have to include the same file (with include_once('captcha.php'); ) and it will check itself if the captcha code is valid!
<?php
if(!isset($_SESSION)) {
@session_start();
}
//debug
//define('_JEXEC',1);
//cosa faccio?
if(defined('_JEXEC') || defined('_VALID_MOS')) {
$given = isset($_POST['captcha'])?$_POST['captcha']:isset($_GET['captcha'])?$_GET['captcha']:'';
if(isset($_SESSION['captcha']) && $_SESSION['captcha']!='' && $given !== $_SESSION['captcha']) {
?>
<script type="text/javascript">
alert('Errore, Ricompila questo form!');
history.back();
</script>
<?php
die('<!-- error captcha -->');
}
else {
//doing nothing!
}
}
else {
$font_file = "./arialbd.ttf";
$font_size = 25;
$length = 6;
$captcha = "";
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$len = strlen($salt);
mt_srand(10000000*(double)microtime());
for ($i = 0; $i < $length; $i++)
$captcha .= $salt[mt_rand(0,$len - 1)];
$captcha = strtoupper($captcha);
$texture = imagecreatefrompng('texture.png');
$source = imagecolorat($texture, rand(0, imagesx($texture)), rand(0, imagesy($texture)));
$source2 = 0x94989B;
$r = ($source >> 16 & 0xff) + 70;
$g = ($source >> 8 & 0xff) + 70;
$b = ($source & 0xff) + 50;
//$r = 87; $g = 189; $b = 263;
$text_color = imagecolorallocate($texture, $r, $g, $b);
//
$r = ($source2 >> 16 & 0xff) + 70;
$g = ($source2 >> 8 & 0xff) + 70;
$b = ($source2 & 0xff) + 50;
$line_color = imagecolorallocate($texture, $r, $g, $b);
//87 - 189 - 263
$posx = 23; //imagesx($texture)/2 - strlen($captcha) * ($font_size/3);
$posy = imagesy($texture)/2 + $font_size/2;
//imagestring($texture, 6, (imagesx($texture) - strlen($row['captcha']) * 5)/ 2, 5, $captcha, $text_color);
for($i=0;$i<$length;$i++) {
$x = $posx + $i*$font_size*1.3;
$y = $posy + rand(-$posy*0.3,$posy*0.3);
//if($i>0) imageline($texture, $x-6, $posy*0.5, $x-6, $posy*1.3, $line_color);
imagefttext($texture, $font_size,rand(-30,30), $x, $y, $text_color, $font_file, $captcha[$i]);
}
//registro il codice
$_SESSION['captcha'] = $captcha;
//stampo l'immagine
header('Content-Type: image/png');
imagepng($texture);
imagedestroy($texture);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment