开发者

Get UNIX server monthly bandwidth usage with PHP

Is there anyway i can get the servers monthly bandwidth usage usin开发者_StackOverflow社区g php ? Thank you .


your best bet is to parse number of packets that passed ethX inteface command that keeps track of bytes passed is /sbin/ifconfig Keep in mind that counters are reset if you reboot your linux box

eth0      
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:32363649 errors:0 dropped:0 overruns:0 frame:0
          TX packets:35133219 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:2813232645 (2.6 GiB)  TX bytes:1696525681 (1.5 GiB)
          Interrupt:16 Memory:f4000000-f4012700 


You can parse your site's apache access log to figure out the total bandwidth. Here's a loose pseudo-php example (the actual implementation will depend on your log format):

<?php
$logfile = '/var/log/apache/httpd-access.log';
$startDate = '2010-10-01';
$endDate = '2010-10-31';

$fh = fopen($logfile, 'r');

if (!$fh) die('Couldn\'t open log file.');

$totalBytes = 0;

// let's pretend the log is a csv file because i'm lazy at parsing
while (($info = fgetcsv($fh, 0, ' ', '"')) !== false) {
  // get the date of the log entry
  $date = $info[3];
  // check if the date is within our month of interest
  if ($date > $startDate && $date < $endDate) {
    // get the number of bytes sent in the request
    $totalBytes += $info[7];
  }
}

fclose($fh);

echo 'Total bytes used: ' . $totalBytes;

Also, this script is likely to be very slow depending on size of your logs, so you should considering caching the result for later use instead of running it repeatedly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜