icheko
3/13/2014 - 5:13 AM

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

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

<?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');
}