date in PHP

2011年11月24日 星期四

date in PHP


這篇會介紹PHP中的date()怎麼使用,主要會說明如何把時間與總秒數互相轉換,還有如何透過ssh同步時間\。(因公司緣故,不知為何無法透過NTP同步時間,才會透過SSH做相似的功能)

#把時間轉成總秒數

$now_time_seconds = strtotime(date("d M Y H:i:s"));

#把總秒數轉成時間

date("d M Y H:i:s",$now_time_seconds);



透過ssh 與server的時間用utc時制同步時間

$ip = 'x.x.x.x';
$_user = "root";
$_passord = "";
$_port="22";
if (!($connection=@ssh2_connect($ip, $_port))) {
        echo 'Lost Connection';
}else {
        if (!@ssh2_auth_password($connection,$_user,$_passord))
        {
                echo 'Invalid Password';
        }else{
        #把server的時間用utc時制轉成總秒數,再存入xx_time檔
                $server_senconds_time=date("Y-m-d-H:i:s");
                system("date -u +%m%d%k%M%y.%S > ".$server_senconds_time."_time");


        #從檔案中把總秒數取出來
                $server_senconds="";
                if(file_exists($server_senconds_time."_time"))
                {
                        $file = fopen($server_senconds_time."_time", "r");
                        $tmp_server_senconds = trim(fgets($file));
                        fclose($file);
                        if($tmp_server_senconds!="" && $tmp_server_senconds!=NULL)
                                $server_senconds=$tmp_server_senconds;

                        system("rm ".$server_senconds_time."_time");
                }

        #透過ssh的方式實現時間同步
                if($server_senconds!="")
                {
                         ssh2_exec($connection, "date -u ".$server_senconds." \n exit");
                }else{
                         ssh2_exec($connection, "exit");
                }
    }
}



這邊還有問題是在透過ssh與server時間同步時,會有些許的誤差,主要是因為寫檔與讀檔的緣故。如果有誤請麻煩改正~謝謝~~

0 意見 :

張貼留言