Checking the Status of a Minecraft Server with PHP

Have you ever needed to have a script check whether a Minecraft server was online, or retrieve its listing information, like the “Message of the Day” (server description) or the number of active players? Maybe you run your own server, and want to display the status on a community website. Or perhaps you have something more ambitious in mind.

After reading up on the protocol Minecraft uses for the in-game listing of your favorite servers, I put together a simple PHP class that makes it easy. Here’s a fancy demo that makes use of it.

The library, which you can download on GitHub, along with the aforementioned demo page, looks like this:

< ?php

class MCServerStatus {

	public $server;
	public $online, $motd, $online_players, $max_players;
	public $error = "OK";

	function __construct($url, $port = '25565') {

		$this->server = array(
			"url" => $url,
			"port" => $port
		);

		if ( $sock = @stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) {

			$this->online = true;

			fwrite($sock, "\xfe");
			$h = fread($sock, 2048);
			$h = str_replace("\x00", '', $h);
			$h = substr($h, 2);
			$data = explode("\xa7", $h);
			unset($h);
			fclose($sock);

			if (sizeof($data) == 3) {
				$this->motd = $data[0];
				$this->online_players = (int) $data[1];
				$this->max_players = (int) $data[2];
			}
			else {
				$this->error = "Cannot retrieve server info.";
			}

		}
		else {
			$this->online = false;
			$this->error = "Cannot connect to server.";
		}

	}

}

There are some code snippets strewn around the internet that do essentially the same thing, but without the handy wrapper class.

To query a server, you instantiate the class and pass it the IP or domain name of the server, as well as the port if it is not the default Minecraft port of 25565. (Do not include “http://” or any slashes. Just the hostname or IP.)

include "MCServerStatus.php";
$server = new MCServerStatus("s.nerd.nu", 25565); //The second argument is optional in this case

Once you have created a new instance of the object, you can use the information that it gathered.

$var = $server->online; //$server->online returns true if the server is online, and false otherwise
echo $server->motd; //Outputs the Message of the Day
echo $server->online_players; //Outputs the number of players online
echo $server->max_players; //Outputs the maximum number of players the server allows
print_r($server); //Shows an overview of the object and its contents. (For debugging.)

Now go and play some Minecraft!

Update: MCServerStatus is now on Github. Fork away!

Update 2012/11/12: The version of the library available on GitHub has been updated to work with the new protocol in Minecraft 1.4.

  • http://www.ater.enjin.com bobacadodl

    Thank you SO much for this easy to use interface. I had been searching for something SIMPLE so that a beginner like me could actually use it. This was exactly what I was looking for. Thank you for the great work.

  • JRockie

    Hello guys. I have a problem where when I put the file online it doesn’t display the server online. When I use wamp on my computer it works, but when I use my web host it doesn’t.

    Site: http://hg-mc.co.cc/demo/

    I have hosting with Hostgator, business plan.
    Can anyone please help. Can it be a problem with the PHP? Maybe the function is not supported. Can you help me out please.

    The server I am trying to connect is 24/7 on a dedicated server. Again it does work on wamp but not on my host.

    • http://www.webmaster-source.com Matt

      Maybe your host has disabled the stream_socket_client() function?

      • Stella

        Your host might also have blocked the port (that’s what mine did. I contacted them and they allowed the port through)

  • Sean

    Any way to sort that the list by status? Like if I wanted all the online servers to be at the top, then sort it by amount of players? I was looking at the option in PHP called “usort()” but I didn’t want to get ahead of myself.. maybe you might know a better way..

    Thanks in advance,
    -Sean

    • http://www.webmaster-source.com Matt

      You’re on the right track. The easiest way to do it would probably be to have the foreach loop store the info it collects about each server in an array. Then use usort() on that before creating a new foreach loop to output the contents of the array.

  • Stella

    Can it be modified to get the list of players/plugins etc aswell? Appreciate the help! this is the first class that’s worked for me so far!

  • Darione

    hey man, nice project, but it doesn’t work for me. Max players are stuck on 0/0 and motd message doesnt work. Can you help me? Can you make a tutorial video? Thx

    • http://www.constantpvp.com/ Constant PvP

      Hey Darione, I also had this same problem when setting up the script on my server tonight. I was able to fix it by following steps previously mentioned by Stella, which involves contacting your web hosting provider and having them open up/allow access to the minecraft server port. If your hosted with HostGator just contact them with live chat and they’ll have it working in minutes.

  • Phoenix

    Hey Matt!
    Love your work, helped me out alot!
    I was just wondering if there is any way to return the ping timer in milliseconds?
    I’m currently working on a project where i want to put the ping time in a database so i can create a procente of how much the server is online.
    Any help would be greatly appreciated!

    ps. I know I could do it with the online variable as well but i’m making a grid in javaScript to show the ping at a certain point in time.

    Thanks in advance!

  • Phoenix

    Hey Matt, Phoenix here again.
    I was wonder if you could do a guide how to update this code?
    It seems bukkit change some protocole(as i’ve understood it) and the code no longer works.
    If you could go into how to do it yourself so we could find it ourselves for upcoming versions of bukkit, would be really helpful.
    Thank you in advance!

    Phoenix.

  • http://www.minecraftcode.net minecraft gift code

    hiiii
    good project thanks for this post

  • http://serverofminecraft.com/ Pravin

    Hello,

    I added same script on my site but online members are not showing also not showing online/offline.

    My server is linux base can i know hot to fix this issue please check below link for it.
    http://serverofminecraft.com/server/demo/

    Minecraft port 25565 is not working. :(

    Waiting for your reply

    Thank you

    • http://www.webmaster-source.com Matt

      Mojang changed the protocol in 1.4. I’m going to update it soon, once I get around to it.

  • Matt

    Nice work man, This is exactly what I’m after. Just curious however, can anybody confirm/deny that this script works with Bukkit servers? or does it have to be vanilla?

    • Phoenix

      This should work for both.
      I’ve modified the script myself a bit but it does work for bukkit.

    • http://www.webmaster-source.com Matt

      It definitely works with Bukkit servers. I tested it with the ones I play on, and they use Bukkit. (They try to keep it reasonably vanilla, but they have to have a bunch of moderator plugins to keep the peace.)

  • Telmine

    Hey,
    Great work, I haven’t implemented yet but it sounds perfect. I am curious though… the files I downloaded from GitHub look nothing like the implementation described above. I’m not good at writing PHP but I can work around it, unfortunately the demo seems really really cryptic and overly complicated. Would it work if I just copied and pasted your script above and implemented as you described? If not could you update your instructions?

    Thanks

    • http://www.webmaster-source.com Matt

      The version on GitHub is much newer, and has had a few contributions from other users. It’s built more for the style of code encouraged by the PSR-0 guidelines, and requires a minimum of PHP 5.3. It’s less simple, but it plays nicer with modern conventions and frameworks.

      The last I checked, the simpler script above still worked for me. The protocol in Minecraft changed in the last update, but the script was still working at the time, so I assume there’s some backwards compatibility. (I might update the script here in the future to use the changes, when I get around to it, for the sake of the future. It seems to work, though.)

  • Paul

    I was wondering, could you make a version that has a HTML for that submits the data?

  • http://stormforgemc.com Delbert Johnson

    I am getting this error any help? “Warning: stream_socket_client(): unable to connect to tcp://stormforgemc.com:25565 (Connection refused)”

  • http://hundevelopers.hu Dawars

    Thanks very much!
    Can I somehow request the list of the online players?

  • you could check here

    Diamonds are expensive but still they are bought and sold on an incredible velocity.
    Christian jewelry is extra special jewelry
    because usually it all has a meaning to go with it. I’ve certain bracelets as well as ear-rings that we wear with certain pieces from your wardrobe bought particularly for your objective.

  • James

    I’m curious whether do we need a VPS to set up this, pls tell me if anyone know?

    • http://www.webmaster-source.com Matt

      You shouldn’t need one, so long as your host doesn’t disable remote socket connections.

  • http://serverofminecraft.com/demo/demo/ Pravin

    http://serverofminecraft.com/demo/demo/

    Please check this one and Please suggest what can i do for this error ?

    Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to tcp://s.nerd.nu:0 (Connection timed out) in /home/serverof/public_html/demo/MCServerStatus/Minecraft/Stats.php on line 10

    Waiting for your reply

    • http://www.webmaster-source.com Matt

      Your web host is probably blocking the port Minecraft uses in their firewall.

  • SacredFort

    Is this supported with the 1.5 update? The current version is 1.5.2 right now.

    • http://www.webmaster-source.com Matt

      The version on GitHub should still be supported, as the protocol hasn’t changed since 1.4, though I haven’t tested the one in the post in awhile.

  • http://9minecrafttool.blogspot.com Minecraft Tools

    I like the valuable information you provide in your articles.
    I’ll bookmark your blog and check again here regularly. I’m quite
    sure I’ll learn a lot of new stuff right here! Best of luck for the next!

  • http://mczona.lt Factor

    Hello,

    I have one question, I have server with new Minecraft version (1.6.1) but server monitor isn’t working, working but don’t show players online and max online. Now show 0/0, how I can fix it?

  • Complete Newb

    Hello, I’ve managed to get your script working with NearlyFreeSpeech, but I can’t seem to catch the exception, when the server is down (it works fine with the server is up). I’ve placed it in a try/catch block:

    try {
    if($statsmc->is_online)
    {
    //whatever
    } else {
    //whatever
    }
    catch (StatsException $e) {
    // display error message
    }

    However, it just throws an error with a FPD:

    Fatal error: Uncaught exception ‘Minecraft\StatsException’ with message ‘Could not connect to the Minecraft server.’

    How would I catch this?

  • http://techprey.net Jonas

    Hello, I found some issus, and that is when the server dosent have the port 25565, like one of main it have 25515 and i am not allowed to chanche it…
    so when i type the server ip and port in, it is comming an error “Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to tcp://serveraddres.com:25515:25565 (Connection timed out) in /home/techprey/public_html/demo/MCServerStatus/Minecraft/Stats.php on line 9

    Fatal error: Call to undefined function Minecraft\StatsException() in /home/techprey/public_html/demo/MCServerStatus/Minecraft/Stats.php on line 12″
    as you might see the server address is “tcp://serveraddres.com:25515:25565 ” when it shuld be “tcp://serveraddres.com:25515″… how can i fix that ?

  • http://brainee.dyndns.org BrAiNee

    Hi i found this Script on a forum but its the same :) Its the best what i found and i love it its smal simple and doesnt output bad values or other unusefull words. thx for this script.

    BrAiNee

  • HoyLRam

    Very Very Very Thank You Coding ;)

  • http://www.woodstone.nu/salive Amma Rany

    Hi . very pleased to see the explanation. waiting for other interesting posts at a time when that will come.
    From bvba Woodstone

  • jayden

    i get this errormsg:

    MCServerStatus Object ( [server] => Array ( [url] => thedarkage.nl [port] => 25565 ) [online] => 1 [motd] => [online_players] => [max_players] => [error] => Cannot retrieve server info. ) it is a 1.7 minecraft server(not mine using it as test) did protcal change? please make a new one if it has

    • Themuddfamily

      This is not an error I’m guessing you print_r’d it.

  • Rikard

    So now i only wonder how do i get all to work the description is far from helping

  • Mary Solero

    This is awesome. Thank you. waterproofing services

  • Jack Selleck

    what server did you use on this one? Because there is this one server that I always entered and it always crashes Stump Grinding in Orland Park IL