1

i using the following code to force download files in 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();


    ?>

When I use this code to download this pdf file (only used for testing purposes), I open the downloaded , and all it gives me is an file empty. i tried it in chrome. opening it with windows and google chrome, it says that it can't display the pdf file because it is empty???

4

2 回答 2

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();

}

于 2013-05-14T07:21:56.133 回答
0

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

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

此选项启用支持访问 URL 对象(如文件)的 URL 感知 fopen 包装器。为使用 ftp 或 http 协议访问远程文件提供了默认包装器,zlib 等一些扩展可能会注册额外的包装器。

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

allow_url_fopen = On
于 2013-05-14T07:31:25.950 回答