-3

Is there a way I can convert this function to be ran from a cron job and then insert the data it returns into a database?

public function ping($host, $port=25565, $timeout=0.1) {
//Set up our socket
    $beginning_time = microtime(true);
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    if (!$fp) return false;
    $end_time = microtime(true);

//Send 0xFE: Server list ping
    fwrite($fp, "\xFE");

//Read as much data as we can (max packet size: 241 bytes)
    $d = fread($fp, 256);

//Check we've got a 0xFF Disconnect
    if ($d[0] != "\xFF") return false;

//Remove the packet ident (0xFF) and the short containing the length of the string
    $d = substr($d, 3);

//Decode UCS-2 string
    $d = mb_convert_encoding($d, 'auto', 'UCS-2');

//Split into array
    $d = explode("\xA7", $d);

//Return an associative array of values
    return array(
        'motd'        =>        $d[0],
        'players'     => intval($d[1]),
        'max_players' => intval($d[2]),
        'latency'     => ($end_time - $beginning_time) * 1000);
}

The data it's returning is what is in the array at the end.

4
  • 1
    Err... yes. You just write a script that calls the function, then uses the data it returns with PDO. Then you set up a cron job to call that script.
    – Quentin
    Apr 26, 2012 at 13:25
  • I'm kind of new to PHP and stuff, how would this be done exactly?
    – WittyPleb
    Apr 26, 2012 at 13:26
  • 1
    @unlucky4ever - 1st get the script to run on the command line and produce the desired effect. 2nd, look up the manual pages for crontab.
    – Ed Heal
    Apr 26, 2012 at 13:28
  • 1
    You appear to have two entirely different questions here. "How do I deal with SQL databases in PHP?" and "How do I set up cron jobs?" … both of which are far better answered by finding introductory tutorials then by asking questions on SO.
    – Quentin
    Apr 26, 2012 at 13:37

1 Answer 1

4

You can run any PHP file from the commandline. So the same command can be used in a cron. No need to convert anything.

/usr/local/bin/php /home/test.php

The path /usr/local/bin/php should be the location of your php binary.

1
  • 1
    Okay thanks, I should have researched a bit more... I can see now how I would make it so it inserts data and so forth, but I have never done cron jobs before, how would I go about setting one up?
    – WittyPleb
    Apr 26, 2012 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.