How can I allow a user to download a file which is stored outside of the webroot?

前端 未结 4 1194
无人及你
无人及你 2020-12-06 07:27

I am developing a system which allows registered users (who could be anybody) to upload files. I\'ve block mime-types etc. to attempt to restrict the files to .doc, .docx a

相关标签:
4条回答
  • 2020-12-06 07:38

    Try the following:

    $fileName = basename($_GET['file']);
    $path = 'path/to/data/'.$fileName;
    
    // define $mimeType and $isAuthenticated
    
    if ($isAuthenticated && file_exists($path)) {
        // serve file
        header('Content-type: '.$mimeType);
        header('Content-Disposition: attachment; filename="'.$fileName.'"');
        readfile($path);
    } else {
        // 404
    }
    

    This will probably need some more headers to suit your needs, but you should get an idea how this can be used.

    0 讨论(0)
  • 2020-12-06 07:45

    See the answers to this similar question: Refer to a file outside the website tree for downloading purposes, which links to the PHP header function manual page.

    0 讨论(0)
  • 2020-12-06 07:50

    You need a PHP script that does the following:

    1. Set the content-type header correctly (depending on what the user is downloading)
    2. Set the content-length header correctly (depending on the file size)
    3. Open the file for reading (you can use fopen)
    4. Read the file and output its content to the output stream
    5. Done

    You can also use readfile function to do basically the same. Here's an example from PHP's site:

    <?php
    $file = 'monkey.gif';
    
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
    ?>
    
    0 讨论(0)
  • 2020-12-06 08:00

    You can put your files directory in root and apply mod rewrite rules to secure and show a virtual path to the users instead of real path.

    0 讨论(0)
提交回复
热议问题