通过PHP脚本从FTP服务器下载文件到带有Content-Length标题的浏览器,无需将文件存储在Web服务器上 [英] Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server

查看:339
本文介绍了通过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");

$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);

这篇关于通过PHP脚本从FTP服务器下载文件到带有Content-Length标题的浏览器,无需将文件存储在Web服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆