-
Notifications
You must be signed in to change notification settings - Fork 22
/
MinecraftServerBasic.php
81 lines (71 loc) · 1.97 KB
/
MinecraftServerBasic.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
<?php
/**
* Minecraft server simple status (fallback)
* Read the basic server info which is intended for minecraft clients
* @author noxifoxi https://github.com/noxifoxi
* @license GNU Public Licence - Version 3
* @copyright © 2011-2022 noxifoxi
*/
class MinecraftServerBasic {
private $socket;
private $info = [];
public function __get($property) {
if (array_key_exists($property, $this->info))
return $this->info[$property];
}
public function __construct(string $host, int $port = 25565, int $timeout = 1) {
$this->socket = @stream_socket_client('tcp://' . $host . ':' . $port, $errNo, $errStr, $timeout);
if (!$this->socket) {
$this->info['online'] = 0;
return;
}
stream_set_timeout($this->socket, $timeout);
// Request server status
fwrite($this->socket, "\xfe");
// Read received info
$data = fread($this->socket, 2048);
// Remove the nulls
$data = str_replace("\x00", '', $data);
// drop the first two bytes
$data = substr($data, 2);
// split/parse information
$info = explode("\xa7", $data);
unset($data);
// Close connection
fclose($this->socket);
/*
populate/parse info
*/
if(sizeof($info) == 3) {
$this->info = [
'hostname' => $info[0], // motd
'numplayers' => (int) $info[1],
'maxplayers' => (int) $info[2],
'online' => 1
];
} else if(sizeof($info) > 3) {
// try to handle occuring errors, Minecraft doesn't handle this.
$tmp = '';
for($i = 0; $i < sizeof($info) - 2; $i++) {
$tmp .= ($i > 0 ? '§' : '').$info[$i];
}
$this->info = [
'hostname' => $tmp, // motd
'numplayers' => (int) $info[sizeof($info) - 2],
'maxplayers' => (int) $info[sizeof($info) - 1],
'online' => 1,
'error' => 'Unreadable "motd"'
];
} else {
$this->info['error'] = 'Unexpected error';
$this->info['online'] = 0;
}
$this->info += [
'hostport' => $port,
'hostip' => $host
];
}
public function getInfoArray(): array {
return $this->info;
}
}