Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server(通过 PHP 脚本将文件从 FTP 服务器下载到带有 Content-Length 标头的浏览器,而无需将文件存储在 Web 服务器上)
问题描述
我使用此代码从 ftp 将文件下载到内存:
I use this code to download a file to memory from ftp:
public static function getFtpFileContents($conn_id , $file)
{
ob_start();
$result = ftp_get($conn_id, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();
if ($resul)
return $data;
return null;
}
如何让它直接将文件发送给用户(浏览器)而不保存到磁盘并且不重定向到 ftp 服务器?
How can I make it directly send the file to the user (browser) without saving to disk and without redirecting to the ftp server ?
推荐答案
只需去掉输出缓冲(ob_start()
等).
Just remove the output buffering (ob_start()
and the others).
只用这个:
ftp_get($conn_id, "php://output", $file, FTP_BINARY);
<小时>
虽然如果要添加 Content-Length
标头,则必须先使用 ftp_size
查询文件大小:
Though if you want to add Content-Length
header, you have to query file size first using ftp_size
:
$conn_id = ftp_connect("ftp.example.com");
ftp_login($conn_id, "username", "password");
ftp_pasv($conn_id, true);
$file_path = "remote/path/file.zip";
$size = ftp_size($conn_id, $file_path);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($file_path));
header("Content-Length: $size");
ftp_get($conn_id, "php://output", $file_path, FTP_BINARY);
(添加错误处理)
有关更广泛的背景,请参阅:
列出并从 FTP 下载点击的文件
这篇关于通过 PHP 脚本将文件从 FTP 服务器下载到带有 Content-Length 标头的浏览器,而无需将文件存储在 Web 服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 PHP 脚本将文件从 FTP 服务器下载到带有 Content-Length 标头的浏览器,而无需将文件存储在 Web 服务器上
基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01