php - 同时在服务器和用户上下载

标签 php header download

我目前正在用 PHP 开发一个应用程序,其中我的服务器(专用服务器)必须下载文件,并且用户应该同时下载该文件。

这是一个例子:

  • 服务器开始一次下载一个文件A
  • 用户想要在时间 A + 3 秒(例如)时下载此文件

我已经解决了这个问题:“如果用户下载文件的速度比服务器快..”。但我不知道如何制作一个用户要下载完整文件的php脚本(这意味着大小必须是文件的完整大小,而不是A + 3秒时当前下载的大小)。我已经做到了:

header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename="'.$data['name'].'";'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: '.$data['size']);
readfile($remoteFile);

但它不起作用,用户将仅下载服务器上当前的大小(这会损坏文件),而不是完整的文件...

如果您有任何解决方案,谢谢。

最佳答案

您可以通过打开连接并读取来手动传输文件,直到读完所有 header 为止。然后,一旦您计算出 Content-Length,将其发送给用户并回显您获得的所有剩余数据(请使用 flush()并避免输出缓冲区)。

伪代码(-ish):

open the file
# grab headers
while you didn't get all HTTP headers:
    read more
look for the Content-Length header
send the Content-Length header

# grab the file
while the rest of the request isn't done
    read more
    send it to the user
    flush the buffers

done

关于php - 同时在服务器和用户上下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8466422/

相关文章:

php - 如何从已登录的表中回显用户?

ios - 如何根据某些条件导入不同的头文件

PHP 更改页面?

iphone - 在为 iphone 下载时弹出 View Controller 时来自 ASIHTTPRequest 的 exc_bad_access

download - 有没有公​​共FTP服务器可以测试上传和下载?

php - 将字符串解析成部分,只有连续的单词,而不是幂集

php - 在 EE 中使用 CodeIgniter 对两个 SQL 行求和

php - MySQL - 输出时在与关系表连接的表上获取重复行

xcode - Mac - 添加 CoreGraphics.framework,用于 C header 中的 CG

android - 从 Android App 下载的文件在下载目录中不可见