lundi 5 octobre 2015

Downloading File from Outside Web Root

I've set up some code to download zip files that exist in a folder above the web root. The download will be triggered from a user account page within WordPress. They don't need to be bank-level secure, but I'd like to prevent direct file access from outside the site and make them accessible only for users with the correct permission levels, and only from the appropriate user's account page. The site is entirely https.

The folder where the zip files reside is protected via htaccess.

Each user that's assigned to a specific user role will see a download link on their "Account" page:

if(current_user_can('download_these_files')){
    $SESSION['check'] = 'HVUKfb0IG1HIzHxJj5fZ';
    ?>
        <form class="user-file-download-form" action="/download.php" method="POST">
            <input type="submit" name="submit" value="Download File">
        </form>
    <?php
}

This form submits to download.php, which sits in the web root and includes some code that I've pieced together with help from Google.

session_start();
if( isset( $_POST['submit'] ) ){
    $check = $_SESSION['check'];
    if( $check === 'HVUKfb0IG1HIzHxJj5fZ' ){
        $file = /path/to/file/above/root.zip;
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        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;
    }else{
        header( 'Location: http://ift.tt/1L3fW9F' );
}else{
    header( 'Location: http://ift.tt/1L3fW9F' );
}

This works perfectly. But I can't help but wonder if I should be doing something differently. I was hoping to get input on whether or not this implementation is prodcution-ready, or if I'm missing something important as this is the first time I'm attempting something like this.

Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire