Best way to output image using php

I have a script called "image.php" that is used to count impressions and then print the image.

This script is called like this:

<img src="path/image.php?id=12345" />

      

And it is used very often by my users, I see thousands of requests per day

So, I want to understand what is the best way to output the image at the end of this script:

Method 1 (actually used):

header("Content-type: $mime"); //$mime is found with getimagesize function
readfile("$image_url");
exit;

      

Method 2 (almost sure this is the slowest):

header("Content-type: $mime");
echo  file_get_contents("$image_url");
exit;

      

Method 3:

header('Location: '.$image_url);
exit();

      

Is method 3 better / faster than method 1?

+3


source to share


2 answers


Okay, first of all, method 3 is faster to redirect to the original file.

The first 2 methods require file access and file reading, and they also don't use the browser cache!

Also when you store rendered images you can better let apache handle your static files. Apache is faster than PHP and uses proper browser caching (3 or 4 times faster shouldn't be a surprise).



What happens when you request a static file is apache sends a Last-Modified header If your client requests the same image again, it sends an If-Modified-Since header with the same date. If the file is unmodified, the server will respond with a 304 Not Modified header without any data, which will save you a lot of I / O (except for the ETAG header, which is also used).

For the number of times your images are shown, you can create a cronjob that analyzes your apache access logs so that the end user doesn't even notice it. But in your case, it's easier to count the impressions in your script and then redirect

+2


source


Essentially what readfile does is it reads the file directly into the output buffer and file_get_contents loads the file into memory (string). Thus, when outputting the results, the data is copied from memory to the output buffer, which makes it twice as slow as readfile.



+1


source







All Articles