首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从php中的外部根目录访问文件

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

Stack Overflow用户
提问于 2013-07-27 09:46:47
回答 2查看 8K关注 0票数 2

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

代码语言:javascript
复制
$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作为/,但它不起作用。

请帮帮忙。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-27 10:05:20

代码语言:javascript
复制
$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,这意味着您无法访问它(权限问题)。
票数 10
EN

Stack Overflow用户

发布于 2013-07-27 10:04:15

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

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

代码语言:javascript
复制
$dl = dirname(__FILE__). '/../';

但要小心安全问题!

  1. 检查文件和目录是否具有读/写权限
  2. 检查open_basedirphp.ini中的限制(参见basedir restriction?)

希望这能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17896429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档