Skip to main content

How to tell if your MineCraft server is online using PHP and socket connection.

You can open a socket connection inside of php. Using @fsockopen function. This is simple code so i will show you a example.

<?php
//ip address of you server
$ip = "127.0.0.1";
//port of your minecraft server
$port = 25565;

// create a connection using the fsockopen function

$coonectionStream = @fsockopen( $ip, $port, $errno, $errstr, 2);

//check if the connection worked and the server is online

if($coonectionStream >= 1) {
    echo 'MineCraft server is online';
    //echo out information if server is online
} else {
    echo 'MineCraft server is offline';
    //echo out information if server is offline
}
?>

Just one note the last parameter to be passed to the fsockopen function is the connection time out this is the length of time that the fsockopen function will try and connect to the socket over the given ip. Why this is important is because this holds up the server from returning any information to the page. So if you have 2 seconds there it will try and connect for 2 seconds before returning any information. Not a big deal but if you increase the time then people may not wait for you page to load because it is just taking to long for it to fail and say there server is offline.

I hope this helps!

For more information on the fsockopen function go here.

If anyone has any questions or would like information about any other subject involving  PHP, JavaScript, Jquery, or CSS please leave a comment and I’ll write a post about it.

Array? How do we save them?

php serialize codeSo the other day I was working on how to build a chess application with PHP. I started to think about building the board by creating a array with eight sub arrays. This allows me to make the whole board and single variable. This was easy to set up. Then I realized how will i save this to a data base? The answer to this is a two functions serialize() and unserialize(). What they do is take an array and tern it into a savable text string. For example if you take the code.

<?php
//Creates an array
$array = array('one'=>1,'two'=>2);
//Serializes the array (makes is savable)
$array_unserialized = serialize($array);
//Echos out the array.
echo $array_unserialized;
?>

This code out puts a:2:{s:3:”one”;i:1;s:3:”two”;i:2;} The nice thing about the serialize functions is that you can also send it multidimensional arrays. To tern it back into a usable array you would do.

<?php
//Terns the array back to the array.
$array_new = unserialize($array_unserialized);
//Does something with the array.
var_dump($array_new);
?>

This code outputs you guessed it array(2) { [“one”]=> int(1) [“two”]=> int(2) }

Just a little handy tool.

Warning: Don’t pass user data to unserialize() a malicious user can use it to exploit your site. To find out more look at http://php.net/manual/en/function.unserialize.php and look under Notes.