PHP: Security for file transfer via $_GET

Written by Joseph MICACCIA, certified network expert - -

Here is a secured variant of a bit of script that is found on almost everywhere on Intenet, as on this site, for example:

It is a module for downloading files via $_GET. We will see how to secure it simply and effectively.écurité $_GET


There are several techniques for securing a $_GET, such as filtering the variable, for example.

The technique I propose here is unprecedented, simple and effective.


$File2Download = isset($_GET['Fic']) ? trim($_GET['Fic']) : ''; 
$RepDownload   = './Download'; 
$ListeDownload = array(
if (!empty($File2Download) && in_array($File2Download,$ListeDownload) && (file_exists("$RepDownload/$File2Download"))) 
        $Taille = filesize("$RepDownload/$File2Download"); 
        header("Content-Type: application/force-download; name='$File2Download'"); 
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: $Taille"); 
        header("Content-Disposition: attachment; filename='$File2Download'");
        header("Expires: 0");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        // traitement de votre choix : message à l'utilisateur et/ou mail à l'administrateur, etc...


$ListDownload is a list containing the names of the files to download.

We make a check with "in_array ($File2Download, $ListDownload)": if $_GET is modified by a user who is trying to download something other than the proposed files, there is no download and a message could be shown ("The file that you want to download is gone to lunch!").

Only files that are in the $ListDownload list can be downloaded.

The constraint is that each time you add a new file to the download directory, you will have to complete the variable "$ListDownload".

To remedy this constraint, you can also dynamically load the variable "$ListDownload" by reading the contents of the directory "$RepDownload".

In this case, it is sufficient to replace:

$ListeDownload = array(

$Fic2Ignore = array(
                    // mettre ici tous les fichiers non téléchargeables qui se trouvent dans ce répertoire, "htaccess" and Co...
$ListeDownload = array();    
foreach (scandir($RepScarica) as $FicFound) 
	if (!in_array($FicFound,$Fic2Ignore))
			$ListeDownload[]=$FicFound; PDF

Comments are closed.