在 PHP 中测量网络带宽

Measure network bandwith in PHP

我正在运行将大文件 (1gb+) 从 Dropbox 传送到 YouTube,并想告知用户 t运行saction 大概需要多长时间。有什么方法可以测量 PHP 中的网络流量吗?

我确实找到了 linux shell (How to measure network performance (how to benchmark network protocol)) 的解决方案,但没有找到 PHP.

的解决方案

除了通知用户我要检查gua运行teed带宽(100mbit/s)因为我运行进入网络问题(带宽太低)了几个次。

使用 exec or system 函数从 PHP 创建 linux bash 脚本和 运行 它。

我真的不知道您是在尝试进行估算还是向用户提供 "live" 反馈。

如果你正在做一个估计,我认为你可以走 OS 路线并做一个 "exec" (就像@kost 建议的那样),它会告诉你当前的负载。不用想太多!

所以,让我们转到实时解决方案 :)!

首先看一下 ReactPHP (http://reactphp.org/) and then into the streams implementation of ReactPHP (https://github.com/reactphp/stream)。

我们的想法是创建一个可读流,您可以在其中从源(DropBox?)读取数据块,并且在您这样做时,您将继续计算剩余时间并将其写入可写流以 Web Socket 为例。

这里是一个小例子,从一个大的本地文件读取,计算 % 并写入 stdoud:

<?php
require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$read = new \React\Stream\Stream(fopen('hugefile.txt', 'r+'), $loop);
$fileStats = fstat($read->stream);
$totalSize = $fileStats['size'];
$chunkSize = $totalSize/100;
$currChunk = 1;
$write = new \React\Stream\Stream(fopen('php://stdout', 'w+'), $loop);
$totalReadBytes = 0;
$read->on('data', function ($data, $read) use ($write, &$totalReadBytes, $totalSize, &$currChunk, $chunkSize) {
  $totalReadBytes += strlen($data);
  if($totalReadBytes > ($chunkSize * $currChunk)){
    $currChunk = ceil(($totalReadBytes/$totalSize)*100);
    $write->write(sprintf('%010d',$totalReadBytes).'/'.sprintf('%010d',$totalSize).' - '.$currChunk.'%'.PHP_EOL);
  }
});
$loop->run();

请注意,您需要做的就是更改可读流的输入和可写流的输出。

您还可以将可读流通过管道传输到一个文件(您稍后会上传到 youtube)或者如果 youtube 允许的话甚至更好,只需将它通过管道传输到 youtube(那会很棒 :D)。

编辑添加我的一些评论以提高可见度:

since ReactPHP is basically a shameless copy of NodeJS, the concept of the code and idea I posted could be easily be implemented in NodeJS (the code should even look alike). With this I'm not trying to say ReactPHP is worse or better :) I just think you can achieve the same result with Node and their documentation is WAY better, with ReactPHP you will find yourself digging into the code to figure stuff out.

I think the core of ReactPHP is stable enough but I understand your concern. That being said, If I where you I would definitely try using NodeJS. If you know the basics of JS it should be practically the same learning curve you would have with ReactPHP (if not less, since there is more resources out there for Node than ReactPHP).