Created
November 18, 2012 02:04
-
-
Save hexathos/4102830 to your computer and use it in GitHub Desktop.
getTimeFromNTPServer - PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This function is free software; you can redistribute it and/or | |
* modify it under the terms of the GNU Lesser General Public | |
* License as published by the Free Software Foundation; either | |
* version 2.1 of the License, or (at your option) any later version. | |
* | |
* This Software is distributed in the hope that it will be useful, | |
* but WITHOUT ANY WARRANTY; without even the implied warranty of | |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
* Lesser General Public License for more details. | |
* | |
* You should have received a copy of the GNU Lesser General Public | |
* License along with this function; if not, write to the Free Software | |
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | |
**/ | |
/** | |
* | |
* Connect to a timeserver and return formatted timestring. | |
* | |
* @param string $server The timeserver to query | |
* @param string $dateformat The dateformat for returning the time | |
* @return string | |
* | |
*/ | |
function getTimeFromNTPServer($server='0.de.pool.ntp.org',$dateformat="Y-m-d H:i:s") | |
{ | |
$_adjustment = 0; | |
$_data =null; | |
$_fp = fsockopen($server, 37, $_errno, $_errstr, 30); | |
if (!$_fp) | |
{ | |
die( "$server: $_errstr ($_errno)"); | |
} | |
else | |
{ | |
while (!feof($_fp)) | |
{ | |
$_data .= fgets($_fp, 128); | |
} | |
fclose($_fp); | |
if (strlen($_data) != 4) | |
{ | |
die("NTP Server {$server} gab ungueltige Antwort zurueck."); | |
} | |
} | |
$_ntpTime = ord($_data{0})*pow(256, 3) + ord($_data{1})*pow(256, 2) + ord($_data{2})*256 + ord($_data{3}); | |
$_from1990 = $_ntpTime - 2840140800; | |
$_timeNow = $_from1990 + 631152000; | |
$_time = date($dateformat, $_timeNow + $_adjustment); | |
return $_time; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment