How will i use php $_GET for serving file safely?

51 Views Asked by At

I am doing a simple download script using $_GET for getting the filename where guest user can download the file. The script check the uploaded folder and if the file is found it delivers it. Simple and works fine. But, after reading more about using $_GET on google and here on SO it may not be safe if the code is implemented poorly. Below is the code i have so far.

<?php
if (isset($_GET['file']) && !empty($_GET['file'])) {
    $name = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_SPECIAL_CHARS);

    $file = './upload/'.$name;

    if (!is_readable($file)) die('File not found!');

    $fp = fopen($file, 'rb');

    header("Content-Type: application/octet-stream");
    header("Content-Transfer-Encoding: Binary");
    header("Content-Disposition: attachment; filename=$name");
    header("Content-Length: " .filesize($file));
    fpassthru($fp);
}
exit;
?>

Edit: method i use for downloading the file: http://example.com/download.php?file=somefile.zip

Is the code actually unsafe against injection or other security issues? If so, how can i make it more secure?

1

There are 1 best solutions below

2
bapap On

I think it is not safe because if someone request with ../login.php (login.php is an example) they can find the source code.

Use urlencode()

I think this code will secure your script for a bit:

$file = './upload/' . urlencode($name);

Or you can use this one:

if (urlencode($name) != $name) die("Something went wrong.");