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 | <?php /** * Pings a given host and returns a red or green image. * Green when the host is online, red when offline. * * Error: ping: socket: Operation not permitted * (raw socket required by specified options). * * Solution: * $ chmod +s /path/to/ping * Alternative: * $ setcap cap_net_raw+ep /path/to/ping * Alternative: * make it passwordless sudo * * Keywords: http image ping online check * * @author Christian Weiske <weiske@mogic.com> */ if (!isset($_GET['host'])) { sendError('Host missing'); } $host = $_GET['host']; if ($host == '') { sendError('Empty host'); } if (!isset($_GET['size'])) { $size = 100; } else { $size = intval($_GET['size']); } exec('ping -c 1 -w 1 -W 1 ' . escapeshellarg($host) . ' 2>&1', $output, $retval); if ($retval == 0) { //all fine sendSvg($size, 'fill: green'); } else if ($retval == 1) { //no reply sendSvg($size, 'fill: red'); } else { //some other error, e.g. permissions header('HTTP/1.0 500 Internal server error'); header('Content-type: text/plain'); echo implode("\n", $output) . "\n"; } function sendSvg($size, $style) { $half = intval($size / 2); header('HTTP/1.0 200 OK'); header('Content-type: image/svg+xml'); echo '<' . '?xml version="1.0"?>' . "\n"; echo <<<XML <svg xmlns="http://www.w3.org/2000/svg" width="$size" height="$size"> <circle cx="$half" cy="$half" r="$half" style="$style"/> </svg> XML; } function sendError($msg) { header('HTTP/1.0 400 Bad Request'); header('Content-type: text/plain'); echo $msg . "\n"; exit(1); } ?> |