### Install PHP Source Query via Composer
Source: https://context7.com/xpaw/php-source-query/llms.txt
Install the library using Composer. Requires PHP 8.3+.
```bash
composer require xpaw/php-source-query-class
```
--------------------------------
### Mocking BaseSocket for Testing PHP Source Query
Source: https://context7.com/xpaw/php-source-query/llms.txt
This example demonstrates how to create a mock `BaseSocket` to substitute the real UDP socket for testing purposes. It replays pre-recorded binary packets to simulate server responses.
```php
*/
private array $packets = [];
public function queue(string $rawBinaryPacket): void
{
$this->packets[] = $rawBinaryPacket;
}
public function Close(): void {}
public function Open(string $Address, int $Port, int $Timeout, int $Engine): void
{
$this->Engine = $Engine;
}
public function Write(int $Header, string $String = ''): bool
{
return true;
}
public function Read(): Buffer
{
$buf = new Buffer();
$buf->Set(array_shift($this->packets) ?? '');
$this->ReadInternal($buf, fn() => false);
return $buf;
}
}
// Replay a real captured A2S_INFO response (hex-encoded)
$rawInfoPacket = hex2bin(
'ffffffff49' . // header: single packet + S2A_INFO_SRC
'11' . // protocol 17
'4d792053657276657200' . // "My Server\0"
'636f5f6475737400' . // "co_dust\0"
'637300' . // "cs\0"
'436f756e7465722d5374'
'72696b6520536f75726365'
'00' . // "Counter-Strike Source\0"
'1b02' . // AppID 539 (little-endian)
'0c18004c0100' // Players=12 MaxPlayers=24 Bots=0 Dedicated='d' Os='l' Password=0 Secure=1
);
$mock = new MockSocket();
$mock->queue($rawInfoPacket);
$query = new SourceQuery($mock);
$query->Connect('', 27015);
$info = $query->GetInfo();
echo $info['HostName'] . PHP_EOL; // "My Server"
echo $info['Map'] . PHP_EOL; // "co_dust"
$query->Disconnect();
```
--------------------------------
### Connect
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Opens a connection to a game server.
```APIDOC
## Connect
### Description
Opens connection to a server.
### Method
Connect
### Parameters
#### Path Parameters
- **Ip** (string) - Required - The IP address of the server.
- **Port** (integer) - Required - The port number of the server.
- **Timeout** (integer) - Optional - The connection timeout in seconds.
- **Engine** (string) - Optional - The game engine (e.g., 'source', 'goldsrc'). Defaults to 'source'.
```
--------------------------------
### Retrieve Server Information with SourceQuery::GetInfo()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Connects to a Source game server and retrieves detailed information using the A2S_INFO query. Handles challenge handshakes and includes extra data fields if available. Ensure the server is reachable and the correct port is used.
```php
Connect('192.168.1.100', 27015, 3, SourceQuery::SOURCE);
$info = $query->GetInfo();
/*
* Example return value for a TF2 server:
* [
* 'Protocol' => 17,
* 'HostName' => 'My TF2 Server',
* 'Map' => 'cp_badlands',
* 'ModDir' => 'tf',
* 'ModDesc' => 'Team Fortress',
* 'AppID' => 440,
* 'Players' => 12,
* 'MaxPlayers' => 24,
* 'Bots' => 0,
* 'Dedicated' => 'd', // 'd' = dedicated, 'l' = listen
* 'Os' => 'l', // 'l' = Linux, 'w' = Windows
* 'Password' => false,
* 'Secure' => true,
* 'Version' => '7.7.3.3',
* 'ExtraDataFlags'=> 177,
* 'GamePort' => 27015,
* 'SteamID' => 90135420658499585,
* 'GameTags' => 'cp,nocrits',
* 'GameID' => 440,
* ]
*/
echo 'Server: ' . $info['HostName'] . PHP_EOL;
echo 'Map: ' . $info['Map'] . PHP_EOL;
echo 'Players: ' . $info['Players'] . '/' . $info['MaxPlayers'] . PHP_EOL;
echo 'VAC: ' . ($info['Secure'] ? 'Yes' : 'No') . PHP_EOL;
if (isset($info['GameTags'])) {
echo 'Tags: ' . $info['GameTags'] . PHP_EOL;
}
} catch (InvalidPacketException $e) {
echo 'Bad packet: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### Retrieve Player List with SourceQuery::GetPlayers()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Fetches a list of currently connected players from a Source game server after acquiring a challenge number. Returns an array of player details including name, frags, and playtime. Ensure proper error handling for connection and packet issues.
```php
Connect('192.168.1.100', 27015, 3, SourceQuery::SOURCE);
$players = $query->GetPlayers();
/*
* Example return value:
* [
* ['Id' => 0, 'Name' => 'PlayerOne', 'Frags' => 42, 'Time' => 3723, 'TimeF' => '01:02:03'],
* ['Id' => 0, 'Name' => 'PlayerTwo', 'Frags' => 7, 'Time' => 305, 'TimeF' => '05:05'],
* ['Id' => 0, 'Name' => '[BOT] HAL', 'Frags' => 100, 'Time' => 7200, 'TimeF' => '02:00:00'],
* ]
*/
echo count($players) . " player(s) online:\n";
foreach ($players as $player) {
printf(
" %-30s Frags: %4d Time: %s\n",
$player['Name'],
$player['Frags'],
$player['TimeF']
);
}
} catch (InvalidPacketException $e) {
echo 'Bad packet: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### Connect to a Game Server
Source: https://context7.com/xpaw/php-source-query/llms.txt
Opens a UDP socket to the target server. Must be called before any query or RCON method. The `$Engine` parameter selects the wire protocol: `SourceQuery::SOURCE` (default) for all Source/Steamworks games, or `SourceQuery::GOLDSOURCE` for Half-Life 1 era servers and HLTV.
```php
Connect('192.168.1.100', 27015, timeout: 3, Engine: SourceQuery::SOURCE);
// --- do queries here ---
} catch (InvalidArgumentException $e) {
// Thrown when $Timeout < 0
echo 'Bad argument: ' . $e->getMessage();
} catch (SocketException $e) {
// Thrown when the UDP socket cannot be created
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
// GoldSource example (CS 1.6, Half-Life mods)
$gsQuery = new SourceQuery();
try {
$gsQuery->Connect('192.168.1.50', 27015, 3, SourceQuery::GOLDSOURCE);
} finally {
$gsQuery->Disconnect();
}
```
--------------------------------
### Enable Legacy Challenge Retrieval for Starbound
Source: https://context7.com/xpaw/php-source-query/llms.txt
Use `SetUseOldGetChallengeMethod(true)` before calling `GetPlayers()` or `GetRules()` to enable the legacy challenge retrieval method. This is necessary for games like Starbound that do not support the modern challenge flow. Returns the previous setting.
```php
Connect('starbound.example.com', 21025, 3, SourceQuery::SOURCE);
// Must be called after Connect() and before GetPlayers() / GetRules()
$previous = $query->SetUseOldGetChallengeMethod(true);
echo 'Old method was previously: ' . ($previous ? 'enabled' : 'disabled') . PHP_EOL;
$players = $query->GetPlayers(); // Now works on Starbound
$rules = $query->GetRules();
print_r($players);
print_r($rules);
} catch (Exception $e) {
echo $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### GetInfo
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Retrieves general information about the server.
```APIDOC
## GetInfo
### Description
Returns server info in an array.
### Method
GetInfo
### Parameters
None
### Response
#### Success Response (200)
- **server_info** (array) - An array containing server information.
```
--------------------------------
### SourceQuery::Connect()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Opens a UDP socket to the target server. This method must be called before any query or RCON method. It supports selecting the wire protocol for Source or GoldSource engines.
```APIDOC
## SourceQuery::Connect()
### Description
Opens a UDP socket to the target server. Must be called before any query or RCON method. The `$Engine` parameter selects the wire protocol: `SourceQuery::SOURCE` (default) for all Source/Steamworks games, or `SourceQuery::GOLDSOURCE` for Half-Life 1 era servers and HLTV.
### Method
```php
public SourceQuery::Connect(string $Host, int $Port, float $Timeout = 3.0, int $Engine = SourceQuery::SOURCE)
```
### Parameters
#### Path Parameters
- **Host** (string) - The IP address or hostname of the game server.
- **Port** (int) - The port number of the game server.
- **Timeout** (float) - Optional. The connection timeout in seconds. Defaults to 3.0.
- **Engine** (int) - Optional. The engine protocol to use. Use `SourceQuery::SOURCE` (default) or `SourceQuery::GOLDSOURCE`.
### Request Example
```php
Connect('192.168.1.100', 27015, timeout: 3, Engine: SourceQuery::SOURCE);
// --- do queries here ---
} catch (InvalidArgumentException $e) {
// Thrown when $Timeout < 0
echo 'Bad argument: ' . $e->getMessage();
} catch (SocketException $e) {
// Thrown when the UDP socket cannot be created
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
// GoldSource example (CS 1.6, Half-Life mods)
$gsQuery = new SourceQuery();
try {
$gsQuery->Connect('192.168.1.50', 27015, 3, SourceQuery::GOLDSOURCE);
} finally {
$gsQuery->Disconnect();
}
```
```
--------------------------------
### Execute RCON Commands with SourceQuery
Source: https://context7.com/xpaw/php-source-query/llms.txt
Send commands to a game server via RCON after establishing a connection and setting the RCON password. Handles multi-packet responses automatically. Useful for broadcasting messages, checking server status, or managing players.
```php
Connect('192.168.1.100', 27015, 5, SourceQuery::SOURCE);
$query->SetRconPassword('my_rcon_password');
// Broadcast a message to all players
$response = $query->Rcon('say Server restarting in 5 minutes!');
echo 'say response: ' . $response . PHP_EOL;
// Get the server log (potentially large, multi-packet response)
$status = $query->Rcon('status');
echo $status . PHP_EOL;
// Kick a player by user ID
$kick = $query->Rcon('kickid 42 "AFK"');
echo 'kick response: ' . $kick . PHP_EOL;
// Minecraft RCON (use SOURCE engine)
$mcQuery = new SourceQuery();
$mcQuery->Connect('mc.example.com', 25575, 5, SourceQuery::SOURCE);
$mcQuery->SetRconPassword('minecraft_rcon_password');
$mcResponse = $mcQuery->Rcon('list');
// Returns e.g. "There are 3 of a max of 20 players online: Alice, Bob, Carol"
echo $mcResponse . PHP_EOL;
$mcQuery->Disconnect();
} catch (AuthenticationException $e) {
echo 'RCON auth error: ' . $e->getMessage();
} catch (InvalidPacketException $e) {
echo 'Packet error: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### SourceQuery::SetUseOldGetChallengeMethod()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Enables the legacy challenge retrieval method for specific games that do not support the modern challenge flow. This method must be called after Connect() and before GetPlayers() or GetRules().
```APIDOC
## `SourceQuery::SetUseOldGetChallengeMethod()` — Enable legacy challenge retrieval
Forces the library to request the challenge number using the old `A2S_SERVERQUERY_GETCHALLENGE` (0x57) packet instead of piggybacking on the actual data request. Required for some games (e.g., Starbound) that do not implement the modern challenge flow. Returns the previous value of the flag.
```
--------------------------------
### SourceQuery::GetInfo()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Retrieves rich associative array describing the server. Handles challenge handshake automatically. Returns extra fields when server includes Extra Data Flags. For GoldSource servers, it returns Address, IsMod, and an optional nested Mod array.
```APIDOC
## `SourceQuery::GetInfo()` — Retrieve server information
### Description
Sends an `A2S_INFO` query and returns a rich associative array describing the server. Handles the challenge handshake introduced in newer Source games automatically. Returns extra fields (`GamePort`, `SteamID`, `SpecPort`, `SpecName`, `GameTags`, `GameID`) when the server includes Extra Data Flags in the response. For GoldSource servers it returns `Address`, `IsMod`, and an optional nested `Mod` array.
### Request Example
```php
Connect('192.168.1.100', 27015, 3, SourceQuery::SOURCE);
$info = $query->GetInfo();
/*
* Example return value for a TF2 server:
* [
* 'Protocol' => 17,
* 'HostName' => 'My TF2 Server',
* 'Map' => 'cp_badlands',
* 'ModDir' => 'tf',
* 'ModDesc' => 'Team Fortress',
* 'AppID' => 440,
* 'Players' => 12,
* 'MaxPlayers' => 24,
* 'Bots' => 0,
* 'Dedicated' => 'd', // 'd' = dedicated, 'l' = listen
* 'Os' => 'l', // 'l' = Linux, 'w' = Windows
* 'Password' => false,
* 'Secure' => true,
* 'Version' => '7.7.3.3',
* 'ExtraDataFlags'=> 177,
* 'GamePort' => 27015,
* 'SteamID' => 90135420658499585,
* 'GameTags' => 'cp,nocrits',
* 'GameID' => 440,
* ]
*/
echo 'Server: ' . $info['HostName'] . PHP_EOL;
echo 'Map: ' . $info['Map'] . PHP_EOL;
echo 'Players: ' . $info['Players'] . '/' . $info['MaxPlayers'] . PHP_EOL;
echo 'VAC: ' . ($info['Secure'] ? 'Yes' : 'No') . PHP_EOL;
if (isset($info['GameTags'])) {
echo 'Tags: ' . $info['GameTags'] . PHP_EOL;
}
} catch (InvalidPacketException $e) {
echo 'Bad packet: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
### Response
#### Success Response (200)
- **Protocol** (int) - Protocol version.
- **HostName** (string) - Server name.
- **Map** (string) - Current map.
- **ModDir** (string) - Directory name of the mod.
- **ModDesc** (string) - Description of the mod.
- **AppID** (int) - Application ID.
- **Players** (int) - Number of players currently on the server.
- **MaxPlayers** (int) - Maximum number of players allowed.
- **Bots** (int) - Number of bots on the server.
- **Dedicated** (string) - Server type ('d' for dedicated, 'l' for listen).
- **Os** (string) - Server operating system ('l' for Linux, 'w' for Windows).
- **Password** (bool) - Whether the server is password protected.
- **Secure** (bool) - Whether the server is VAC (Valve Anti-Cheat) enabled.
- **Version** (string) - Server version.
- **ExtraDataFlags** (int) - Flags indicating the presence of extra data.
- **GamePort** (int) - The port the game is running on.
- **SteamID** (int) - The server's SteamID.
- **SpecPort** (int) - The spectator port.
- **SpecName** (string) - The spectator name.
- **GameTags** (string) - Comma-separated list of game tags.
- **GameID** (int) - The game's unique identifier.
- **Address** (string) - Server IP address (for GoldSource).
- **IsMod** (bool) - Whether the server is running a mod (for GoldSource).
- **Mod** (array) - Nested array with mod details (for GoldSource).
```
--------------------------------
### Rcon
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Executes an RCON command on the server.
```APIDOC
## Rcon
### Description
Execute rcon command on the server.
### Method
Rcon
### Parameters
#### Path Parameters
- **Command** (string) - Required - The RCON command to execute.
```
--------------------------------
### Retrieve Server CVars (Rules) with SourceQuery::GetRules()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Sends an A2S_RULES query to retrieve all public console variables (CVars) exposed by the server. The challenge token is reused from a prior GetPlayers() call if available. Handles InvalidPacketException and SocketException.
```php
Connect('192.168.1.100', 27015, 3, SourceQuery::SOURCE);
$rules = $query->GetRules();
/*
* Example return value (TF2 + SourceMod server):
* [
* 'mp_timelimit' => '30',
* 'mp_friendlyfire' => '0',
* 'sv_cheats' => '0',
* 'sm_nextmap' => 'cp_granary',
* 'tf_weapon_criticals' => '0',
* ... (potentially hundreds of entries)
* ]
*/
echo count($rules) . " rule(s):\n";
// Check a specific rule
if (isset($rules['sv_cheats'])) {
echo 'sv_cheats = ' . $rules['sv_cheats'] . PHP_EOL;
}
// Print all rules sorted
ksort($rules);
foreach ($rules as $name => $value) {
echo " $name = $value\n";
}
} catch (InvalidPacketException $e) {
echo 'Bad packet: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### Ping Server with SourceQuery::Ping()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Sends an A2A_PING packet to check server liveness. Returns true if an A2A_ACK response is received. Note: Many Source engine games do not respond to ping packets; use GetInfo() for a reliable check. Handles InvalidPacketException and SocketException.
```php
Connect('192.168.1.50', 27015, 2, SourceQuery::GOLDSOURCE);
$alive = $query->Ping(); // true or false
echo $alive ? "Server is up.\n" : "No ping response (may still be up).\n";
} catch (InvalidPacketException | SocketException $e) {
echo 'Error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### GetPlayers
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Retrieves a list of players currently on the server.
```APIDOC
## GetPlayers
### Description
Returns players on the server in an array.
### Method
GetPlayers
### Parameters
None
### Response
#### Success Response (200)
- **players** (array) - An array containing player data.
```
--------------------------------
### Authenticate for RCON with SourceQuery::SetRconPassword()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Authenticates for RCON access by opening a separate TCP socket and performing protocol-level authentication. Must be called before Rcon(). Handles AuthenticationException and SocketException.
```php
Connect('192.168.1.100', 27015, 5, SourceQuery::SOURCE);
// Throws AuthenticationException if the password is wrong
// Throws SocketException if the TCP connection fails
$query->SetRconPassword('my_rcon_password');
echo "RCON authenticated successfully.\n";
} catch (AuthenticationException $e) {
// $e->getCode() === AuthenticationException::BAD_PASSWORD (1)
// $e->getCode() === AuthenticationException::BANNED (2)
echo 'Authentication failed: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Connection error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### SourceQuery::GetRules()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Retrieves all public console variables (CVars) exposed by the server. It sends an A2S_RULES query and returns a flat string-to-string associative array. The challenge token is reused if a prior GetPlayers() call was made.
```APIDOC
## `SourceQuery::GetRules()` — Retrieve server CVars (rules)
Sends an `A2S_RULES` query and returns a flat `string => string` associative array of all public console variables (CVars) the server exposes. The challenge is reused from a prior `GetPlayers()` call if available.
### Method
```php
public SourceQuery::GetRules(): array
```
### Returns
An associative array where keys are CVar names and values are their string representations.
### Example
```php
Connect('192.168.1.100', 27015, 3, SourceQuery::SOURCE);
$rules = $query->GetRules();
// Example return value (TF2 + SourceMod server):
// [
// 'mp_timelimit' => '30',
// 'mp_friendlyfire' => '0',
// 'sv_cheats' => '0',
// 'sm_nextmap' => 'cp_granary',
// 'tf_weapon_criticals' => '0',
// ... (potentially hundreds of entries)
// ]
echo count($rules) . " rule(s):\n";
// Check a specific rule
if (isset($rules['sv_cheats'])) {
echo 'sv_cheats = ' . $rules['sv_cheats'] . PHP_EOL;
}
// Print all rules sorted
ksort($rules);
foreach ($rules as $name => $value) {
echo " $name = $value\n";
}
} catch (InvalidPacketException $e) {
echo 'Bad packet: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
```
--------------------------------
### SourceQuery::Rcon()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Executes a remote console command over an authenticated RCON connection. It automatically handles multi-packet responses and must be called after SetRconPassword().
```APIDOC
## `SourceQuery::Rcon()` — Execute a remote console command
Sends a command string over the authenticated RCON TCP connection and returns the server's response as a plain string. Handles multi-packet responses automatically (Source RCON responses ≥ 4000 bytes trigger the sentinel-packet workaround). Must be called after a successful `SetRconPassword()`.
```
--------------------------------
### SourceQuery::Ping()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Pings the server by sending an A2A_PING packet and expecting an A2A_ACK response. Returns true if the server responds, indicating it is alive. Note that many Source engine games may not respond to ping packets.
```APIDOC
## `SourceQuery::Ping()` — Ping the server
Pings the server by sending an `A2A_PING` packet and checking for an `A2A_ACK` response. Returns `true` if the server is alive. **Note:** many Source engine games (e.g., TF2) do not respond to ping packets; use `GetInfo()` as a reliable liveness check instead.
### Method
```php
public SourceQuery::Ping(): bool
```
### Returns
`true` if the server responds to the ping, `false` otherwise.
### Example
```php
Connect('192.168.1.50', 27015, 2, SourceQuery::GOLDSOURCE);
$alive = $query->Ping(); // true or false
echo $alive ? "Server is up.\n" : "No ping response (may still be up).\n";
} catch (InvalidPacketException | SocketException $e) {
echo 'Error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
```
--------------------------------
### Ping
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Pings the server to check if it is online. Note: The Source engine may not respond to this ping.
```APIDOC
## Ping
### Description
Ping the server to see if it exists.
Warning: Source engine may not answer to this.
### Method
Ping
### Parameters
None
```
--------------------------------
### Handle SourceQuery Exceptions with Typed Error Codes
Source: https://context7.com/xpaw/php-source-query/llms.txt
Catch specific exceptions like `InvalidArgumentException`, `AuthenticationException`, `InvalidPacketException`, and `SocketException` to handle errors gracefully. Each exception provides integer error codes as constants for detailed error identification.
```php
Connect('192.168.1.100', 27015, 3, SourceQuery::SOURCE);
$query->SetRconPassword('wrong_password');
$query->Rcon('status');
} catch (InvalidArgumentException $e) {
// Connect() was called with a negative timeout
echo '[InvalidArgument] ' . $e->getMessage();
} catch (AuthenticationException $e) {
match ($e->getCode()) {
AuthenticationException::BAD_PASSWORD => print('[Auth] Wrong RCON password.');
AuthenticationException::BANNED => print('[Auth] This IP is banned from RCON.');
default => print('[Auth] ' . $e->getMessage());
};
} catch (InvalidPacketException $e) {
// Error codes: PACKET_HEADER_MISMATCH=1, BUFFER_EMPTY=2,
// BUFFER_NOT_EMPTY=3, CHECKSUM_MISMATCH=4, UNPACK_FAILED=5
echo '[Packet #' . $e->getCode() . '] ' . $e->getMessage();
} catch (SocketException $e) {
// Error codes: COULD_NOT_CREATE_SOCKET=1, NOT_CONNECTED=2,
// CONNECTION_FAILED=3, INVALID_ENGINE=4
echo '[Socket #' . $e->getCode() . '] ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
--------------------------------
### GetRules
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Retrieves the public rules (cvars) of the server.
```APIDOC
## GetRules
### Description
Returns public rules (cvars) in an array.
### Method
GetRules
### Parameters
None
### Response
#### Success Response (200)
- **rules** (array) - An array containing server rules.
```
--------------------------------
### SourceQuery::GetPlayers()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Retrieves the current player list by sending an A2S_PLAYER query. Returns an indexed array of players, each with details like ID, Name, Frags, Time, and TimeF (formatted playtime).
```APIDOC
## `SourceQuery::GetPlayers()` — Retrieve the current player list
### Description
Sends an `A2S_PLAYER` query (acquiring a challenge number first) and returns an indexed array where each element is an associative array describing one connected player. The `TimeF` field is a pre-formatted human-readable playtime string.
### Request Example
```php
Connect('192.168.1.100', 27015, 3, SourceQuery::SOURCE);
$players = $query->GetPlayers();
/*
* Example return value:
* [
* ['Id' => 0, 'Name' => 'PlayerOne', 'Frags' => 42, 'Time' => 3723, 'TimeF' => '01:02:03'],
* ['Id' => 0, 'Name' => 'PlayerTwo', 'Frags' => 7, 'Time' => 305, 'TimeF' => '05:05'],
* ['Id' => 0, 'Name' => '[BOT] HAL', 'Frags' => 100, 'Time' => 7200, 'TimeF' => '02:00:00'],
* ]
*/
echo count($players) . " player(s) online:\n";
foreach ($players as $player) {
printf(
" %-30s Frags: %4d Time: %s\n",
$player['Name'],
$player['Frags'],
$player['TimeF']
);
}
} catch (InvalidPacketException $e) {
echo 'Bad packet: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Socket error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
### Response
#### Success Response (200)
- **Id** (int) - Player ID.
- **Name** (string) - Player name.
- **Frags** (int) - Number of frags.
- **Time** (int) - Playtime in seconds.
- **TimeF** (string) - Formatted playtime string.
```
--------------------------------
### Disconnect
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Closes all open connections to game servers.
```APIDOC
## Disconnect
### Description
Closes all open connections.
### Method
Disconnect
### Parameters
None
```
--------------------------------
### Exception Hierarchy
Source: https://context7.com/xpaw/php-source-query/llms.txt
Provides typed error handling for exceptions thrown by the SourceQuery library. All exceptions extend `SourceQueryException` and expose integer error codes for detailed error management.
```APIDOC
## Exception Hierarchy — Typed error handling
All exceptions extend `SourceQueryException` (which extends `\RuntimeException`) and expose integer error codes as class constants for fine-grained error handling.
```
--------------------------------
### SourceQuery::SetRconPassword()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Authenticates for RCON access by opening a separate TCP socket to the server's RCON port. It supports both the Source RCON Protocol and the older GoldSource challenge-string method. This method must be called before using the Rcon() method.
```APIDOC
## `SourceQuery::SetRconPassword()` — Authenticate for RCON
Opens a separate TCP socket to the server's RCON port and performs protocol-level authentication. For Source engine servers this follows the [Source RCON Protocol](https://developer.valvesoftware.com/wiki/Source_RCON_Protocol); for GoldSource servers it uses the older challenge-string method. Must be called before `Rcon()`.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Method
```php
public SourceQuery::SetRconPassword(string $password): void
```
### Parameters
- **password** (string) - Required - The RCON password for the server.
### Throws
- `AuthenticationException` if the provided password is incorrect or the client is banned.
- `SocketException` if the TCP connection to the RCON port fails.
### Example
```php
Connect('192.168.1.100', 27015, 5, SourceQuery::SOURCE);
// Throws AuthenticationException if the password is wrong
// Throws SocketException if the TCP connection fails
$query->SetRconPassword('my_rcon_password');
echo "RCON authenticated successfully.\n";
} catch (AuthenticationException $e) {
// $e->getCode() === AuthenticationException::BAD_PASSWORD (1)
// $e->getCode() === AuthenticationException::BANNED (2)
echo 'Authentication failed: ' . $e->getMessage();
} catch (SocketException $e) {
echo 'Connection error: ' . $e->getMessage();
} finally {
$query->Disconnect();
}
```
```
--------------------------------
### Disconnect from a Game Server
Source: https://context7.com/xpaw/php-source-query/llms.txt
Closes the UDP query socket and (if open) the TCP RCON socket, and resets the challenge state. Also called automatically by the destructor. Always disconnect in a finally block.
```php
Connect('192.168.1.100', 27015);
$info = $query->GetInfo();
print_r($info);
} catch (Exception $e) {
echo $e->getMessage();
} finally {
// Always disconnect in a finally block
$query->Disconnect();
}
// The destructor also calls Disconnect(), so the connection is safe even without finally.
```
--------------------------------
### SourceQuery::Disconnect()
Source: https://context7.com/xpaw/php-source-query/llms.txt
Closes all open connections, including the UDP query socket and the TCP RCON socket. This method also resets the challenge state. It is automatically called by the destructor.
```APIDOC
## SourceQuery::Disconnect()
### Description
Closes all open connections, including the UDP query socket and (if open) the TCP RCON socket, and resets the challenge state. Also called automatically by the destructor.
### Method
```php
public SourceQuery::Disconnect(): void
```
### Request Example
```php
Connect('192.168.1.100', 27015);
$info = $query->GetInfo();
print_r($info);
} catch (Exception $e) {
echo $e->getMessage();
} finally {
// Always disconnect in a finally block
$query->Disconnect();
}
// The destructor also calls Disconnect(), so the connection is safe even without finally.
```
```
--------------------------------
### SetRconPassword
Source: https://github.com/xpaw/php-source-query/blob/master/README.md
Sets the RCON password for subsequent RCON commands.
```APIDOC
## SetRconPassword
### Description
Sets rcon password for later use with Rcon().
### Method
SetRconPassword
### Parameters
#### Path Parameters
- **Password** (string) - Required - The RCON password.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.