Using .htaccess Instead file_exists for Images

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 a good idea. I can create a property for the image and save it with the actual article record.

However, there is something important to consider: what if I don't have an 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 the default image if the 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 the 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 make it easier.

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

I created /img/article/ folder to keep my article images and also created /img/article.jpg to be served as the 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 to serve the actual JPEG file if the file actually exists.
  • Otherwise redirect to the predefined default image.

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


Published on Nov 30, 2016