views:

64

answers:

1

Hi, I'm trying to add a captcha to a site somebody else has made. I've been following this tutorial and if I make it in a separate file, it works just fine (so it's not an issue with the server setup)

However, when I try to add it to an existing page, it's not working at all. When I load the page in Internet Explorer, the source code is displayed with random characters where the image should have been displayed such as:

‰PNGIHDRé1°8ö[IDATxœÍ]kp×u>»X‹± (4  ›–9¦:‰-C£V™©4–[ÓL•4“Dm~„njR3ª]*qÒÚ‰£ŽãD–&~Ô±ØØŽ$

In Firefox, I get the message: The image “myurl” cannot be displayed, because it contains errors.

I'm assuming this is something to do with the headers, but I'm not really sure.

This is the code I'm using to create the image:

$md5 = md5(microtime() * mktime());
$string = substr($md5,0,5);
$captcha = imagecreatefrompng("./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['key'] = md5($string);
header("Content-type: image/png");
imagepng($captcha);

Any advice would be greatly appreciated. Thanks.

+4  A: 

Those random characters are actually the contents of a PNG file.

What's happening is you're dumping the PNG data into your HTML file, rather than linking to it with an <img> tag.

You need to put the code into its own file and embed it like this:

<img src="image.php">
Greg