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

Dani AI

Generated

A short, practical follow-up that helps future readers identify and fix the same problem faster.

The browser message "cannot be displayed, because it contains errors" almost always means the PNG stream was corrupted before the image data reached the client. The PNG file must start with these eight bytes: 89 50 4E 47 0D 0A 1A 0A. Any HTML, stray whitespace, PHP warnings, or a UTF-8 BOM (bytes EF BB BF) emitted before that signature will break the image. and were on the right track — here are focused diagnostics and safer techniques that go beyond the original replies.

Quick diagnostics:

  • Request the image URL directly and inspect the raw start of the response; if it begins with < or text, something before the binary is being printed.
  • From a shell you can check the first bytes with:
    curl -s 'http://yourhost/counter.php?page=index' | xxd | head

    Look for any printable text or ef bb bf before the PNG signature.

Safer counter updates and hardening:

  • Avoid race conditions by locking when using flat files. Example (file locking, different from the code in the thread):
    <?php
    $fp = fopen($path.$page, 'c+');
    if ($fp && flock($fp, LOCK_EX)) {
    $count = (int)trim(stream_get_contents($fp));
    rewind($fp);
    ftruncate($fp, 0);
    fwrite($fp, sprintf('%010d', $count + 1));
    fflush($fp);
    flock($fp, LOCK_UN);
    }
    fclose($fp);
  • Save pure-PHP image generator files without the closing ?> to avoid accidental trailing whitespace.
  • Consider using a database and an atomic UPDATE counters SET hits = hits + 1 WHERE id = ? for reliability at scale.

Extra tips: sanitize the page parameter (whitelist or strict regex), check file permissions and webserver error logs for PHP notices, and add cache headers if the image shouldn't be re-generated on every view. See PHP docs for details: header(), flock(), ob_start(), and the GD image functions.

Recommended Answers

All 4 Replies

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!

Thanx


Problem solved, Plz close this topic

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.