Using .htaccess Instead file_exists for Images

Published on Nov 30, 2016

Using .htaccess Instead file_exists for Images


I like using associated images with the page content; i.e. different images for every single article. It makes the look dynamic and attractive.

Building my Article Model keeping this in mind is good idea. I can create a propert for the image and save it with the actual article record.

However, there is something important to consider: what if I don't have image ready and would like to use a default article image for that specific article until I prepare the new image. What happens if the image file doesn't exist for some reason?

  • I can read the image property value and assign the image source accordingly or use default image if image is not set. I would likely use if .. else .. endif in the script for this.
  • I also have to deal with checking the image files on the server. If it doesn't exist then I have to use default image again. I can use file_exists (or Exists validator with Zend Framework).

This can be the method I can follow. However, .htaccess can help making it easier.

Instead; I will use .htaccess that we often use for many kind of redirections.

I created /img/article/ folder to keep my article images and also created /img/article.jpg to be served as default image.

* One small indirect detail: I decided to use article aliases to be the article image names as well. This way I won't even need to create a new property for storing the image file name as I already have a unique alias for each article.

# /public/img/article/.htaccess
RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [L] RewriteRule \.(jpg)$ /img/article.jpg [NC,R,L]

Finally if the article image url is /img/article/2016/11/another-article.jpg then configuration directives in this .htaccess file:

  • Make sure serving the actual JPEG file if the file actually exists.
  • Otherwise redirect to the predefined default image.

What most beautiful here is everything is controlled by Apache at the background and PHP/ZF doesn't have to worry about it!


*** I'd be happy to know if this content helped you or anything else about it to tell me. Please also feel free to share it by using the buttons below if you think it might help others too.

 
Worked with Apache 2.4