Skip to content

Instantly share code, notes, and snippets.

@rdundon
Created December 27, 2017 19:52
Show Gist options
  • Save rdundon/ec488af138fd64d46341e52062d65647 to your computer and use it in GitHub Desktop.
Save rdundon/ec488af138fd64d46341e52062d65647 to your computer and use it in GitHub Desktop.
Update time without NTP with PHP
<?php
/**
* Little script to update date based on SO answer here: https://askubuntu.com/a/655528/158714
* but with more security in mind (as that answer just feeds the output right into bash)
*
* Useful for little VMs when NTP is blocked and you put VMs into saved state regularly/
*
* Run via cron as root or other privileged user.
*
* Robert Dundon
* (C) 2017 BH Media Group, Inc. (I wrote this at work, for work)
*/
//Site to get the Date header from
$url = 'http://www.example.com';
//Get the headers
$header_lines = get_headers($url);
//Parse headers accordingly
$headers = [];
foreach ($header_lines as $header_line) {
$header_datum = explode(': ',$header_line);
$key = $header_datum[0];
$value = $header_datum[1];
$headers[$key] = $value;
}
// Convert string of header to timestamp (helps sanitize the given header data), and convert it to ISO 8601
$new_date = date('c',strtotime($headers['Date']));
// Then set the date
exec("date -s $new_date");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment