title: Displaying an image in php from a file in a directory
body: <p>I have several images in a directory which is located outside of the public facing portion of the server (outside of the public_html directory). I want to be able to read the image contents with a php file, then output the result to html. </p>
  
  <p>For example, I have a php file called getimg.php with the following source code:</p>
  
  <pre><code>header('Content-type: image/jpeg');
  
  $dir = '/home/server/images/';
  $file_name = addslashes($_GET['file']);
  
  readfile('' . $dir . '' . $file_name . '.jpg');
  </code></pre>
  
  <p>getimg.php reads the contents of a jpg image in the images directory, then is referenced using the following code when I want to display the image to a user:</p>
  
  <pre><code>&lt;img src="getimg.php?file=name_of_image_file"&gt;
  </code></pre>
  
  <p>The getimg.php file also does some verification checks to ensure that the user is logged in, actually owns the image they are trying to view, etc (this is not shown above for simplicity's sake). This approach is meant to control access to the image files. However, that is not the matter at hand.</p>
  
  <p>Here is the problem: The approach/code above is only working in the Chrome browser. The images are not properly displaying in IE, FF, Safari, or Opera. Any ideas why this isn't working or how to do this properly? </p>
  
  <p><strong>Notes:</strong></p>
  
  <ul>
  <li><p>I am trying to avoid using mysql to
  store the images due to the large
  quantity of images. Being able to utilize the filesystem is greatly preferable here.</p></li>
  <li><p>The solution must be cross browser
  friendly.</p></li>
  <li><p>In reality, the image can be a jpg,
  png, or gif file. For the sake of
  simplicity, the above code only
  handles jpg images.</p></li>
  <li><p>I doubt it is relevant, but <strong>I am
  NOT using jQuery. And no, I will not
  alter my entire site to use jQuery. Any "use jQuery" posts will automatically receive a downvote</strong>. I don't hate jquery.. it's just not the right solution for my site.</p></li>
  </ul>
  
  <p><strong>UPDATE</strong></p>
  
  <p>The problem was not with the code itself. I had my php.ini file set to auto include a login verification script. Since I was not logged in all of my browsers, the image was not displaying. Silly mistake, but understandable and fixed. The code above should work just fine. It has also been updated to use readfile() instead of file_get_contents(). I am going to leave this post up for anyone that's browsing the web looking for a way to control who has access to an image using php.</p>