我是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,Dave
您的脚本可能容易受到目录遍历的攻击。在您的情况下,我会对文件名使用realpath(),并检查它是否是.files/
中的有效文件。
有人可能会遍历目录树并窃取/etc/passwd
等文件。
你对黑客的攻击很开放,有人可以这么做吗?文件=/etc/passwd/和bam拥有你最好检查一下如何防止lfi