0

I am trying to implement a Captcha image in my php form. The problem is that when I load my php form in the browser the captcha image is not being loaded and the default broken image for the tag is displayed. My code for the php form and the captcha image is written below:-

image.php (php code for generating the captcha image)

<?php
session_start();

$img = imagecreatetruecolor(80,30);

$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
$grey = imagecolorallocate($img,150,150,150);
$red = imagecolorallocate($img, 255, 0, 0);
$pink = imagecolorallocate($img, 200, 0, 150);

function randomString($length){
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $str = "";
    $i = 0;

        while($i <= $length){
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $str = $str . $tmp;
            $i++;
        }
    return $str;
}

for($i=1;$i<=rand(1,5);$i++){
    $color = (rand(1,2) == 1) ? $pink : $red;
    imageline($img,rand(5,70),rand(5,20), rand(5,70)+5,rand(5,20)+5, $color);
}

imagefill($img, 0, 0, $white);

$string = randomString(rand(7,10));
$_SESSION['string'] = $string;

imagettftext($img, 11, 0, 10, 20, $black, "calibri.ttf", $string);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>

captcha.php (php form)

<?php
ob_start();
session_start();

if(!$_POST['submit']){
    echo "<form method=\"post\" action=\"captcha.php\">\n";
    echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n";
    echo "<tr><td>Type The Letters You See Below Into the Box</td></tr>\n";
    echo "<tr><td align=\"center\"><img src=\"image.php\"></td></tr>\n";
    echo "<tr><td align=\"right\"><input type=\"text\" name=\"image\"></td></tr>\n";
    echo "<tr><td align=\"right\"><input type=\"submit\" name=\"submit\" value=\"Check CAPTCHA\"></td></tr>\n";
    echo "</table></form>\n";
}else {
    $image = $_POST['image'];

    if($image == $_SESSION['string']){
        echo "<b>Great success!</b>\n";
    }else {
        echo "<em>Failure!</em>\n";
    }
}

ob_end_flush();
?>

I tried to search for some solutions online but didn't get some thing that would work. Thanks.

Corporal
  • 157
  • 3
  • 14
  • Could you check whether the image is being generated by visiting image.php directly? – shxfee Oct 02 '14 at 10:10
  • No, If I directly visit the image.php it again shows me the default broken image for the image tag, it doesn't show me the captcha image. – Corporal Oct 02 '14 at 10:48
  • Then you should start there. Try turning on PHP error reporting. – shxfee Oct 02 '14 at 11:01
  • I used error_reporting(-1) in the image.php file to turn on the php error reporting, but it showed me the same result and didn't show any error as well. Not sure if you meant the same thing. – Corporal Oct 02 '14 at 12:08

0 Answers0