how to access file from outside root directory in php

后端 未结 2 895
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 08:15

I have a code to download zip files:

$dl_path = \'./\';  
$filename = \'favi.zip\';  
$file = $dl_path.$filename; 
if (file_exists($file))  {
  header(\'Cont         


        
相关标签:
2条回答
  • 2020-12-20 09:00

    First of all check if your script is running under the correct directory by echoing dirname(__FILE__).

    If it is running under public_html then you can change the code like this:

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

    But beware of security issue!

    1. Check if you have read/write permission on the file and directory
    2. Check the open_basedir restriction in php.ini (see How can I relax PHP's open_basedir restriction?)

    Hope this helps

    0 讨论(0)
  • 2020-12-20 09:03
    $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).
    0 讨论(0)
提交回复
热议问题