How to access a file from an external root directory in php

I have code for downloading 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 a root directory /public_html, the script is executed in the root directory.

There is a zip file in the directory /.

I try to use $dl_pathhow /, but it does not work.

Please, help.

+1
source share
2 answers
$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 this works. If this is not the case:

  • If it 404means the file was not found.
  • If this 403means that you cannot access it (permissions).
+8
source

, script , dirname(__FILE__).

public_html, :

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

!

,

0

All Articles