Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Query Time from a NTP Server with PHP

A time server is a computer server that reads the precise time from a reference source and distributes this information to various clients. The most widely used protocol for distributing and synchronising time over the Internet is the Network Time Protocol (NTP), though other less-popular or outdated time protocols continue to be in use.

Your time can be synced to any number of NTP servers for the purpose of updating your own system time or querying it for another use. While most UNIX-based servers will support synchronising by default - many don't... and some other smaller servers may not provide that feature at all. This PHP function is a means of obtaining a GPS-accurate time when other methods fail you.

Query Time from a NTP Server with PHP

Pictured: Windows has supported NTP updating since Windows 2000

You can choose any number of NTP servers to sync to here .

The PHP Function

1
<?php 
2
/*
3
 Query Time from a NTP Server with PHP
4
 http://www.beliefmedia.com/query-ntp-time-server
5
*/
6
 
7
function beliefmedia_ntp_time($host) {
8
 
9
  /* Create a socket and connect to NTP server */
10
  $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
11
  socket_connect($sock, $host, 123);
12
 
13
  /* Send request */
14
  $msg = &quot;\010&quot; . str_repeat(&quot;\0&quot;, 47);
15
  socket_send($sock, $msg, strlen($msg), 0);
16
 
17
  /* Receive response and close socket */
18
  socket_recv($sock, $recv, 48, MSG_WAITALL);
19
  socket_close($sock);
20
 
21
  /* Interpret response */
22
  $data = unpack('N12', $recv);
23
  $timestamp = sprintf('%u', $data[9]);
24
 
25
  /* NTP is number of seconds since 0000 UT on 1 January 1900
26
     Unix time is seconds since 0000 UT on 1 January 1970 */
27
  $timestamp -= 2208988800;
28
 
29
return $timestamp;
30
}
31
 
32
/* Usage */
33
$host = '0.au.pool.ntp.org';
34
$timestamp = beliefmedia_ntp_time($host);
35
 
36
$time = date('F j, Y, g:i a', $timestamp);
37
echo $time;

Download


Title: Query Time from a NTP Server
Description: Query the Server Time from a NTP Server with PHP.
  Download • Version 0.2, 914.0B, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Connecticut)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433