fixnode
fixnode

Reputation: 107

Properly escaping bad characters from filename in a PHP download

I have a php script that downloads files from a folder off the document root. Here it is:

$getdir = $_GET['dir'];
$getdoctype = $_GET['doctype'];
$getfile = $_GET['filename'];
if ( !preg_match('/^[a-zA-Z]+[a-zA-Z0-9\s\_\-]+$/', urldecode($getdir)) ||
     !preg_match('/^[a-zA-Z]+[a-zA-Z0-9\s\_\-]+$/', urldecode($getdoctype))) {
    die('Bad parameter!');
}
$dir = "/var/www/uploads/$getdir/$getdoctype/";

$type = mime_content_type( $dir . $getfile );
if (file_exists($dir . $getfile)) {
header('Content-Type: ' . $type);
header('Content-Disposition: attachment;filename=' . $getfile);
readfile($dir . $getfile);
}
else{
echo "File Not Found";
}

The problem is alot of the time the files that are uploaded to my website have invalid characters like + # % () alot of these characters are ok locally but on the web they are interpreted as something else. Using my existing script how would I achieve properly escaping these characters so that my download works?

Upvotes: 0

Views: 1549

Answers (1)

mic
mic

Reputation: 1273

You can get around having some special chars in the file downloads by wrapping the filename in quotes

header('Content-Disposition: attachment;filename="' . $getfile . '"');

Alternatively you could get regex to remove the special chars, although this is not the best option.

something like this would do it: Regular Expression for alphanumeric and underscores

To do this in regex you would use

$filteredName = preg_replace('/[^a-z0-9\.]/i', '', $filename);

Upvotes: 1

Related Questions