3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ntpdを使わずにPHPで日付日時を合わせる

Last updated at Posted at 2018-04-20

むか~し、某システムでfwの関係上、内側から外向きのNTPポートも閉じられてたときに作ったものです。
厳密な時刻が必要なシステムの場合は無理ですが、数msのズレでもいいなら使えなくはないと思います。

端的に言えば情報通信研究機構が提供している公開NTPのjsonを
file_get_contentsで取得して、
時刻部分を力技で切り出してdateコマンドに流し込んでいるという・・
恐ろしや・・

/bin/echo '<?php date_default_timezone_set("Asia/Tokyo");
$r=file_get_contents("http://ntp-a1.nict.go.jp/cgi-bin/jsont?".time());
$startpos=strpos($r,"st");$startpos=strpos($r," ",$startpos)+1;$endpos=strpos($r,",",$startpos);
$mt=substr($r,$startpos,$endpos-$startpos);
$cmd="/bin/date -s \"".date("m/d H:i:s Y",$mt)." JST\"";
if(date("Y",$mt)>=2012){exec($cmd);}else{echo "set error\n";}
echo "dateset ".$cmd."\n";?>' | /usr/bin/php

見た目上、改行入れてますが、全ての改行を外せばワンライナーでいけますので
ntpd設定するのメンドクセってときにはcrontabに仕込んでおけばよいかとw

(※ json_decode使わなかったのは、その時のサーバに何故か入っていなかったからw)
(※ ソース内には2012なんて文字があるのでたぶんその頃に作ったんだろなーー)

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?