I am following a 4-year old tutorial on creating PHP captchas through the GD. When I include the PHP-generating code on a page that has nothing else (no HTML/text content), the captcha loads perfectly fine.
But when I try to mix it in with any HTML at all, I get the error: "The image “http://testing.mysite.com/dts/cots/Test.php” cannot be displayed, because it contains errors.". Here is my code:
// Author: Andrew Walsh
// Original Post: http://www.codewalkers.com/c/a/Miscellaneous/Creating-a-CAPTCHA-with-PHP/
session_start();
$md5 = md5(microtime() * mktime());
$string = substr($md5,0,7);
$captcha = imagecreatefrompng("./img/captcha.PNG");
$black = imagecolorallocate($captcha, 0, 0, 0);
$line = imagecolorallocate($captcha,233,239,239);
imageline($captcha,0,0,39,29,$line);
imageline($captcha,40,0,64,29,$line);
imagestring($captcha, 5, 20, 10, $string, $black);
$_SESSION["CAPTCHA_CHALLENGE"] = md5($string);
header("Content-type: image/png");
imagepng($captcha);
The reason for the error is obvious: I am telling the system that I want to set the page's content type to image/png. If I am placing my CAPTCHA in an HTML form, then by definition there will already be text/html content sent back from the server by the time it gets to the header definition. According to the PHP manual, header must be the first call in a PHP page, otherwise it will throw an error.
Is there a way to hack this or make this work so that I can place the code in an HTML form, mid-page? I guess I just don't know enough about the GD or PHP in general to come up with my own solution.
Thanks,
ZHarvey