Password Protected Images with PHP

Mar 20, 2009 | Tags: PHP, Image | del.icio.us del.icio.us | digg Digg

So you have images only for your site's members, and not for everyone else? Use this script to display your images to your members, and hide them for non-member visitors.

Instead of writing simple logic like:

if (member)
    display_image
else
    hide_image

for every images you have, why don't you write an image wrapper that does the logic automatically for you. Then you display the image like this: <img src="image.php?f=photo.jpg" />. The image wrapper does all the necessary stuffs. The listing is shown below:

Listing 1: image.php

  1. <?php
  2. /**
  3.  * Password protected image wrapper
  4.  *
  5.  * Author  Nash <me@nashruddin.com>
  6.  * Website http://nashruddin.com
  7.  *
  8.  * Usage: <img src="image.php?f=photo.jpg" border="0" />
  9.  */
  10.  
  11.  
  12. $path = '/path/to/images/';
  13.  
  14. if (is_file($path . $_GET['f'])) {
  15.     $f = $path . $_GET['f'];
  16. } else {
  17.     $f = $path . 'not_found.jpg';
  18. }
  19.  
  20. if ($_SESSION['login'] == false) {
  21.     $f = $path . 'req_auth.jpg';
  22. }
  23.  
  24. header('Content-type: image/jpeg');
  25.  
  26. $im = @ImageCreateFromJPEG ($f) or // Read JPEG Image
  27. $im = @ImageCreateFromPNG ($f) or // or PNG Image
  28. $im = @ImageCreateFromGIF ($f) or // or GIF Image
  29. $im = false; // If image is not JPEG, PNG, or GIF
  30.  
  31. if (!$im) {
  32.     readfile ($f);
  33. } else {
  34.     @ImageJPEG($im);
  35. }
  36.  

The code above does these:

  1. Displays req_auth.jpg if the user has not logged in.
  2. Displays not_found.jpg if the user has logged in but the requested image is not found.
  3. Displays the requested image if everything is ok.

Using the code above, you have the advantage to hide the path of the requested image. It also supports JPEG, PNG and GIF images. In addition, you can add new features to the code like: create image's thumbnail on the fly, add watermark, etc.

Related Articles

2 Comments

alexander kena on Apr 3, 2009:

great stuff man.

Jim on Sep 16, 2009:

Very cool, I have always wanted to protect my pictures and now I can!

Leave a comment

Name (required)
Email (will not be published) (required)
Website

Characters left = 1000