Skip to content

Instantly share code, notes, and snippets.

@picasso250
Last active March 16, 2018 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save picasso250/66dcf91511097986c7347db5a2a66feb to your computer and use it in GitHub Desktop.
Save picasso250/66dcf91511097986c7347db5a2a66feb to your computer and use it in GitHub Desktop.
lib of php
<?php
function env_load($dir='.')
{
$file = "$dir/.env";
if (!is_file($file)) {
echo "no .env file $file\n";
exit(1);
}
if (!is_readable($file)) {
echo ".env $file file not readable\n";
exit(1);
}
$config = parse_ini_file($file);
foreach ($config as $key => $value) {
if (!isset($_ENV[$key])) {
$_ENV[$key] = $value;
}
}
}
function autoload_dir($namespace_root, $dir_root) {
spl_autoload_register(function ($nc) use ($namespace_root, $dir_root) {
$prefix = "$namespace_root\\";
if (strpos($nc, $prefix) === 0) {
$c = substr($nc, strlen($prefix));
require "$dir_root/$c.php";
}
});
}
function exception_error_handler($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting
return;
}
throw new ErrorException($message, 0, $severity, $file, $line);
}
function error2exception()
{
set_error_handler("exception_error_handler");
}
function make_csrf($token_name = '_csrf_token_name')
{
//After the user's login has deemed to be successful.
//Generate a secure token using openssl_random_pseudo_bytes.
$myToken = bin2hex(openssl_random_pseudo_bytes(24));
//Store the token as a session variable.
$_SESSION[$token_name] = $myToken;
}
// [reg, func, method]
function regex_router($routers)
{
// get url
$uri = $_SERVER["REQUEST_URI"];
$a = explode("?", $uri);
$url = $a[0];
// run
foreach ($routers as $reg => $arr) {
foreach ($arr as $method => $func) {
if ($_SERVER["REQUEST_METHOD"] == $method && preg_match($reg, $url, $m)) {
if (is_callable($func)) {
$func($m);
return true;
} elseif (is_string($func)) {
$f404($func);
return true;
} elseif (is_array($func)) {
list($class_name, $func_name) = $func;
if (!class_exists($class_name))
return false;
$c = new $class_name();
if (!method_exists($c, $func_name))
return false;
$c->$func_name($m);
return true;
}
return false;
}
}
}
return false;
}
function service($name, $value = null)
{
static $lazy;
static $pool;
if ($value === null) {
// get
if (isset($pool[$name])) {
return $pool[$name];
}
if (isset($lazy[$name])) {
$func = $lazy[$name];
return $pool[$name] = $func();
}
return null;
}
// set
if (is_callable($value)) {
$lazy[$name] = $value;
return;
}
$pool[$name] = $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment