프로그램/script

php inline captcha

mulderu 2015. 12. 7. 06:49


PHP를 이용해서 손쉽게 인라인 captcha image 를 만들수 있다.

ref : http://99webtools.com/blog/php-simple-captcha-script/

  

First generate captcha image

Here is php code to generate image with random code. Save it as captcha.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165); //background color blue
$fg = imagecolorallocate($im, 255, 255, 255);//text color white
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5,  $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

First start session to store captcha code in session then generate random code using php rand() function and write it on image generated by imagecreatetruecolor(). To change image background color edit line 6 and for text color edit line 7

Put captcha image in html form

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>Test Form</title>
</head>
<body>
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>

Now validate Captcha response

1
2
3
4
5
6
7
8
9
10
11
12
<?php
session_start();
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
echo "Correct Code Entered";
//Do you stuff
}
else
{
die("Wrong Code Entered");
}
?>

first start session to access $_SESSION[“code”] variable then compare it with posted captcha response. If both are same then run your code else exit from code with message Wrong Code Entered