gpt4 book ai didi

php - 如何从php中的根目录外部访问文件

转载 作者:行者123 更新时间:2023-12-05 08:44:02 24 4
gpt4 key购买 nike

我有一个下载 zip 文件的代码:

$dl_path = './';  
$filename = 'favi.zip';
$file = $dl_path.$filename;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/zips');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/download");
header("Content-Disposition:attachment;filename=$filename ");
header("Content-Transfer-Encoding:binary ");
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

有根目录/public_html,脚本在根目录下执行。

/目录下有zip文件。

我正在尝试将 $dl_path 用作 / 但它不起作用。

请帮忙。

最佳答案

$dl_path = __DIR__.'/..'; // parent folder of this script
$filename = 'favi.zip';
$file = $dl_path . DIRECTORY_SEPARATOR . $filename;

// Does the file exist?
if(!is_file($file)){
header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
header("Status: 404 Not Found");
echo 'File not found!';
die;
}

// Is it readable?
if(!is_readable($file)){
header("{$_SERVER['SERVER_PROTOCOL']} 403 Forbidden");
header("Status: 403 Forbidden");
echo 'File not accessible!';
die;
}

// We are good to go!
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary ");
header('Content-Length: ' . filesize($file));
while(ob_get_level()) ob_end_clean();
flush();
readfile($file);
die;

^ 试试这段代码。看看它是否有效。如果没有:

  • 如果是 404 表示找不到文件。
  • 如果是 403,则表示您无法访问它(权限问题)

关于php - 如何从php中的根目录外部访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17896429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com