Wednesday, January 22, 2014

Retrive timestamp from an NTP server using PHP

In my PHP application, I needed to retrive time from NTP server using PHP.
NTP server uses port 123 and I needed to communicate to pool.ntp.org with UDP port 123.
I used the following function to retrive time.

function getNtpTime($host = "pool.ntp.org") {

    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    socket_connect($sock, $host, 123);

    $msg = "\010" . str_repeat("\0", 47);
    socket_send($sock, $msg, strlen($msg), 0);
    
    socket_recv($sock, $recv, 48, MSG_WAITALL);
    socket_close($sock);
    
    $data = unpack('N12', $recv);
    $timestamp = sprintf('%u', $data[9]);
    $timestamp -= 2208988800;

    return $timestamp;
}