Created
July 2, 2016 09:49
-
-
Save PsyChip/c32db456510a80317902b75cb167e582 to your computer and use it in GitHub Desktop.
my private php utilities which used in previously involved web projects. no documentation but it's worth to take a look.
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 | |
# PsyUtils - Generic web toolkit for php 5.4+ | |
# Armagan Corlu aka PsyChip | |
# root@psychip.net | |
# March 2014 | |
$psy_mimetypes = [ | |
'cpt' => 'application/mac-compactpro', | |
'bin' => 'application/macbinary', | |
'dms' => 'application/octet-stream', | |
'lha' => 'application/octet-stream', | |
'lzh' => 'application/octet-stream', | |
'exe' => 'application/octet-stream', | |
'class' => 'application/octet-stream', | |
'so' => 'application/octet-stream', | |
'sea' => 'application/octet-stream', | |
'dll' => 'application/octet-stream', | |
'oda' => 'application/oda', | |
'pdf' => 'application/pdf', | |
'ai' => 'application/postscript', | |
'eps' => 'application/postscript', | |
'ps' => 'application/postscript', | |
'smi' => 'application/smil', | |
'smil' => 'application/smil', | |
'mif' => 'application/vnd.mif', | |
'xls' => 'application/excel', | |
'ppt' => 'application/powerpoint', | |
'wbxml' => 'application/wbxml', | |
'wmlc' => 'application/wmlc', | |
'dcr' => 'application/x-director', | |
'dir' => 'application/x-director', | |
'dxr' => 'application/x-director', | |
'dvi' => 'application/x-dvi', | |
'gtar' => 'application/x-gtar', | |
'gz' => 'application/x-gzip', | |
'php' => 'application/x-httpd-php', | |
'php4' => 'application/x-httpd-php', | |
'php3' => 'application/x-httpd-php', | |
'phtml' => 'application/x-httpd-php', | |
'phps' => 'application/x-httpd-php-source', | |
'js' => 'application/x-javascript', | |
'swf' => 'application/x-shockwave-flash', | |
'sit' => 'application/x-stuffit', | |
'tar' => 'application/x-tar', | |
'xhtml' => 'application/xhtml+xml', | |
'xht' => 'application/xhtml+xml', | |
'zip' => 'application/x-zip', | |
'mid' => 'audio/midi', | |
'midi' => 'audio/midi', | |
'mpga' => 'audio/mpeg', | |
'mp2' => 'audio/mpeg', | |
'mp3' => 'audio/mpeg', | |
'aif' => 'audio/x-aiff', | |
'aiff' => 'audio/x-aiff', | |
'aifc' => 'audio/x-aiff', | |
'ram' => 'audio/x-pn-realaudio', | |
'rm' => 'audio/x-pn-realaudio', | |
'rpm' => 'audio/x-pn-realaudio-plugin', | |
'ra' => 'audio/x-realaudio', | |
'rv' => 'video/vnd.rn-realvideo', | |
'wav' => 'audio/x-wav', | |
'bmp' => 'image/bmp', | |
'gif' => 'image/gif', | |
'jpeg' => 'image/jpeg', | |
'jpg' => 'image/jpeg', | |
'jpe' => 'image/jpeg', | |
'png' => 'image/png', | |
'tiff' => 'image/tiff', | |
'tif' => 'image/tiff', | |
'css' => 'text/css', | |
'html' => 'text/html', | |
'htm' => 'text/html', | |
'shtml' => 'text/html', | |
'txt' => 'text/plain', | |
'text' => 'text/plain', | |
'log' => 'text/plain', | |
'rtx' => 'text/richtext', | |
'rtf' => 'text/rtf', | |
'xml' => 'text/xml', | |
'xsl' => 'text/xml', | |
'mpeg' => 'video/mpeg', | |
'mpg' => 'video/mpeg', | |
'mpe' => 'video/mpeg', | |
'qt' => 'video/quicktime', | |
'mov' => 'video/quicktime', | |
'avi' => 'video/x-msvideo', | |
'movie' => 'video/x-sgi-movie', | |
'doc' => 'application/msword', | |
'xl' => 'application/excel', | |
'eml' => 'message/rfc822', | |
'json' => 'application/json', 'text/json' | |
]; | |
$psy_mf = [ | |
"../", "<!--", "-->", "<", ">", "'", '"', | |
'&', '$', '#', '{', '}', '[', ']', '=', ';', ' ', '_', | |
'?', "%20", "%22", "%3c", "%253c", "%3e", | |
"%0e", "%28", "%29", "%2528", "%26", "%24", | |
"%3f", "%3b", "%3d" | |
]; | |
class psyutil { | |
public static function time_since($original) { | |
$chunks = array( | |
array(60 * 60 * 24 * 365, 'Year'), | |
array(60 * 60 * 24 * 30, 'Month'), | |
array(60 * 60 * 24 * 7, 'Week'), | |
array(60 * 60 * 24, 'Day'), | |
array(60 * 60, 'Hour'), | |
array(60, 'Minute'), | |
); | |
$today = time(); | |
$since = $today - $original; | |
for ($i = 0, $j = count($chunks); $i < $j; $i++) { | |
$seconds = $chunks[$i][0]; | |
$name = $chunks[$i][1]; | |
if (($count = floor($since / $seconds)) != 0) { | |
break; | |
} | |
} | |
$print = ($count == 1) ? '1 ' . $name : "$count {$name}"; | |
if ($i + 1 < $j) { | |
$seconds2 = $chunks[$i + 1][0]; | |
$name2 = $chunks[$i + 1][1]; | |
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) { | |
$print .= ($count2 == 1) ? ', 1 ' . $name2 : ", $count2 {$name2}"; | |
} | |
} | |
if ($print == "0 Minute") { | |
return "few seconds ago"; | |
exit; | |
} | |
return $print . " ago"; | |
} | |
public static function createPath($path) { | |
if (is_dir($path)) | |
return true; | |
$prev_path = substr($path, 0, strrpos($path, '/', -2) + 1); | |
$return = psyutil::createPath($prev_path); | |
return ($return && is_writable($prev_path)) ? mkdir($path) : false; | |
} | |
public static function strfind($tofind, $str) { | |
$hede = stristr($str, $tofind); | |
if (strlen($hede) > 0) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
public static function ArraySetLeader($array, $key) { | |
/* limbo'ya dusmus ayni keylere sahip inception tarzi arraylerin | |
* icinden secilen bir degiskeni ana key olarak atar | |
* | |
* $deneme = array([0]=>array('hede'=>'xx1','hebele'=>'yyy'),[1]=>array('hede'=>'xx2','hebele'=>'yyy')); | |
* $yeniarray = array_setleader($deneme,'hede'); | |
* yeniarray icerigi = array([xx1]=>array('hebele'=>'yyy'),[xx2]=>array('hebele'=>'yyy')); | |
*/ | |
$result = []; | |
foreach ($array as $line) { | |
$child = []; | |
foreach (array_keys($line) as $content) { | |
if ($content == $key) { | |
continue; | |
} | |
$child[$content] = $line[$content]; | |
$result[$line[$key]] = $child; | |
} | |
empty($child); | |
} | |
return $result; | |
} | |
public static function inception2array($array, $key, $value) { | |
/* build a key->value array from another multidimensional | |
* array which has same structure. | |
* | |
* in other words, it will convert vertical binary tree to | |
* horizontal binary tree | |
*/ | |
$tmp = []; | |
foreach ($array as $data) { | |
$tmp[$data[$key]] = $data[$value]; | |
} | |
return $tmp; | |
} | |
public static function RemovePrefix($string, $instring) { | |
if ($instring == substr($string, 0, strlen($instring))) { | |
return str_replace($instring, '', $string); | |
} else { | |
return $string; | |
} | |
} | |
public static function ArrayUnPrefix($prefix, $array) { | |
$newarr = []; | |
foreach (array_keys($array) as $keys) { | |
$newarr[psyutil::removeprefix($keys, $prefix)] = $array[$keys]; | |
} | |
return $newarr; | |
} | |
public static function RemoveLastChar($str) { | |
return substr_replace($str, "", -1); | |
} | |
public function ArrayKeyExtractEx($array, $head, $delim, $limit = null) { | |
$cikti = []; | |
foreach ($array as $key => $value) { | |
if (psyutil::strfind($head . $delim, $key)) { | |
$content = explode($delim, $key, $limit); | |
$cikti[$content[1]] = $value; | |
} | |
} | |
return $cikti; | |
} | |
public static function ArrayKeyExtract($array, $head, $delim = "_", $limit = null) { | |
$cikti = []; | |
foreach (array_keys($array) as $key) { | |
$pos = strpos($key, $head . $delim); | |
if ($pos !== false) { | |
$patlat = explode($delim, $key, $limit); | |
$xkey = $patlat[1] . $delim; | |
if (count($patlat) > 2) { | |
for ($i = 2; $i < count($patlat); $i++) { | |
$xkey.=$patlat[$i] . $delim; | |
} | |
} | |
$xkey = psyutil::RemoveLastChar($xkey); | |
$cikti[$xkey] = $array[$key]; | |
} | |
} | |
return $cikti; | |
} | |
public static function CleanString($interim) { | |
$result = ''; | |
$permitted = '_.,-/ '; | |
$permasc_arr = []; | |
for ($x = 0; $x < strlen($permitted); $x++) { | |
$permchar = $permitted{$x}; | |
$asciichr = ord($permchar); | |
$permasc_arr[] = $asciichr; | |
} | |
for ($c = ord('a'); $c < ord('z') + 1; $c++) { | |
$permasc_arr[] = $c; | |
} | |
for ($c = ord('A'); $c < ord('Z') + 1; $c++) { | |
$permasc_arr[] = $c; | |
} | |
for ($c = ord('0'); $c < ord('9') + 1; $c++) { | |
$permasc_arr[] = $c; | |
} | |
for ($i = 0; $i < strlen($interim); $i++) { | |
$char = $interim{$i}; | |
$asciivalue = ord($char); | |
foreach ($permasc_arr as $ascval) { | |
if ($ascval == $asciivalue) { | |
$result.=$char; | |
} | |
} | |
} | |
return $result; | |
} | |
public static function CalcPercent($num_amount, $num_total) { | |
$count1 = $num_amount / $num_total; | |
$count2 = $count1 * 100; | |
return number_format($count2, 0); | |
} | |
public static function TimeLeft($date) { | |
$chunks = array( | |
array(60 * 60 * 24 * 365, 'Year'), | |
array(60 * 60 * 24 * 30, 'Month'), | |
array(60 * 60 * 24 * 7, 'Week'), | |
array(60 * 60 * 24, 'Day'), | |
array(60 * 60, 'Hour'), | |
array(60, 'Minute'), | |
); | |
$since = $date - time(); | |
for ($i = 0, $j = count($chunks); $i < $j; $i++) { | |
$seconds = $chunks[$i][0]; | |
$name = $chunks[$i][1]; | |
if (($count = floor($since / $seconds)) != 0) { | |
break; | |
} | |
} | |
$print = ($count == 1) ? '1 ' . $name : "$count {$name}"; | |
if ($i + 1 < $j) { | |
$seconds2 = $chunks[$i + 1][0]; | |
$name2 = $chunks[$i + 1][1]; | |
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) { | |
$print .= ($count2 == 1) ? ', 1 ' . $name2 : ", $count2 {$name2}"; | |
} | |
} | |
if ($print == "0 Minute") { | |
return "few seconds left"; | |
exit; | |
} | |
return $print . " left"; | |
} | |
function ArrayDelKey($arr, $key) { | |
/* removes a key with its value */ | |
if (is_array($key)) { | |
foreach ($key as $_key) { | |
$arr = array_delkey($arr, $_key); | |
} | |
return $arr; | |
} | |
$tmp = []; | |
foreach (array_keys($arr) as $arrkey) { | |
if ($arrkey <> $key) { | |
$tmp[$arrkey] = $arr[$arrkey]; | |
} | |
} | |
return $tmp; | |
} | |
function shash($data) { | |
static $map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
$hash = crc32($data) + 0x100000000; | |
$str = ""; | |
do { | |
$str = $map[31 + ($hash % 31)] . $str; | |
$hash /= 31; | |
} while ($hash >= 1); | |
return $str; | |
} | |
public static function BoolArray2Bitstream($arr) { | |
$bs = ""; | |
foreach (array_keys($arr) as $key) { | |
$bs = $bs . intval($arr[$key]); | |
} | |
return strval($bs); | |
} | |
public static function ParseDMY($date, $format = "d/m/Y") { | |
$dt = DateTime::createFromFormat($format, $date); | |
return $dt->getTimestamp(); | |
} | |
public static function GetUserIP() { | |
$client = @$_SERVER['HTTP_CLIENT_IP']; | |
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; | |
$remote = $_SERVER['REMOTE_ADDR']; | |
if (filter_var($client, FILTER_VALIDATE_IP)) { | |
$ip = $client; | |
} elseif (filter_var($forward, FILTER_VALIDATE_IP)) { | |
$ip = $forward; | |
} else { | |
$ip = $remote; | |
} | |
return $ip; | |
} | |
public static function VerifyArray($arr, $template) { | |
foreach (array_keys($template) as $key) { | |
if (!array_key_exists($key, $arr)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
public static function redirect($page) { | |
if (!headers_sent()) { | |
header("Location: " . $page); | |
} | |
die( | |
'<script type="text/javascript">' . | |
'window.location="' . $page . '";' . | |
'</script>' . | |
'<a href="' . $page . '">Click if redirection doesnt work</a>' | |
); | |
} | |
public static function setcookie($key, $value, $expire = 3600) { | |
if ($expire == 0) { | |
setcookie($key, $value, time() + (10 * 365 * 24 * 60 * 60)); | |
} else { | |
setcookie($key, $value, time() + $expire); | |
} | |
} | |
public static function delcookie($key) { | |
if (isset($_COOKIE[$key])) { | |
unset($_COOKIE[$key]); | |
setcookie($key, null, time() - 3600, '/'); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
public static function session_start() { | |
try { | |
if (version_compare(phpversion(), '5.4.0', '<')) { | |
if (session_id() == '') { | |
if (!headers_sent($_file, $_line)) { | |
session_start(); | |
} else { | |
Echo '<h2>PsyUtils: Cannot start session</h2>'; | |
psyutil::printpre($data); | |
} | |
} | |
} else { | |
if (session_status() == PHP_SESSION_NONE) { | |
if (!headers_sent($_file, $_line)) { | |
session_start(); | |
} else { | |
Echo '<h2>PsyUtils: Cannot start session, headers already sent</h2>'; | |
psyutil::printpre($data); | |
} | |
} | |
} | |
if (!isset($_SESSION) || !is_array($_SESSION)) { | |
$_SESSION = []; | |
} | |
} catch (Exception $ex) { | |
$data = [ | |
'File' => $ex->getFile(), | |
'Line' => $ex->getLine(), | |
'Message' => $ex->getMessage() | |
]; | |
Echo '<h2>PsyUtils: Cannot start session</h2>'; | |
psyutil::printpre($data); | |
} | |
} | |
public static function session_kill() { | |
if (version_compare(phpversion(), '5.4.0', '<')) { | |
if (session_id() != '') { | |
$_SESSION = []; | |
session_destroy(); | |
} | |
} else { | |
if (session_status() != PHP_SESSION_NONE) { | |
$_SESSION = []; | |
session_destroy(); | |
setcookie(session_name(), null, -1, '/'); | |
} | |
} | |
if (isset($_COOKIE[session_name()])) { | |
unset($_COOKIE[session_name()]); | |
} | |
} | |
public static function LoadJs($path) { | |
foreach (glob("{$path}/*.js") as $filename) { | |
echo '<script type="text/javascript" src="/' . $filename . '"></script>' . chr(13) . chr(10); | |
} | |
} | |
public static function LoadCss($path) { | |
foreach (glob("{$path}/*.css") as $filename) { | |
echo '<link rel="stylesheet" href="/' . $filename . '">' . chr(13) . chr(10); | |
} | |
} | |
public static function define_array($arr, $prefix = "", $inception = true) { | |
$i = 0; | |
if (count($arr) > 0 && is_array($arr)) { | |
foreach (array_keys($arr) as $key) { | |
if (is_array($arr[$key])) { | |
if ($inception) { | |
$i = $i + psyutil::define_array($arr[$key], $prefix, $inception); | |
} else { | |
define($prefix . $key, serialize($arr[$key])); | |
} | |
} else { | |
define($prefix . $key, $arr[$key]); | |
$i++; | |
} | |
} | |
} | |
return $i; | |
} | |
public static function ExplodeStr($string, $index, $char) { | |
$tmp = explode($char, $string); | |
return $tmp[$index]; | |
} | |
public static function StripHiddenChars($str, $url_encoded = TRUE) { | |
$non_displayables = []; | |
if ($url_encoded) { | |
$non_displayables[] = '/%0[0-8bcef]/'; | |
$non_displayables[] = '/%1[0-9a-f]/'; | |
} | |
$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; | |
do { | |
$str = preg_replace($non_displayables, '', $str, -1, $count); | |
} while ($count); | |
return $str; | |
} | |
public static function SanitizeFilename($str) { | |
global $psy_mf; | |
$str = psyutil::StripHiddenChars($str, FALSE); | |
return stripslashes(str_replace($psy_mf, '', $str)); | |
} | |
public static function GetFileExt($file_name) { | |
if (stristr($file_name, '.') == false) { | |
return $file_name; | |
} | |
return end(explode('.', $file_name)); | |
} | |
public static function formatBytes($bytes, $precision = 2) { | |
$units = array('B', 'KB', 'MB', 'GB', 'TB'); | |
$bytes = max($bytes, 0); | |
$pow = floor(($bytes ? log($bytes) : 0) / log(1024)); | |
$pow = min($pow, count($units) - 1); | |
$bytes /= (1 << (10 * $pow)); | |
return round($bytes, $precision) . ' ' . $units[$pow]; | |
} | |
public static function base64_encode($input) { | |
return strtr(base64_encode($input), '+/=', '-_.'); | |
} | |
public static function base64_decode($input) { | |
return base64_decode(strtr($input, '-_.', '+/=')); | |
} | |
public static function printpre($arr) { | |
echo '<pre>'; | |
print_r($arr); | |
echo '</pre>'; | |
die; | |
} | |
public static function GetMime($file) { | |
$ext = psyutil::GetFileExt($file); | |
global $psy_mimetypes; | |
if (array_key_exists($ext, $psy_mimetypes)) { | |
return $psy_mimetypes[$ext]; | |
} | |
} | |
public static function SwitchMime($ext) { | |
if (!headers_sent()) { | |
global $psy_mimetypes; | |
if (array_key_exists($ext, $psy_mimetypes)) { | |
header('Content-Type: ' . $psy_mimetypes[$ext]); | |
} | |
} | |
} | |
public static function array_push_assoc($array, $key, $value) { | |
$array[$key] = $value; | |
return $array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment