I have written a simple image cache script, the purpose is to load the image locally, so i can control the cache times of the images, and i have better load times than the host server, (battle.net serves 350 ms, i serve 65ish ms) this times 20 images is a pretty good performance step.
But being the performance freak i am. I was wondering if i can make it run faster!
Please also include the following in the review:
- Better suggestions for function/variable names.
- Better writing of code.
- Alternate formatting.
- Something that could be changed for something better / more correct.
- Suggestions about how to make this generic / reusable.
- An explanation about why you are right.
- An explanation why you down vote this post.
So we all can learn from this.
Comments are only for Code Review and not actually in the file.
<?php
// Checks if the img parameter is set.
if(!isset($_GET['img'])){
die;
}
// Saves it as a variable
$url = $_GET['img'];
// Compiles the local file string
$img = dirname(__FILE__) . '/media/cache/' . get_image_from_url($url);
// Check if the file exists, if not it dowloads a version of the image.
if(!file_exists($img)){
// log_message('info', 'file does not exists');
download_image($img, $url);
}
// Checks if the image existing is more than 24 hours old if it is gets a new image.
if(time()-filemtime($img) > 24 * 3600){
// log_message('info', 'file is too old');
download_image($img, $url);
}
header('Content-Type: image/jpeg');
$handle = imagecreatefromjpeg($img);
imagejpeg($handle);
/*
* FUNCTIONS
*/
function get_image_from_url($url){
$url = str_replace('http://eu.battle.net/static-render/','', $url);
$url = str_replace('/','-',$url);
return $url;
}
function download_image($img, $url){
$headers = get_headers($url);
$response_code = substr($headers[0], 9, 3);
if($response_code == '404'){
// Pleas also advice here to make the file more generic.
$url = 'http://localhost/warlords' . '/media/images/anonymous.jpg';
}
$thisurl = file_get_contents($url);
file_put_contents($img, $thisurl);
}