从FTP流式传输文件并允许用户同时下载它


Streaming a file fromFTP and letting user to download it at the same time

我正在创建一个备份系统,其中将自动生成备份,所以我会将备份存储在不同的服务器上,但是当我想下载它们时,我希望链接是一次性链接,这并不难制作,但是为了安全起见,我正在考虑存储文件,以便无法通过另一台服务器上的http访问它们。

所以我要做的是通过ftp连接,将文件下载到主服务器,然后将其呈现以供下载并删除它,但是如果备份很大,这将需要很长时间,有没有办法从FTP流式传输它而不向下载的人显示实际位置而不是将其存储在服务器上?

这是一个使用 cURL 的非常基本的示例。 它指定一个读回调,当数据可以从FTP读取时调用,并将数据输出到浏览器,以便在FTP事务与备份服务器发生时同时向客户端提供下载。

这是一个非常基本的示例,您可以对其进行扩展。

<?php
// ftp URL to file
$url = 'ftp://ftp.mozilla.org/pub/firefox/nightly/latest-firefox-3.6.x/firefox-3.6.29pre.en-US.linux-i686.tar.bz2';
// init curl session with FTP address
$ch = curl_init($url);
// specify a callback function for reading data
curl_setopt($ch, CURLOPT_READFUNCTION, 'readCallback');
// send download headers for client
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="backup.tar.bz2"');
// execute request, our read callback will be called when data is available
curl_exec($ch);

// read callback function, takes 3 params, the curl handle, the stream to read from and the maximum number of bytes to read    
function readCallback($curl, $stream, $maxRead)
{
    // read the data from the ftp stream
    $read = fgets($stream, $maxRead);
    // echo the contents just read to the client which contributes to their total download
    echo $read;
    // return the read data so the function continues to operate
    return $read;
}

有关CURLOPT_READFUNCTION选项的详细信息,请参阅 curl_setopt()。