Skip to content

Instantly share code, notes, and snippets.

@alash3al
Created March 3, 2016 12:22
Show Gist options
  • Save alash3al/729db9b6f8deea7c8d90 to your computer and use it in GitHub Desktop.
Save alash3al/729db9b6f8deea7c8d90 to your computer and use it in GitHub Desktop.
dirty & quick php router only for xerver platform
<?php namespace xerver;
// sort the _SERVER array based on its keys
ksort($_SERVER);
// normalize our path-info
$_SERVER["PATH_INFO"] = preg_replace("~/+~", "/", "/" . $_SERVER["PATH_INFO"] . "/");
// start the output buffer
ob_start();
// defer the output buffer flusher at the end of the script
register_shutdown_function("ob_end_flush");
/*
* pretty print the specified data
*
* @param mixed $data
*
* @return void
*/
function dump($data) {
echo "<pre>" . print_r($data, 1) . "</pre>";
}
/*
* get a customized url using the specified info
*
* @param string $path the path to append to the url, (default "")
* @param string $hostname the hostname of the url, (default HTTP_HOST)
* @param bool $secure whether to be https url ornot, (default autodected)
*
* @return void
*/
function url($path = null, $hostname = null, $secure = null) {
$url = "";
if ( null === $secure ) {
$url = $_SERVER["HTTPS"] ? "https://" : "http://";
} else {
$url = $secure ? "https://" : "http://";
}
if ( null === $hostname ) {
$url .= $_SERVER["HTTP_HOST"];
} else {
$url .= $hostname;
}
return $url . "/" . ltrim($path, "/");
}
/*
* rewrite a pathinfo to a new pathinfo
*
* @param regexp $from
* @param string $to
*
* @return void
*/
function rewrite($from, $to) {
$_SERVER["PATH_INFO"] = preg_replace($from, $to, $_SERVER["PATH_INFO"]);
$_SERVER["PATH_INFO"] = preg_replace("~/+~", "/", "/" . $_SERVER["PATH_INFO"] . "/");
}
/*
* handle the specified path "pathinfo" using the specified callback
*
* @param string $path
* @param callable $fn
*
* @return void
*/
function on($path, callable $fn) {
if ( preg_match("~^" . preg_replace("~/+~", "/", "/" . $path . "/") . "$~", $_SERVER["PATH_INFO"], $matches) ) {
array_shift($matches);
call_user_func_array($fn, $matches);
}
}
/*
* handle the specified domain "hostname" using the specified callback
*
* @param string $hostname
* @param callable $fn
*
* @return void
*/
function vhost($hostname, callable $fn) {
if ( preg_match($path, split(":", $_SERVER["HTTP_HOST"])[0] ?? "localhost", $matches) ) {
array_shift($matches);
call_user_func_array($fn, $matches);
}
}
/*
* Send the specified file/directory to the browser using internal xerver action .
*
* @param string $path
*
* @return void
*/
function sendfile($filename) {
header("Xerver-Internal-FileServer: " . $filename);
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment