-
Notifications
You must be signed in to change notification settings - Fork 2
/
data.php
116 lines (90 loc) · 2.66 KB
/
data.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
/**
* Realtime bandwidth meter with php and jquery.
*
* @author Andreas Beder <[email protected]>
* @author Nikola Petkanski <[email protected]>
*/
$interface = array_key_exists('interface', $_GET) ? $_GET['interface'] : null;
if (!ctype_alnum($interface)) {
throw new RuntimeException('Invalid interface name. Must contain only alphabetic and numeric characters.');
}
/**
* WARNING: DRAGONS AHEAD!
*
* Do not modify after this line, unless you know what you are doing.
*/
session_start();
define('OS_LINUX', 'Linux');
define('OS_FREEBSD', 'FreeBSD');
define('OS_OSX', 'Darwin');
define('PATH_NETSTAT', '/usr/sbin/netstat');
$rx[] = getInterfaceReceivedBytes($interface);
$tx[] = getInterfaceSentBytes($interface);
sleep(1);
$rx[] = getInterfaceReceivedBytes($interface);
$tx[] = getInterfaceSentBytes($interface);
$tbps = $tx[1] - $tx[0];
$rbps = $rx[1] - $rx[0];
$round_rx=round($rbps/1024, 2);
$round_tx=round($tbps/1024, 2);
$time=date("U")."000";
$_SESSION['rx'][] = array($time, $round_rx);
$_SESSION['tx'][] = array($time, $round_tx);
/**
* to make sure that the graph shows only the
* last minute (saves some bandwitch to)
*/
if (count($_SESSION['rx'])>60)
{
$x = min(array_keys($_SESSION['rx']));
unset($_SESSION['rx'][$x]);
}
header('Content-Type: application/json');
echo json_encode(array(
'label' => $interface,
'data' => array_values($_SESSION['rx']),
));
function isOSX()
{
$uname = explode(' ', php_uname());
return $uname[0] === OS_OSX;
}
function isLinux()
{
$uname = explode(' ', php_uname());
return $uname[0] === OS_LINUX;
}
function isFreeBSD()
{
$uname = explode(' ', php_uname());
return $uname[0] === OS_FREEBSD;
}
function getInterfaceReceivedBytes($interface)
{
if (isLinux()) {
$filepath = '/sys/class/net/%s/statistics/rx_bytes';
$output = file_get_contents(sprintf($filepath, $interface));
return $output;
}
if (isFreeBSD() || isOSX()) {
$command = "%s -ibn| grep %s | grep Link | awk '{print $7}'";
exec(sprintf($command, PATH_NETSTAT, $interface), $output);
return array_shift($output);
}
throw new Exception('Unable to guess OS');
}
function getInterfaceSentBytes($interface)
{
if (isLinux()) {
$filepath = '/sys/class/net/%s/statistics/tx_bytes';
$output = file_get_contents(sprintf($filepath, $interface));
return $output;
}
if (isFreeBSD() || isOSX()) {
$command = "%s -ibn| grep %s | grep Link | awk '{print $10}'";
exec(sprintf($command, PATH_NETSTAT, $interface), $output);
return array_shift($output);
}
throw new Exception('Unable to guess OS');
}