PHP cURL Realtime proxy (stream file)(PHP cURL 实时代理(流文件))
问题描述
目前我有一个如下所示的脚本:
Currently I have a script like the following:
<?php
$filename = "http://someurl.com/file.ext";
header('Content-Type: application/octet-stream');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$filename);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 500);
$data=curl_exec($ch);
curl_close($ch);
echo $data;
?>
问题是服务器在下载整个文件后才发送响应.我想让它像流"一样工作,在下载文件时发送数据块作为响应.
The problem is that the server just send the response after download the whole file. I want to make it work like a "stream", sending chunks of data as response while the file is downloaded.
用 PHP 和 cURL 可以实现吗?
Is that possible to achieve with PHP and cURL?
推荐答案
这是可能的.您可以使用 curl 选项 CURLOPT_WRITEFUNCTION
指定一个回调,您将在其中接收数据块,以便在 curl 下载文件时将它们直接发送到客户端.
It's possible. You can use the curl option CURLOPT_WRITEFUNCTION
to specify a callback where you'll receive chunks of data so you can send them directly to the client as curl downloads the file.
<?php
$filename = "http://someurl.com/file.ext";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$filename);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 500);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
echo $data;
return strlen($data);
});
curl_exec($ch);
curl_close($ch);
这篇关于PHP cURL 实时代理(流文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP cURL 实时代理(流文件)


基础教程推荐
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01