Why is this code not working ?
&l
You must not output anything before header()
. Just start your document with <?php
(as the first file characters), followed by the code for displaying the image. Skip the HTML tags. Do not even write a single blankline before header().
If you want to display an image inside the html document of yours, you must do it in two files. One, call it for example image.php, containing only the PHP code including the header. The second file, call it show.php or show.html, includes the HTML code you like, including <img src="image.php" alt="Your generated image" />
.
If you are using Filezilla
to upload your webpages make sure you select transfer type as 'Auto/Binary'
.
Transfer -> Transfer type -> Auto/ Binary.
You should output only the image. You are outputting a bunch of tags. Specifically
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title></title> </head> <body>
and then the image as a binary. If you want to see this, wget
the page from your server and try opening it in an editor. Your code should start at the <?php
.
Removing the header gets rid of the notification to the client that this is an image so it will try out print it out as text.
This is all you need. You can not print anything else because it needs to look like it's own file. You could call this image.php and pass it a variable to define which image to output.
<?php
header('Content-type: image/png');
$myImage = imagecreate(200, 100);
$myGray = imagecolorallocate($myImage, 204, 204, 204);
$myBlack = imagecolorallocate($myImage, 0, 0, 0);
imageline($myImage, 15, 35, 120, 60, $myBlack);
imagepng($myImage);
imagedestroy($myImage);
?>
Even if you think you have removed all the text from before header() your PHP file may contain a Byte Order Marker
This will be invisible to you in your editor, but your browser will see it and think the image is corrupt. You need to take the steps appropriate to your editor to remove any BOM.
I had the same problem and the solution was to change the charset of the code from UTF-8 to ansi or viceversa. If the server is set to UTF-8 and your code is in ansi this don't work and if your code is in ansi and the server is configured to UTF-8 neither.