【问题标题】:how to access file from outside root directory in php如何在php中从外部根目录访问文件
【发布时间】:2013-07-27 14:43:16
【问题描述】:

我有一个下载 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 用作/,但它不起作用。

请帮忙。

【问题讨论】:

  • 1.正确格式化您的代码; 2. 使用 ../ 作为在 public_html 下方移动的路径

标签: php file


【解决方案1】:

首先通过回显dirname(__FILE__) 检查您的脚本是否在正确的目录下运行。

如果它在public_html 下运行,那么您可以像这样更改代码:

$dl = dirname(__FILE__). '/../';

但要注意安全问题!

  1. 检查您是否对文件目录有读/写权限
  2. 检查php.ini 中的open_basedir 限制(参见How can I relax PHP's open_basedir restriction?

希望对你有帮助

【讨论】:

    【解决方案2】:
    $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's 表示找不到文件。
    • 如果是403,则表示您无法访问它(权限问题)

    【讨论】:

    • 是的,它正在工作,谢谢。还有一件小事,下载的文件保存为“favi.zip”而不是 favi.zip。如何改变它。
    • 修复了header("Content-Disposition: attachment;filename={$filename}"); 现在可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 2021-05-12
    • 2023-04-01
    • 2016-10-17
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多