只是想知道 PHP 中是否有一种方法可以从特定服务器(例如谷歌)检索时间。我想制作一个可以检索服务器上设置的时间的脚本。
谢谢 :)
如果您可以信任 HTTP 请求返回的Date:
标头,您可以在PHP中使用cURL执行类似的操作。
<?
$date = null;
function header_callback($curl, $header)
{
global $date;
if (preg_match('/^Date:/', $header)) {
$date = trim(substr($header, 5));
$date = DateTime::createFromFormat('D, d M Y H:i:s e', $date);
}
return strlen($header);
}
$curl = curl_init("http://www.google.com/");
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADERFUNCTION, 'header_callback');
curl_exec($curl);
curl_close($curl);
if ($date != NULL) {
echo "Date from HTTP: " . $date->format('r');
}
?>
没有内置的 PHP 函数来查询特定的时间服务器,但您可以编写一个脚本来执行此操作。可以在此页面上找到一些示例:http ://www.kloth.net/software/timesrv1.php
上一个链接中的这个示例在端口 37 上使用了 TIME 协议:
<?php
/* Query a time server
(C) 1999-09-29, Ralf D. Kloth (QRQ.software) <ralf at qrq.de>
*/
function query_time_server ($timeserver, $socket) {
$fp = fsockopen($timeserver,$socket,$err,$errstr,5);
# parameters: server, socket, error code, error text, timeout
if ($fp) {
fputs($fp,"\n");
$timevalue = fread($fp,49);
fclose($fp); # close the connection
}
else {
$timevalue = " ";
}
$ret = array();
$ret[] = $timevalue;
$ret[] = $err; # error code
$ret[] = $errstr; # error text
return($ret);
} # function query_time_server
$timeserver = "ntp1.sf-bay.org";
$timercvd = query_time_server($timeserver,37);
if (!$timercvd[1]) { # if no error from query_time_server
$timevalue = bin2hex ($timercvd[0]);
$timevalue = abs (HexDec('7fffffff') - HexDec($timevalue) - HexDec('7fffffff')) ;
$tmestamp = $timevalue - 2208988800; # convert to UNIX epoch time stamp
$datum = date("Y-m-d (D) H:i:s",$tmestamp - date("Z",$tmestamp)); /* incl time zone offset */
$doy = (date("z",$tmestamp)+1);
echo "Time check from time server ",$timeserver," : [<font color=\"red\">",$timevalue,"</font>]";
echo " (seconds since 1900-01-01 00:00.00).<br>\n";
echo "The current date and universal time is ",$datum," UTC. ";
echo "It is day ",$doy," of this year.<br>\n";
echo "The unix epoch time stamp is $tmestamp.<br>\n";
} #if (!$timercvd)
else {
echo "Unfortunately, the time server $timeserver could not be reached at this time. ";
echo "$timercvd[1] $timercvd[2].<br>\n";
} # else
?>