在 CentOs 5.6 上使用 php 脚本强制下载文件


Forcing Download of file using php script on CentOs 5.6

我需要对用户进行身份验证才能查看/下载我网站中的某些文件。我的文件位于一个文件夹中,比如 A 在public_html/mySiteName/FoldesName(A)/subFolder/sample.(*.*)内。我使用.htaccess来检查用户是否经过身份验证。


我的.htaccess代码:

RewriteEngine on   # Enable rewrite
RewriteCond %{REQUEST_FILENAME} '.*pdf$|.*psd$|.*indd$ [NC]  
RewriteRule (.*) http://MySiteIp/admin_panel/auth.php?file=$1 [NC,L]

我的下载脚本如下所示:

if($authed){
    if(file_exists("../".$_GET['file'])) {
        //Create the pointer to our file and open it as read-only binary data
        $fp = fopen($file,'rb');
        // Send headers telling browser to download our passed data
        header("Content-Type: application/force-download");
        header("Pragma: no-cache");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Length: " . filesize($file));
        header("Accept-Ranges: bytes");
        header("Content-Disposition: attachment; filename='"$file'"");
        while (!feof($fp)) {
            echo(@fgets($fp, 8192));
        } 
        //Here comes the data 
        fclose($fp);
        //and quit
        exit;
    } else {
        echo "No file exists !!!";
    }
}

当我在本地计算机上测试它并安装了 Xampp 服务器时。它有效。但是在我的主机上,我收到错误消息"不存在任何文件"。

请帮助我找到我错的地方...

我猜你在问这个问题之前删除了echo "here"; die();

无论如何,您的本地计算机和Web主机上的文件结构是否相同?

文件是否实际在../? 也许尝试使用文件的完整路径?/home/youruser/public_html/或任何主机的目录结构。