php - Auto redirect / download if image doesn't exist - optimisation -


i have lot of images on website, pulled image server onto main server when requested save disk space @ hosting server.

to achieve have entry in .htaccess file internally redirects people /images/image.jpg download.php checks see if file exists. if file exists serves (code below) else it'll use curl pull in remote file redirect header("location: ".$_server['request_uri']); shows image.

is inefficient serve images browser in such manner? faster let web server naturally? code reading , showing file below.

$file_extension = strtolower(substr(strrchr($filename,"."),1));  header("pragma: public"); header("content-type: image/jpg"); header("content-length: ".filesize($filename)); header("content-transfer-encoding: binary"); header("content-length: ".filesize($filename)); readfile("$filename"); 

would better off (read: more efficient) not using htaccess redirect modifying 404 page check image specific 404's , download them?

here .htaccess defines redirect download.php

^images/([0-9]+)_([a-z0-9_]+).jpg$ /download.php?id=$1 

it's little unclear mean 'redirect itself'. there reason download.php can't use curl grab image remote server , serve using code sample in same way? why need redirect?

it's best not use php engine serve images if can avoided, apache can more efficiently itself. lose of apache's default behaviour, e.g. code example isn't sending last modified headers or handling etags, if user revisits same page they're going end downloading image again instead of using cached version.

your suggested alternative approach little better, once script had downloaded image first time, subsequent requests served apache directly. make sure you're not sending 404 headers along image.

alternatively possible check whether files exist using htaccess, redirect requests non existent images download.php , not have modify 404 script. (untested):

rewriteengine on rewritecond %{request_uri} ^/images rewritecond %{request_filename} !-s rewriterule ^.*$ download.php [nc,l] 

this means: if request_uri starts /images, , filename not match existing file on file system, rewrite download.php.

i'd recommend looking x-sendfile, apache module makes easy serve images (and other binary data). using in php simple sending header containing path file:

header("x-sendfile: /home/whatever/public/images/something.jpg"); 

apache rest of work - reading , outputting file contents , sending appropriate headers. module isn't enabled default might need install or check host.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -