As far as i can see your function is insecure! the user can doenload any file.
I have the following script:
$allowed_extensions = array ("bin", "dat", "ps", "pdf", "xml", "txt", "doc", "xls", "ppt", "mpg",
"mpeg", "avi", "wav", "mp3", "bmp", "jpg", "gif", "png", "exe", "run",
"zip", "rar", "ace", "tgz", "tar", "gz", "bz2", "jar"); // Create an array, with filetypes, that are allowed to download (this is case-sensitive)
$filename = basename ($resource);
$string_length = strlen ($filename); // Get length of filename
$last_point = strrpos ($filename,"."); // Get position of last '.'
if ($last_point > 0) // Check whether file has any extensions
{
$extension = substr ($filename, ($last_point + 1), ($string_length - $last_point - 1)); // Extract the file-extensions
if (in_array($extension, $allowed_extensions)) // Check whether download of such a filetype is granted
{
$filepath = $DOCUMENT_ROOT.$resource;
if ((file_exists ($filepath)) && (!strpos ($filepath, ".."))) // Check whether the desired file exists and whether they try request a file above the webserver root
{
if (file_exists ($filepath)) // Check whether this file does actually exist
{
$filesize = filesize ($filepath);
$fp = fopen ($filepath, "rb");
if ($fp) // Check whether we can open the desired file
{
header ("Content-Type: application/force-download");
header ("Content-Length: ".$filesize."");
header ("Content-Disposition: attachment; filename=".$filename."");
header ("Content-Transfer-Encoding: binary");
fpassthru ($fp);
flush();
// fclose ($fp); Keep it outcommented, it generates a error message at the eof
}
}
}
}
}
Hint: I do a session_start before all that and it works fine.