Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

how to access file from outside root directory in php

I have a code to download zip files:

$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;
}

there is root directory /public_html, the script is executing in root directory.

there is zip file in / directory.

i am trying to use the $dl_path as / but it is not working.

Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$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;

^ try this code. See if it works. If it doesn't:

  • If it 404's means the file is not found.
  • If it 403's it means you can't access it (permissions issue).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...