Skip to content

Instantly share code, notes, and snippets.

@mikaelz
Forked from bohwaz/get_time_from_ntp.php
Created September 17, 2018 10:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelz/32e3bf3ca0951331cdef442ed796e185 to your computer and use it in GitHub Desktop.
Save mikaelz/32e3bf3ca0951331cdef442ed796e185 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment