Vercas
Vercas

Reputation: 9161

Return the contents of an image in php file?

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:

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

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

Upvotes: 8

Views: 21016

Answers (4)

Cyberwip
Cyberwip

Reputation: 29

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 );
  exit;
}

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.

Upvotes: 0

Phil
Phil

Reputation: 165065

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

<?php
// myhumbleimage.php

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

header('Content-Type: image/jpeg');
readfile('path/or/url/of/image/file.jpg');
exit;

Upvotes: 17

Robert
Robert

Reputation: 6540

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

Upvotes: 1

simshaun
simshaun

Reputation: 21476

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).

Upvotes: 1

Related Questions