Michel Michel - 2 months ago 9
PHP Question

serve image with php script vs direct loading image

i want to monitor how often some external images are loaded.
So what my idea was instead of giving a uri directly like this:

www.site.com/image1.jpg


i create a php script which reads the image, so i build a php file and my html would look like this:

<img src="www.site.com/serveImage.php?img=image1.jpg">


but i don't know how to read the image from disk and return it. Would i return a byte array, or set the content type?

Kind regards,
Michel

Answer

You must set the content type:

header("Content-type: image/jpeg");

Then you load the image and output it like this:

$image=imagecreatefromjpeg($_GET['img']);
imagejpeg($image);