Subhajit Gorai
Subhajit Gorai

Reputation: 182

Why PHP Force Download script does not work if I include a space (%20) inside the URL?

I am using a PHP force download script as following:-

$file_Name = $_GET['name'];
$file_Url = $_GET['file'];
header("Cache-Control: public");
header("Content-Description:     File Transfer");
header("Content-Disposition: attachment; filename=$file_Name");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
readfile($file_Url);
exit;

If URL of my link is like:- /image.php?name=Germany.png&file=https%3A%2F%2Fmaps.google.com%2Fmaps%2Fapi%2Fstaticmap%3Fcenter%3DGermany%26zoom%3D15%26size%3D240x320%26maptype%3Droadmap%26mobile%3Dtrue%26sensor%3Dfalse, so it is working without any trouble!

And if I include a space (%20) inside the URL and try to visit it, browsers are showing me "Download Failed"!

Example URL:- /image.php?name=Image.png&file=https%3A%2F%2Fmaps.google.com%2Fmaps%2Fapi%2Fstaticmap%3Fcenter%3DRiver%20Annan%26zoom%3D15%26size%3D240x320%26maptype%3Droadmap%26mobile%3Dtrue%26sensor%3Dfalse

So, why is this happening? What's going wrong with it?

Upvotes: 1

Views: 307

Answers (2)

Anton Malyshev
Anton Malyshev

Reputation: 8861

That happens, because accordingly to php docs, "The superglobals $_GET and $_REQUEST are already decoded.", so %20 is replaced by space. The following code should work:

readfile(urlencode($file_Url));

+1 for general unsafety of the code

Upvotes: 1

B. Desai
B. Desai

Reputation: 16436

replace space with - then try to read url

$file_Name = $_GET['name'];
$file_Url = $_GET['file'];
header("Cache-Control: public");
header("Content-Description:     File Transfer");
header("Content-Disposition: attachment; filename=$file_Name");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
echo readfile(str_replace(" ","-",$file_Url));
exit;

Upvotes: 1

Related Questions