PHP下载文件损坏(zip& word)

时间:2014-06-09 14:54:56

标签: php zip docx doc

我有从服务器获取文件的脚本,但每次点击下载链接。它给了我一个腐败的单词或zip文件,需要修复。

这是代码:

    if(!$file_download=@fopen(_get_dir().'/'.$_GET['file'],'rb')){
      die("403 - Access denied");
    } else {

    header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$_GET['file']."\"");
    header('Content-Transfer-Encoding: binary');
    header('Connection: Keep-Alive');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header("Content-length:".(string)(filesize(_get_dir().'/'.$_GET['file'])));

    sleep(1);

    set_time_limit(0);
    readfile($file_download);
    }

我已阅读并尝试了许多类似的问题,但它不起作用。感谢。

问题解决了!我只是删除PHP文件中的所有BOM(也包括在内),它可以工作!

1 个答案:

答案 0 :(得分:0)

尝试这种方法,希望有所帮助。 filePath - >是ex:C:\ files。

文件的路径

fileName - >是扩展名为ex:resume.doc

的文件名
private function GetHeadersForDownload ($filePath, $fileName)
    {
        $data = file_get_contents($filePath . '/' . $fileName);

        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        $mime = $this->GetMIMEType($extension);

        // Generate the server headers

            header('Content-Type: "' . $mime . '"');
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header("Content-Transfer-Encoding: binary");
            header('Pragma: public');
            header("Content-Length: " . strlen($data));

        exit($data);
    }

private function GetMIMEType($ext)
    {
        $mimes = array(
            'zip' => 'application/x-zip'
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'txt' => 'text/plain',
            'doc' => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'word' => 'application/msword'

        );
        // Set a default mime if we can't find it
        if (!isset($mimes[$ext]))
            return 'application/octet-stream';
        else
            return $mimes[$ext];
    }