PHP is reading file instead of downloading

2019-09-08 11:55发布

I have script below for downloading files from a folder using PHP, it is working local but online it is reading and printing on the page instate of downloading.

if( $result && count($result) > 0){
    $row = $result[0];
    $book = true;
    $Location = './files/';
    $bookLocation = $Location . $row['file_name']; // exampe: report.zip
    if( file_exists( $bookLocation ) ){
        $fileLocation = $bookLocation;
        $file_size = filesize($fileLocation);
        echo 'Please wait downloading the file....';
        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename=' . $row['file_name']);
        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: ' . $file_size);
        ob_clean();
        flush();
        readfile($fileLocation);
        exit;      
    }else{
        echo '<h3>Sorry!, file not found...</h3>';
    }
}

.htaccess script

RewriteEngine on

RewriteRule ^$ index.html
RewriteRule ^index.html$ index.php

RewriteRule ^([0-9]{1,9})(/)([^/\.]+[^/\.]+)(_+[^/\.]+)(\.html|)/?$ index.php?id=$1&cat=$3
RewriteRule ^([^/\.]+[^/\.]+)(\.html|)/?$ index.php?page=$1
RewriteRule ^(.*)(/)([0-9]{1,9})(/)(.*)(\.html|)/?$ index.php?view_file=$3&file=$5
RewriteRule ^(.*)(/)([0-9]{1,9})(/)(.*)(\.htm)/?$ index.php?download=$3

RewriteRule ^(author)(/)(.*)(.html)/?$ index.php?user=$1

Thanks for the help.

标签: php .htaccess
2条回答
等我变得足够好
2楼-- · 2019-09-08 12:20

As Christian suggested, you must remove the echo statement in your code. If it doesn't work for you even after that, try replacing the line

header('Content-Type: application/force-download');

with

header('Content-Type: application/octet-stream');
查看更多
再贱就再见
3楼-- · 2019-09-08 12:26

It is possible that in certain browsers, you set it to automatically download and run that particular file type.

If that is the case, there is no way to "fix" this. The browser decides what to do with the file, even if you tell it to download it, the user might have told it to run directly.

Big Edit

While my earlier comment is correct, you have a major issue in your code:

    $file_size = filesize($fileLocation);
    echo 'Please wait downloading the file....';
    header('Content-Description: File Transfer');

You must remove that echo statement. It is bound to cause issues, such as the headers not being sent. Considering your description, I'd say this is your problem.

See, once you send any content, you cannot send more headers.

查看更多
登录 后发表回答