Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Created April 28, 2017 02:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bohwaz/6d01bf00fdb4721a601c4b9fc1007d81 to your computer and use it in GitHub Desktop.
Save bohwaz/6d01bf00fdb4721a601c4b9fc1007d81 to your computer and use it in GitHub Desktop.
Fetches timestamp from a NTP server in PHP
<?php
/**
* Returns UNIX timestamp from a NTP server (RFC 5905)
*
* @param string $host Server host (default is pool.ntp.org)
* @param integer $timeout Timeout in seconds (default is 10 seconds)
* @return integer Number of seconds since January 1st 1970
*/
function getTimeFromNTP($host = 'pool.ntp.org', $timeout = 10)
{
$socket = stream_socket_client('udp://' . $host . ':123', $errno, $errstr, (int)$timeout);
$msg = "\010" . str_repeat("\0", 47);
fwrite($socket, $msg);
$response = fread($socket, 48);
fclose($socket);
// unpack to unsigned long
$data = unpack('N12', $response);
// 9 = Receive Timestamp (rec): Time at the server when the request arrived
// from the client, in NTP timestamp format.
$timestamp = sprintf('%u', $data[9]);
// NTP = number of seconds since January 1st, 1900
// Unix time = seconds since January 1st, 1970
// remove 70 years in seconds to get unix timestamp from NTP time
$timestamp -= 2208988800;
return $timestamp;
}
@Sigri44
Copy link

Sigri44 commented Apr 13, 2018

Response is "-2208988800".
If i comment this line, the result is 0....

@fzed51
Copy link

fzed51 commented Jun 1, 2021

Hello! Please note, I encountered a problem with a 32bit architecture. Indeed unpack returns negative values because the returned values are> PHP_INT_MAX.
In line 26, I added:

if ($timestamp < 0) {
  $timestamp += (double)4294967296;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment