Last active
August 29, 2015 13:57
-
-
Save icheko/9522194 to your computer and use it in GitHub Desktop.
Usage in cron: 0,5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/bin/php /root/scripts/dynamic_htaccess_update.php dynamic.ip.com
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 | |
// Rewrites the entire htaccess file. When a line starts with '# Allow from brett.getmyip.com' the | |
// very next line will be replaced with the actual ip associated with brett.getmyip.com | |
// | |
// Usage in cron: 0,5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/bin/php /root/scripts/dynamic_htaccess_update.php /var/www/html/.htaccess dynamic.ip.com | |
// | |
// Hat tip: http://brett.batie.com/software-development/update-htaccess-with-dynamic-dns-ip-address-to-prevent-password-protection/ | |
$htaccessFile = $argv[1]; | |
$target_dns_name = $argv[2]; | |
$output = shell_exec('host '.$target_dns_name); | |
if (preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches)) { | |
$allow_from = 'Allow from '.$matches[0]."\n"; | |
} else { | |
$allow_from = "# Unable to get IP\n"; | |
} | |
$handle = fopen($htaccessFile, "r"); | |
if ($handle) { | |
$previous_line = $content = ''; | |
while (!feof($handle)) { | |
$current_line = fgets($handle); | |
if (stripos($previous_line,'# Allow from '.$target_dns_name) !== FALSE) { | |
$content .= $allow_from; | |
} else { | |
$content .= $current_line; | |
} | |
$previous_line = $current_line; | |
} | |
fclose($handle); | |
$tempFile = tempnam('/tmp','allow_'); | |
$fp = fopen($tempFile, 'w'); | |
fwrite($fp, $content); | |
fclose($fp); | |
rename($tempFile,$htaccessFile); | |
chmod($htaccessFile,'0644'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment