15.8. Serving Images Securely
Problem
You want to control who can view a set of images.
Solution
Don’t keep the images in your document root, but store them elsewhere. To deliver a file, manually open it and send it to the browser:
header('Content-Type: image/png');
readfile('/path/to/graphic.png');Discussion
The first line in the Solution sends the
Content-type
header to the browser, so the browser knows what type of object is
coming and displays it accordingly. The second opens a file off a
disk (or from a remote URL) for reading, reads it in, dumps it
directly to the browser, and closes the file.
The typical way to serve up an image is to use an
<img> tag and set the src
attribute to point to a file on your web site. If you want to protect
those images, you probably should use some form of password
authentication. One method is HTTP Basic Authentication, which is
covered in Recipe 8.10.
The typical way, however, may not always be the best. First, what happens if you want to restrict the files people can view, but you don’t want to make things complex by using usernames and passwords? One option is to link only to the files; if users can’t click on the link, they can’t view the file. They might, however, bookmark old files, or they may also try and guess other filenames based on your naming scheme and manually enter the URL into the browser.
If your content is embargoed, you don’t want people to be able to guess your naming scheme and view images. When information is embargoed, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access