Skip to content

Instantly share code, notes, and snippets.

@GianpaMX
Created October 18, 2012 21:48
Show Gist options
  • Save GianpaMX/3914960 to your computer and use it in GitHub Desktop.
Save GianpaMX/3914960 to your computer and use it in GitHub Desktop.
Automatically updating a hosts file for dynamic dns
<?php
if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
$redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header("Location: $redirect");
}
class Host {
private $ip;
private $hosts;
public function __construct($ip = '', $hostname = null) {
$this->ip = $ip;
$this->hosts = array();
if($hostname) $this->hosts[] = $hostname;
}
public function setIP($ip) {
$this->ip = $ip;
}
public function getHosts() {
return $this->hosts;
}
public static function fromLine($line) {
$line = trim($line);
if(empty($line) || false !== strpos($line, '#')) return false;
$host = new Host();
$columns = preg_split('/\h+/', $line);
$host->ip = array_shift($columns);
$host->hosts = array_filter($columns, function($element) {
return trim($element) != "";
});
return $host;
}
public static function fromFile($file) {
$hosts = array();
$handle = @fopen($file, "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if(false !== $host = Host::fromLine($buffer)) $hosts[] = $host;
}
if (!feof($handle)) {
throw new Exception("Error: unexpected fgets() fail");
}
fclose($handle);
}
return $hosts;
}
public function __toString() {
if(!is_array($this->hosts)) die(print_r($this,1));
return $this->ip . "\t" . implode(' ', $this->hosts);
}
public static function toString($hosts) {
$fileContent = "";
foreach($hosts as $host) {
$fileContent .= "$host\n";
}
return $fileContent;
}
public static function toFile($file, $hosts) {
file_put_contents($file, Host::toString($hosts));
}
public static function array_search($hosts, $hostname) {
foreach($hosts as $index => $host) {
if(false !== array_search($hostname, $host->getHosts())) {
return $index;
}
}
return false;
}
}
function getRealIpAddr() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$hosts = Host::fromFile('/etc/hosts');
$hostname = $_POST['hostname'];
$ip = getRealIpAddr();
if(!$hostname) throw new Exception("Bad request");
$index = Host::array_search($hosts, $hostname);
if(false !== $index) {
$host = $hosts[$index];
$host->setIP($ip);
system('/home/pablo/dnsmasq_restart');
}
Host::toFile('/etc/hosts', $hosts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment