Ok finally had time to finish this little snippet. Could still be improved but it already serves it's purposes very well.
I hope there will be a possibility to receive playernames, scores and some other information (player color? ) in the future. Go matricks go!
Here's the baby
<?php
// Server Stats Receiving Tool for Teewars
//
// visit www.teewars.com
//
// (c) by zeeq
// Returns server information packed in an array
//
// @param string $ip: IP or URI of the server to check
// @param int $port : Port of the game server provided as integer
//
// @return array("Name", "IP", "Port", "Map", "MaxPlayers", "Players") or false if an error occured
function getServerStats($ip, $port)
{
// Initialize return array
$Stats = array ( "Name" => "", "IP" => $ip, "Port" => $port, "Map" => "", "MaxPlayers" => 0, "Players" => 0 );
// Open socket
$fp = @fsockopen("udp://" . $Stats['IP'], $Stats['Port'], $errno, $errstr, 2);
socket_set_timeout($fp, 2);
if(!$fp)
{
//echo "*** ERROR $errno: $errstr";
return false;
}
else
{
// Send query
// required byte sequence in ASCII
$query = "ÿÿÿÿÿÿÿÿÿÿgief";
$i = fwrite($fp, $query);
$data = fread($fp, 1024);
// Search for the "info" string
$index = strpos($data, "info");
if ($index === false)
{
//echo "*** ERROR: Unknown server response";
return false;
}
else
{
// Cut unimportant bytes until server name
$data = substr($data, $index + 4);
// Get server name until next nul byte
$index = strpos($data, chr(00));
$Stats['Name'] = substr($data, 0, $index);
// Get map name
$data = substr($data, $index + 1);
$index = strpos($data, chr(00));
$Stats['Map'] = substr($data, 0, $index);
// Get max- and players
$data = substr($data, $index + 1);
$Stats['MaxPlayers'] = ord($data[0]);
$Stats['Players'] = ord($data[1]);
return $Stats;
}
}
}
This script will work as long the server name + map name is no longer than 110 characters. But I don't think this will ever be the case
Example use of the function:
$stats = getServerStats("192.168.1.1", 8303);
if ($stats === false)
echo "ERROR";
else
var_dump($stats);