通过从FTP服务器与Content-Length头的浏览器的PHP脚本下载文件,而无需存储在Web服

2019-05-12 10:44发布

我用这个代码将文件从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服务器?

Answer 1:

只是删除输出缓冲( ob_start()及其他)。

只需使用这个:

ftp_get($conn_id, "php://output", $file, FTP_BINARY);

如果你想添加虽然Content-Length头,你必须先查询文件大小及使用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);

(添加错误处理)



Answer 2:

public static function getFtpFileContentsWithSize($conn_id , $file)
{
    ob_start();
    $result = ftp_get($conn_id, "php://output", $file, FTP_BINARY);
    $data = ob_get_contents();
    $datasize = ob_get_length( );
    ob_end_clean();
    if ($result)
        return array( 'data' => $data, 'size' => $datasize );
    return null;
}


            $mapfile = SUPERFTP::getFtpFileContentsWithSize($ftpconn, $curmap['filename']);
            ftp_close($ftpconn);
            if (!$mapfile)
            {
                $viewParams['OutContext'] = "Error. File not found." ;
            }

            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.$curmap['filename']);
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . $mapfile['size']); 

            echo $mapfile['data'];
            exit( );

此代码的工作。 感谢所有。



文章来源: Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server
标签: php ftp