See, I am using the following PHP code to generate a PNG image file

<?php
// create a 100*30 image
$im = imagecreate(100, 30);

// white background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// write the string at the top left
imagestring($im, 5, 0, 0, "Hello world!", $textcolor);

// output the image
header("Content-type: image/png");
imagepng($im);
?>

The above code works absolutely fine if I am running on the top of my webpage,

But if I try to run anywhere in between my page, then it generates the following error

The image "http://localhost" cannot be displayed, because it contains erros

I know this is due to because I am passing the header after the HTML codes, but if I try to pass the header before any HTML tag then I get the same error as above.

Any suggestions?

PS: I want to make a graphical counter at the bottom of my page, and this is the reason I need this code to work. Or is there any alternative????


Kindly Help


God Bless

header stuff has to come out before anything else is printed to the screen. Try splitting the code in two. Put the header at the top and then move your image code to where you need it.

Just make a html image tag and call your image counter script from that tag!

// add to your html output page

<img src='/my_counter.php?page=index' height='24' width='100' alt='' />

example counter file content

file name = index

0000000000

// my_counter.php

<script language='php'>

/* path to counter files */

$path = './counters/';

/* default count, invalid page or no page or counter file doesn't exist */

$count = 0;

if ( ! empty ( $_GET['page']  ) )
{
	$p = trim ( $_GET['page'] );

	if ( preg_match ( "/^[a-z]{4,10}$/", $p ) && file_exists ( $path . $p ) )
	{
		$io = fopen ( $path . $p, 'r+' );
		$count = fgets ( $io, 11 );
		fseek ( $io, 0 );
		fputs ( $io, sprintf ( '%010d', ++$count ) );
		fclose ( $io );
	}
}

if ( $count == 0 )
{
	++$count;
}

$im = imagecreate ( 100, 24 );

$bg = imagecolorallocate ( $im, 255, 255, 255 );

$tc = imagecolorallocate ( $im, 0, 0, 255 );

imagestring ( $im, 5, 6, 4, sprintf ( '%010d', $count), $tc );

header ( 'Content-Type: image/png' );

imagepng ( $im );

imagedestroy ( $im );

</script>

demo!

cancer10, you can mark the topic as solved yourself. Up on the menu navigation there's an option for the topic starter to mark the topic as solved.

This article has been dead for over six months. Start a new discussion instead.