空文件有效下载 - 有什么问题?

时间:2013-05-14 07:19:30

标签: php download

我使用以下代码强制下载php中的文件

<?PHP
    $id =$_GET['id'];

$query = mysql_query("SELECT * FROM `blog` WHERE  id = '" . $id . "' LIMIT 1")or die(mysql_error());
while($row = mysql_fetch_assoc($query)){

        $file_name = $row[url]; //  "wwyypyv6.pdf"
        $file_type = $row[type]; // "application/pdf"
        $file_url = 'http://emfhal.hostech.co.il/upload/' . $file_name;
    }
        header("Content-Type: " . $file_type);
        header("Content-Disposition: attachment; filename=\"$file_name");
        readfile($file_url);
        exit();


    ?>

当我使用此代码下载此pdf文件(仅用于测试目的)时,我打开下载的内容,而它给我的全部文件为空。我试着用铬。用windows和google chrome打开它,它说它无法显示pdf文件,因为它是空的???

2 个答案:

答案 0 :(得分:1)

正确的解决方案:

// grab the requested file's name
$file_name = $_GET['file'];

// make sure it's a file before doing anything!
if(is_file($file_name)) {

    /*
        Do any processing you'd like here:
        1.  Increment a counter
        2.  Do something with the DB
        3.  Check user permissions
        4.  Anything you want!
    */

    // required for IE
    if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }

    // get the file mime type using the file extension
    switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
        case 'pdf': $mime = 'application/pdf'; break;
        case 'zip': $mime = 'application/zip'; break;
        case 'jpeg':
        case 'jpg': $mime = 'image/jpg'; break;
        default: $mime = 'application/force-download';
    }
    header('Pragma: public');   // required
    header('Expires: 0');       // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
    header('Cache-Control: private',false);
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: '.filesize($file_name));    // provide file size
    header('Connection: close');
    readfile($file_name);       // push it out
    exit();

}

答案 1 :(得分:0)

为正在读取的本地文件使用相对或绝对路径,或者如果使用http,则为其启用fopen包装器:

http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

  

此选项启用支持URL的fopen包装器以启用访问   URL对象,如文件。为访问提供了默认包装器   使用ftp或http协议的远程文件,像zlib这样的扩展   可以注册其他包装。

在php.ini文件中添加/修改此行:

allow_url_fopen = On