出于安全考虑,我将文件存储在public_html文件夹之外。但是,我想以某种方式链接到特定文件,用户可以在其中下载这些文件之一。
我正在使用一个 jquery 脚本,该脚本允许我将服务器 PATH 指定为上传文件夹,并且它确实在public_html文件夹之外上传。
唯一的问题是它要求我指定用于下载文件的"上传路径"的 URL。我想我也许可以做这样的事情:
public_html/redirect (contains htaccess which forwards all requests to "hiding" folder)
hiding (outside public_html)
A user clicks /redirect/file.doc and they download a file located at hiding/file.doc
这可能吗?如果没有,如何授予对public_html目录之外的文件的特定文件下载访问权限?我知道我以前在其他脚本上看过它......
您可以使用"php 下载处理程序"执行此操作:
您可以使用这样的方法将文件内容和文件信息标头返回到用户浏览器,只需确保在此之前没有其他输出即可。
我建议你把它放在单独的文件中,并称之为例如download.php
.
function returnFile( $filename ) {
// Check if file exists, if it is not here return false:
if ( !file_exists( $filename )) return false;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
// Suggest better filename for browser to use when saving file:
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
// Caching headers:
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
// This should be set:
header('Content-Length: ' . filesize($filename));
// Clean output buffer without sending it, alternatively you can do ob_end_clean(); to also turn off buffering.
ob_clean();
// And flush buffers, don't know actually why but php manual seems recommending it:
flush();
// Read file and output it's contents:
readfile( $filename );
// You need to exit after that or at least make sure that anything other is not echoed out:
exit;
}
扩展它以供基本使用:
// Added to download.php
if (isset($_GET['file'])) {
$filename = '/home/username/public_files/'.$_GET['file'];
returnFile( $filename );
}
警告:
这是基本示例,并未考虑到用户可能会尝试利用未正确消毒$_GET
的一些恶意优势。
这基本上意味着,如果某些条件适用,用户可以检索passwd
文件或其他一些敏感信息。
例如,检索/etc/passwd
:
只需将浏览器指向http://server.com/download.php?file=../../../etc/passwd
服务器即可返回该文件。因此,在实际使用之前,您应该了解如何正确检查和清理任何用户提供的参数。
对于
public_html
之外的路径是不可能的。
mod_rewrite
仅重写请求,但路径仍应可供用户使用。
另一种标准方法是使用 mod_xsendfile - 它将允许 Web 应用程序通过指定标头中的路径 (X-SendFile) 让 Web 服务器发送文件作为其输出。