<?php
	//$ntpTime = explode( "/", NTP_client("udp://ntp.nict.jp", 123));
	$ntpTime = explode( "/", NTP_client("udp://ntp1.jst.mfeed.ad.jp", 123));
	
	$y = $ntpTime[0];	//年
	$m = $ntpTime[1]-1;	//月
	$d = $ntpTime[2];	//日
	$h = $ntpTime[3];	//時
	$i = (int)$ntpTime[4];	//分
	$s = (int)$ntpTime[5];	//秒
	
	$sOut = "";
	$sOut .= "function getNtpTime(){";
	$sOut .= "var ntpjst = new Date( {$y}, {$m}, {$d}, {$h}, {$i}, {$s});";
	$sOut .= "return ntpjst;";
	$sOut .= "}";
	
	print $sOut;
	
	
	
function NTP_putpacket($packet)
{
	$str  = "<TABLE BORDER><CAPTION>send</CAPTION>";
	foreach($packet as $key => $value) $str .= "<TR><TD>" . $key . "</TD><TD>" . bin2hex($value) . "</TD></TR>";
	$str .= print "</TABLE>";

	return($str);
}


/*-------------------------------------------------------------------------------------------------
NTPクライアント
-------------------------------------------------------------------------------------------------*/
function NTP_client($server, $port, $timeout = 30){
	/* NTPパケット */
	$ntp["control_word"]	= chr(hexdec("0b")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["root_delay"]		= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["root_dispersion"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["ref_identifier"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["ref_time_sec"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["ref_time_frac"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["org_time_sec"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["org_time_frac"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["recv_time_sec"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["recv_time_frac"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["send_time_sec"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));
	$ntp["send_time_frac"]	= chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00")) . chr(hexdec("00"));


	/* NTPサーバに接続 */
	if( !($sock = fsockopen($server, $port, $err_no, $err_str, $timeout)) ){
		return(0);
	}

	/* パケットを送る */
	unset($tmp);
	foreach($ntp as $key => $value) $tmp .= $value;
	fwrite($sock, $tmp, 4 * 12);

	/* 応答を得る */
	foreach($ntp as $key => $value){
		$value = fread($sock, 4);
		$ntp[ $key ] = $value;
	}

	fclose($sock);

	return(date("Y/n/j/G/i/s", hexdec(bin2hex($ntp["send_time_sec"])) - 2208988800));
}
?>