通过PHP脚本从FTP服务器下载文件到带有Content-Length标头的浏览器,而不将文件存储在Web服务器上

时间:2017-11-11 17:12:40

标签: php ftp

我使用此代码从ftp:

将文件下载到内存
<!DOCTYPE html>
<html>
<head>

	<link rel="stylesheet" type="text/css" href="style.css">
	<style>
body  {
    background-image: url("rail.jpg");
    background-color: #cccccc;
    background-size: 100% auto;
    background-repeat: no-repeat;
}
</style>
</head>
<body>

<p>
	<?php
	if(isset($_POST['train_date'])) { //if i have this post
		
     // print it  
    echo $_POST['train_date'];    }
    else{
    	$var="nothing";
    	echo "nothing";
    }

    
?>
</p>



</body>
</html>

如何直接将文件发送给用户(浏览器)而不保存到磁盘而不重定向到ftp服务器?

2 个答案:

答案 0 :(得分:2)

只需删除输出缓冲(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);

(添加错误处理)

答案 1 :(得分:0)

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

此代码有效。谢谢大家。