I've written this simple script to force download some files (jpg, mp3, usually those which are loaded in browser by default). I was wondering whether there's any way this could be improved upon, which means:
- making it more secure
- making it use less cpu (filesize(), fopen(), fpassthru() are the usual suspects here)
- making it simpler maybe
Here it goes:
<?php
if (!isset($_GET['file'])){
die('no file requested');
}
else{
if (substr($_GET['file'], 0, 1) == '.'){
die('trying to leave this directory? :)');
}
$path = './'.$_GET['file'];
if (file_exists($path) && is_readable($path)){
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$_GET['file']);
header('Content-Transfer-Encoding: binary');
$file = fopen($path, 'rb');
fpassthru($file);
exit;
}
}
?>
Usage: /?file=sample.jpg

http://example.com?file=/../../../../../../etc/passwdfirst char is a/, not ., and file path operations will collapse//into a single/, so you've done nothing to secure things. – Marc B Oct 21 '12 at 15:35