快使用php,使用PHP快速通过网络传输大量小文件

通过SSH隧道使用gzip压缩包很快.比纯scp更快的速度,特别是对于许多小文件.以下是linux命令行的示例:

user@local# cd /source/ ; tar czf – * | ssh user@remote “cd /target/ ; tar xzf -“

更新:根据要求,这里你使用一个纯PHP解决方案 – 有一些乐趣摆弄这个棘手的位.

注意:您需要PHPs libssh extension才能工作.此外,STDIN似乎仅在使用SSH的流包装器时可用.

这几乎没有开销,因为它直接在流上运行,并且您的CPU很可能总是比您用于传输的网络链接更快.

要交换网络与CPU速度,可以从命令行中删除选项-z. (CPU使用率更低,但线路上的数据更多)

代码示例:

$local_cmd = "cd /tmp/source && tar -czf - *";

$remote_cmd = "tar -C /tmp/target -xzf -";

$ssh = new SSH_Connection('localhost');

$auth = $ssh->auth_password('gast', 'gast');

$bytes = $ssh->command_pipe($local_cmd, $remote_cmd);

echo "finished: $bytes bytes of data transfered\n";

class SSH_Connection {

private $link;

private $auth;

function __construct ($host, $port=22) {

$this->link = @ssh2_connect('localhost', 22);

}

function auth_password ($username, $password) {

if (!is_resource($this->link))

return false;

$this->auth = @ssh2_auth_password($this->link, $username, $password);

return $this->auth;

}

function command_pipe ($localcmd, $remotecmd) {

if (!is_resource($this->link) || !$this->auth)

return false;

// open remote command stream (STDIN)

$remote_stream = fopen("ssh2.exec://{$this->link}/$remotecmd", 'rw');

if (!is_resource($remote_stream))

return false;

// open local command stream (STDOUT)

$local_stream = popen($localcmd, 'r');

if (!is_resource($local_stream))

return false;

// connect both, pipe data from local to remote

$bytes = 0;

while (!feof($local_stream))

$bytes += fwrite($remote_stream,fread($local_stream,8192));

// close streams

fclose($local_stream);

fclose($remote_stream);

return $bytes;

}

function is_connected () { return is_resource($this->link); }

function is_authenticated () { return $this->auth; }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值