Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

Serve image with PHP script vs direct loading an image

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

www.site.com/image1.jpg

I can create a PHP script which reads the image, so I built 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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sending images through a script is nice for other things like resizing and caching on demand.

As answered by Pascal MARTIN the function readfile and these headers are the requirements:

  • Content-Type
    • The mime type of this content
    • Example: header('Content-Type: image/gif');
    • See the function mime_content_type
    • Types
      • image/gif
      • image/jpeg
      • image/png

But beside the obvious content-type you should also look at other headers such as:

  • Content-Length
    • The length of the response body in octets (8-bit bytes)
    • Example: header('Content-Length: 348');
    • See the function filesize
    • Allows the connectio to be better used.
  • Last-Modified
    • The last modified date for the requested object, in RFC 2822 format
    • Example: header('Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT');
    • See the function filemtime and date to format it into the required RFC 2822 format
      • Example: header('Last-Modified: '.date(DATE_RFC2822, filemtime($filename)));
    • You can exit the script after sending a 304 if the file modified time is the same.
  • status code
    • Example: header("HTTP/1.1 304 Not Modified");
    • you can exit now and not send the image one more time

For last modified time, look for this in $_SERVER

  • If-Modified-Since
    • Allows a 304 Not Modified to be returned if content is unchanged
    • Example: If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
    • Is in $_SERVER with the key http_if_modified_since

List of HTTP header responses


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...