下载 .zip 文件运行损坏的文件 php

Download of .zip file runs a corrupted file php(下载 .zip 文件运行损坏的文件 php)
本文介绍了下载 .zip 文件运行损坏的文件 php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试强制下载受保护的 zip 文件(我不希望人们在未先登录的情况下访问它.

I'm trying to force a download of a protected zip file (I don't want people to access it without logging in first.

我为 login 等创建了函数,但我遇到了下载文件损坏的问题.

I have the function created for the login and such , but I'm running into a problem where the downloaded file is corrupting.

这是我的代码:

$file='../downloads/'.$filename;
header("Content-type: application/zip;
");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($file).";
");
header("Content-disposition: attachment; filename="".basename($file).""");
readfile("$file");
exit();

这是错误:无法打开文件:它似乎不是有效的存档.

否则文件下载正常,所以一定是我的标题有问题.

The file downloads fine otherwise, so it must be something I'm doing wrong with the headers.

有什么想法吗?

推荐答案

此问题可能有多种原因.也许您的文件未找到或无法读取,因此文件的内容只是 PHP 错误消息.或者 HTTP 标头已经发送.或者您有一些额外的输出会破坏您的文件内容.

This issue can have several causes. Maybe your file is not found or it can not be read and thus the file’s content is just the PHP error message. Or the HTTP header is already sent. Or you have some additional output that then corrupts your file’s content.

尝试在脚本中添加一些错误处理,如下所示:

Try to add some error handling into your script like this:

$file='../downloads/'.$filename;
if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
    if (!is_file($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
        echo 'File not found';
    } else if (!is_readable($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo 'File not readable';
    } else {
        header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: ".filesize($file));
        header("Content-Disposition: attachment; filename="".basename($file).""");
        readfile($file);
        exit;
    }
}

这篇关于下载 .zip 文件运行损坏的文件 php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)