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

如何在php中从根目录外部访问文件,php,file,Php,File,我有一个下载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"); h

我有一个下载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\u html
,脚本正在根目录中执行

/
目录中有zip文件

我正在尝试将
$dl_路径
用作
/
,但它不起作用


请提供帮助。

首先,通过回显
dirname(\uuu FILE\uu)
检查脚本是否在正确的目录下运行

如果它在
public\u html
下运行,则可以如下更改代码:

$dl = dirname(__FILE__). '/../';
但要注意安全问题

  • 检查您是否对文件和目录具有读/写权限
  • 检查
    php.ini
    中的
    open\u basedir
    限制(请参阅)
  • 希望这有帮助

    $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
      ,则表示您无法访问它(权限问题)

    1。正确格式化代码;2.使用../作为路径移动到公共区域下方,它正在工作,谢谢。还有一件小事,下载的文件被保存为“favi.zip”而不是favi.zip。如何更改。修复了
    标题(“内容处置:附件;文件名={$filename}”)以立即正常工作。