Home » Php » Return the contents of an image in php file?

Return the contents of an image in php file?

Posted by: admin July 12, 2020 Leave a comment


I really do not know any PHP but I’d love to do one simple thing:
I access a php page from within a <img src="/myhumbleimage.php" /> and I’d like to have an image returned from another URL.

I came up with:

header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');

And it works:
Avatar selection http://vercas.webuda.com/img.php?.png
(Reload the page a few times!)

How to&Answers:

Check out readfile().

The basic idea is you send the appropriate MIME type headers (using header()) then deliver the file contents using readfile().

For example

// myhumbleimage.php

// Do whatever myhumbleimage.php does before the image is delivered

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


Why not just reference the image directly then? If you are trying to hide the fact you are pulling an image from an external source, that external source will still be able to tell you are pulling their images.

Otherwise, pass a Content-Type header with the appropriate mime-type and echo the results of file_get_contents($imageUrl).


Just generate or read, then output the image using PHP.

...get image data from file or dynamically...
header('Content-type: image/png'); //or whatever MIME type

print $imgdata;

Or check out this: http://php.net/manual/en/function.imagepng.php


I’ve discovered problems if I didn’t also include a ‘Content-Length: ‘ header. The problems are crawler, proxy, and browser caching related. In worst cases the browser waits until timeout for more data.

It’s in the spec’ and solved all issues so I’ve always included it even if modern browsers may work without it. Who knows, there still may be a slight delay since the browser doesn’t know when it has received the last segment.

Another problem I see here is that you are assuming a .png image format.
Better to create a specific function for the purpose so you can re-use it.

function returnImage( $path ) {
  header( 'Content-Type: image/' . substr($path, -3) );
  header( 'Content-Length: ' . filesize( $path ) );
  readfile( $path );

I’ve made a lot of assumptions here (like the file exists and its extension is 3 characters) but this sequence seems to be the silver bullet in my experience.