SRCDS Steam group


[Web-Integration]: Query to retrieve server info in PHP
#1
Here's a tutorial on how to query a Source Dedicated Server to retrieve server information, you can load this PHP script in to a website to show the server name, IP address, players connected and what map it's running on your front page!

All credit goes to [Toast] for creating this script

Please leave questions and suggestions at the original post located here:
http://forums.srcds.com/viewtopic/4441


Enter this in a PHP file somewhere on your webspace and include the following code snippets in your website:

The actual function:
PHP Code:
/* SOURCE ENGINE QUERY FUNCTION, requires the server ip:port */
function source_query($ip)
{
$cut explode(":"$ip);
$HL2_address $cut[0];
$HL2_port $cut[1];

$HL2_command "\377\377\377\377TSource Engine Query\0";
$HL2_socket fsockopen("udp://".$HL2_address$HL2_port$errno$errstr,3);
fwrite($HL2_socket$HL2_command); $JunkHead fread($HL2_socket,4);
$CheckStatus socket_get_status($HL2_socket);

if(
$CheckStatus["unread_bytes"] == 0)
{
    return 
0;
}

$do 1;
while(
$do)
{
    
$str fread($HL2_socket,1);
    
$HL2_stats.= $str;
    
$status socket_get_status($HL2_socket);
    if(
$status["unread_bytes"] == 0)
    {
        
$do 0;
    }
}
fclose($HL2_socket);

$x 0;
while (
$x <= strlen($HL2_stats))
{
    
$x++;
    
$result.= substr($HL2_stats$x1);    
}
$result urlencode($result); // the output
return $result;


Finally, an example of how to use all of this would be:
PHP Code:
$query source_query($ip); // $ip MUST contain IP:PORT
$q format_source_query($query);

echo 
"Hostname: ".$q['hostname'];
echo 
"Map: ".$q['map'];
echo 
"Game: ".$q['game'];
echo 
"Gamemode: ".$q['gamemode']; 


An example of similar code at work would be the following image which [Toast] has dynamically created with php:
[Image: ?a=gmod.randomresources.com:27016]



Disclaimer from [Toast]:
A portion of the code was not made by me (part of the query code),, however I had to spend lots of time figuring out how to dissect the query results and get the broken query code to work. You are free to use this wherever you wish with no credits, but a link to randomresources.org would be nice. I made this because a few months ago I looked for such a script and could not find one.


Forum Jump:


Users browsing this thread: 2 Guest(s)