Skip to content

Instantly share code, notes, and snippets.

@vibbow
Created January 22, 2014 23:55
Show Gist options
  • Save vibbow/8570062 to your computer and use it in GitHub Desktop.
Save vibbow/8570062 to your computer and use it in GitHub Desktop.
PHP通过NTP服务器获取时间脚本
#!/usr/bin/php -q
<?php
echo "PHP Time Protocol Client\n";
echo "-----------------\n";
/* NTP服务器列表 */
$ntp_server_list = array(
'0.hk.pool.ntp.org',
'0.asia.pool.ntp.org',
'1.asia.pool.ntp.org',
'2.asia.pool.ntp.org',
'3.asia.pool.ntp.org',
'time.windows.com',
'time.nist.gov'
);
/* NTP服务器数量 */
$ntp_server_count = count($ntp_server_list);
/* Flag: 已经获取到时间 */
$have_got_time = false;
/* 设置时区 */
date_default_timezone_set('Asia/Shanghai');
for ($i = 0; $i < $ntp_server_count; $i++) {
$ntp_server = $ntp_server_list[$i];
echo "Connect to NTP server {$ntp_server} ... ";
$fp = @fsockopen($ntp_server, 37, $errno, $errmsg, 10);
if (!$fp) {
echo "Failed!\n";
} else {
echo "Connected\n";
$result = null;
while (!feof($fp))
$result .= fgets($fp, 1452);
fclose($fp);
if (strlen($result) != 4) {
echo " > NTP Server return a unexpect data\n";
echo " > Try next server\n";
} else {
echo " > Got valied data\n";
$have_got_time = true;
break;
}
}
}
if ($have_got_time) {
$NTP_timestamp = ord($result{0}) * pow(256, 3) + ord($result{1}) * pow(256, 2) + ord($result{2}) * 256 + ord($result{3});
/*
* PHP的Timestamp是从1970/1/1开始计算的
* Time协议的Timestamp是从1900/1/1开始计算的
* 他俩之间差25567天
* 所以通过NTP server获取的时间戳减去25567天就是PHP的时间戳
*/
$real_timestamp = $NTP_timestamp - 25567*24*60*60;
$date_string = date('j M Y H:i:s', $real_timestamp);
echo " > {$date_string}\n";
$sys_date = exec("date -s \"{$date_string}\"");
echo " > System date set to {$sys_date}\n";
} else {
echo "Can not get any valid data from NTP server list\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment