Skip to content

Instantly share code, notes, and snippets.

@nachivpn
Created May 27, 2015 12:50
Show Gist options
  • Save nachivpn/e4829fa2475885a20d2a to your computer and use it in GitHub Desktop.
Save nachivpn/e4829fa2475885a20d2a to your computer and use it in GitHub Desktop.
function loadIp($host){
$filepath = "/dev/shm/ipcache";
$ip = gethostbyname($host);
$wfile = fopen($filepath, "w");
fwrite($wfile, $ip);
fclose($wfile);
return $ip;
}
function getIp($host)
{
/*Initialize variables*/
$result = 0;
$cltime = 0;
$ttl = 3600;
$filepath = "/dev/shm/ipcache";
$shieldsquare_config_data = new shieldsquare_config();
$ttl = $shieldsquare_config_data->_domain_ttl;
/*file doesn exist at all*/
if(!file_exists($filepath))
{
echo "<p>Loading because file doesnt exist..<p>";
$ip = loadIp($host);
}
/*file exists*/
else
{
$rfile = fopen($filepath, "r");
$result = fread($rfile,filesize($filepath));
fclose($rfile);
$cltime = filemtime($filepath);
/*file exists with o content*/
if(!$result || !$cltime)
{
echo "<p>Loading to cache because file is empty..<p>";
$ip = loadIp($host);
}
else
{
$life=time()-$cltime;
/*file exists with content but the value has expired*/
if($life>$ttl)
{
echo "<p>Loading the IP because the name record expired in the cache..</p>";
$ip = loadIp($host);
}
/*value has not expired*/
else
echo "<p>Using cached IP</p>";
$ip=$result;
}
}
return $ip;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment