我是相當新的PHP,並設法將這個簡單的下載腳本通過閱讀在這裏列出的一些問題在SO,並想問你那些更熟悉PHP的人看一看在下面的代碼中,看看我的實現是否有明顯的缺陷,或者是否應該改變。簡單的文件下載器
只是讓你知道,在我有限的測試過程中,一切似乎都做工精細,但正如我說我是相當新的PHP和希望確保我不是失去了一些東西,可能破壞了腳本以後的道路。
<?php
//Settings
$filesPath = './files';
$fileName = $_GET['file'];
$allowedExts = array('jpg','png','gif');
//Functions
//Returns the extension portion of a filename.
function file_extension($fileName)
{
$path_info = pathinfo($fileName);
return strtolower($path_info['extension']);
}
//Validation and processing
//Check that a file is actually being requested
if (empty($fileName)) {
die('no file was requested');
}
//Check that the file is allowed to be downloaded
if (!in_array(file_extension($fileName), $allowedExts)) {
die('you cannot download this file');
}
//Get the file
if (file_exists($filesPath . DIRECTORY_SEPARATOR . $fileName)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
?>
TIA, 戴夫
不是安全相關的,但是你應該有'set_time_limit(0);'如果你不想讓你的下載在隨機中途中止.. http://php.net/manual/en/function.set-time-limit.php – Ben 2012-03-13 08:28:15
謝謝,我補充說該設置,不知道我的主機會尊重它tho。 – 2012-03-13 09:01:08
不是一個設置,只是在您的php代碼中,靠近頂部,添加'set_time_limit(0);' – Ben 2012-03-13 09:49:54