Skip to content

Instantly share code, notes, and snippets.

@skorotkiewicz
Last active February 11, 2020 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skorotkiewicz/f3c49eecfb6c364502ad9895685cd15a to your computer and use it in GitHub Desktop.
Save skorotkiewicz/f3c49eecfb6c364502ad9895685cd15a to your computer and use it in GitHub Desktop.
Simple captcha written in php

Simple captcha written in php

Usage:

if ( implode($_SESSION['captcha']) !== $_POST['captcha'] ) {
	die('Captcha incorrect')
} else {
	// captcha correct
}
<?php
header('Content-type: image/png');
session_start();
// image parameters
$width=120;
$height=40;
// create image
$image = imagecreatetruecolor($width, $height);
// colour declaration
$color_white = imagecolorallocate($image, 232, 232, 232); // 255, 255, 255
$color_gray_1 = imagecolorallocate($image, 100, 100, 100);
$color_gray_2 = imagecolorallocate($image, 50, 50, 50);
// background
imagefilledrectangle($image, 0, 0, $width, $height, $color_white);
$font_name = __DIR__ . "/GloriaHallelujah.ttf"; // font
$font_size = 16; // font size
// characters from what will be chosen
$letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
// number of characters
$characters = 6;
// character-dependent loop
for($i=1;$i<=$characters;$i++) {
$character[$i]=$letters[rand(0, count($letters)-1)]; // store random letters in a variable
}
// save the array to the sessions
$_SESSION['captcha']=$character;
$vertical_shadow = -1; // vertical position of the shadow
$horizontal_shadow = -1; // horizontal position of the shadow
$distance = 16; // distance between characters
// shadow creation
for($i=1;$i<=$characters;$i++) {
$slope_1[$i]=rand(-5 , 5); // slope
imagettftext($image, $font_size, $slope_1[$i], ($i*$distance)+$horizontal_shadow, 30+$vertical_shadow, $color_gray_1, $font_name, $character[$i]);
}
// character creation
for($i=1;$i<=$characters;$i++) {
imagettftext($image, $font_size, $slope_1[$i], ($i*$distance)+1, 30, $color_gray_2, $font_name, $character[$i]);
}
// show image
imagepng($image);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment