Skip to content

Instantly share code, notes, and snippets.

@cagcak
Last active June 6, 2018 11:52
Show Gist options
  • Save cagcak/3348105d1ba45bafbd07b7c62c5bd133 to your computer and use it in GitHub Desktop.
Save cagcak/3348105d1ba45bafbd07b7c62c5bd133 to your computer and use it in GitHub Desktop.
A simple routing function with i18n json data
<?php
define('i18n', dirname(__DIR__) . '/locales/');
function __($phrase) {
$locale = $GLOBALS['APPLANG'];
static $trans = NULL;
$ext = '.json';
if (is_null($trans)) {
$lang_file = i18n . $locale . $ext;
if (!file_exists($lang_file)) {
$lang_file = i18n . $locale . $ext;
}
$lang_file_content = file_get_contents($lang_file);
$trans = json_decode($lang_file_content, true);
}
// return var_dump($trans[$phrase]);
return $trans[$phrase];
}
<?php
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
if ( is_session_started() === FALSE ) {
session_start();
$available_langs = array('en','tr');
$_SESSION['lang'] = 'tr';
if(isset($_GET['lang']) && $_GET['lang'] != ''){
if(in_array($_GET['lang'], $available_langs)) {
$_SESSION['lang'] = $_GET['lang']; // Set session
}
} else {
$GLOBALS['APPLANG'] = 'tr';
}
$GLOBALS['APPLANG'] = $_SESSION['lang'];
$GLOBALS['i18n'] = '?lang=' . $GLOBALS['APPLANG'];
}
<?php
function route($req)
{
require_once dirname(__DIR__) . '/web.php';
$req_file = $routes[$req] . '.php';
$url = parse_url($req);
if (is_readable($req_file)) {
include_once $req_file;
} elseif ( strpos($req, $GLOBALS['i18n']) ) {
$req = $url['path'];
include_once $routes[$req] . '.php';
} else {
echo "404: File name " . $req . " could not be loaded";
}
}
<?php
$routes = [
'/' => dirname(__DIR__) . 'pages/index',
'/about' => dirname(__DIR__) . 'pages/about',
'/sub/page' => dirname(__DIR__) . 'pages/sub/page'
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment