feat: add isPrivateIP helper, fix getUserIP and addToLog
This commit is contained in:
@@ -1,35 +1,49 @@
|
||||
<?php
|
||||
|
||||
function renderTemplate($templatename,$variables=[],$basepath=ROOT.'/src')
|
||||
function renderTemplate($templatename, $variables = [], $basepath = ROOT . '/src')
|
||||
{
|
||||
ob_start();
|
||||
if(is_array($variables))
|
||||
if (is_array($variables))
|
||||
extract($variables);
|
||||
if(file_exists($basepath.DS.'templates'.DS.$templatename.'.php'))
|
||||
include($basepath.DS.'templates'.DS.$templatename.'.php');
|
||||
else if(file_exists($basepath.DS.'templates'.DS.$templatename))
|
||||
include($basepath.DS.'templates'.DS.$templatename);
|
||||
if (file_exists($basepath . DS . 'templates' . DS . $templatename . '.php'))
|
||||
include($basepath . DS . 'templates' . DS . $templatename . '.php');
|
||||
else if (file_exists($basepath . DS . 'templates' . DS . $templatename))
|
||||
include($basepath . DS . 'templates' . DS . $templatename);
|
||||
$rendered = ob_get_contents();
|
||||
ob_end_clean();
|
||||
|
||||
return $rendered;
|
||||
}
|
||||
|
||||
function addToLog($data)
|
||||
function addToLog(string $data): void
|
||||
{
|
||||
$fp = fopen(ROOT.DS.'logs'.DS.'app.log','a');
|
||||
fwrite($fp,date("d.m.y H:i")."\t".$data."\n");
|
||||
$data = str_replace(["\n", "\r", "\t"], ' ', $data);
|
||||
$fp = fopen(ROOT . DS . 'logs' . DS . 'app.log', 'a');
|
||||
fwrite($fp, date("d.m.y H:i") . "\t" . $data . "\n");
|
||||
fclose($fp);
|
||||
}
|
||||
|
||||
function getUserIP()
|
||||
function getUserIP(): string
|
||||
{
|
||||
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;
|
||||
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
|
||||
return trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
|
||||
return $_SERVER['REMOTE_ADDR'];
|
||||
}
|
||||
|
||||
function isPrivateIP(string $ip): bool
|
||||
{
|
||||
if (filter_var($ip, FILTER_VALIDATE_IP) === false) return true;
|
||||
|
||||
$long = ip2long($ip);
|
||||
if ($long === false) return true;
|
||||
|
||||
foreach ([
|
||||
[ip2long('127.0.0.0'), 0xFF000000], // 127.0.0.0/8 loopback
|
||||
[ip2long('10.0.0.0'), 0xFF000000], // 10.0.0.0/8 RFC1918
|
||||
[ip2long('172.16.0.0'), 0xFFF00000], // 172.16.0.0/12 RFC1918
|
||||
[ip2long('192.168.0.0'), 0xFFFF0000], // 192.168.0.0/16 RFC1918
|
||||
[ip2long('169.254.0.0'), 0xFFFF0000], // 169.254.0.0/16 link-local/metadata
|
||||
] as [$base, $mask]) {
|
||||
if (($long & $mask) === ($base & $mask)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
Reference in New Issue
Block a user