Responsive Images Generator (PHP)
A script that automatically scales requested image based on the requesting device's screen. It's a cookie based solution with a backup that checks the useragent string for "mobile".
This software is a simplified version of the awesome PHP Adaptive Images (PHP-AI) (no longer maintained) and was created to work with both Apache and NGINX in a quick and easy way.
- create cache dir (write access) and update
_rigen.php
with dir name - Add rewrite for Apache (
.htaccess
) or NGINX (via site config) - Add javascript in header
<script>document.cookie='resolution='+Math.max(screen.width,screen.height)+'; path=/';</script>
These are examples for my localhost, using a subfolder called rigen
.
RewriteEngine On
RewriteBase /rigen/
RewriteCond %{REQUEST_URI} !img-cache
RewriteRule ^(.*\.(?:jpe?g|jpg|gif|png))$ _rigen.php?$1 [NC,L]
location ~* /rigen/.*/(.*)\.(gif|jpg|png|jpeg)$ {
rewrite ^/rigen/(.*)$ /rigen/_rigen.php?$1 last;
}
The javascript stores the users screen size in a cookie. At the moment an image is requested further down the html, it is redirected through _rigen.php
, which will handle the request in this order:
- If there is no cookie found, check the useragent string for "mobile". Send either the biggest or smallest image based on the breakpoints array
- If the image dimensions are smaller than the users size, serve the original image
- If the the image is bigger, check the cache dir for a scaled down version for the next (downward) breakpoint (configurable)
- Compare the cached file timestamp to the original file timestamp
- Regenerate the cache file if not available or outdated
- Serve the cache file