snippetphpMinor
Is there a better way how to force file download than using this simple PHP script?
Viewed 0 times
thisscriptfileforcesimplephpthanwaybetterusing
Problem
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:
Here it goes:
Usage:
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:
Usage:
/?file=sample.jpgSolution
Always use
Should be:
Also look into other ways to sanitize
From the docs you can save on a
A better way to use variables in a string is to use
Would be better as
I think that covers the three bullet points :)
=== in your comparisons.if (substr($_GET['file'], 0, 1) == '.'){
die('trying to leave this directory? :)');
}Should be:
if (substr($_GET['file'], 0, 1) === '.'){
die('trying to leave this directory? :)');
}Also look into other ways to sanitize
$_GET['file'] properly at the moment I could pass in something like /../ and I could access other files.From the docs you can save on a
fopen() call by using readfile() instead see fpassthru()A better way to use variables in a string is to use
curly syntax so this lineheader('Content-Disposition: attachment; filename='.$_GET['file']);Would be better as
header("Content-Disposition: attachment; filename={$_GET['file']}");I think that covers the three bullet points :)
Code Snippets
if (substr($_GET['file'], 0, 1) == '.'){
die('trying to leave this directory? :)');
}if (substr($_GET['file'], 0, 1) === '.'){
die('trying to leave this directory? :)');
}header('Content-Disposition: attachment; filename='.$_GET['file']);header("Content-Disposition: attachment; filename={$_GET['file']}");Context
StackExchange Code Review Q#17790, answer score: 4
Revisions (0)
No revisions yet.