Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Last active June 4, 2018 16:20
Show Gist options
  • Select an option

  • Save julianjupiter/36d3644f4b274976bc44a2d8ac2e6df0 to your computer and use it in GitHub Desktop.

Select an option

Save julianjupiter/36d3644f4b274976bc44a2d8ac2e6df0 to your computer and use it in GitHub Desktop.
Simple Routing in PHP
<?php
$contextPath = '/pepcon';
$url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $contextPath;
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
$urlSegments = explode('/', rtrim($url));
echo 'URL: ' . $url . '<br>';
echo 'HTTP Method: ' . $requestMethod . '<br>';
echo '<pre>';
var_dump($urlSegments);
echo '</pre>';
$loggedUser = 'acalvarez';
if ($requestMethod == 'GET') {
switch($url) {
case $contextPath: // login
case $contextPath . '/': // login
case $contextPath . '/index.php': // login
index();
break;
case $contextPath . '/homepage':
homepage();
break;
case $contextPath . '/' . $loggedUser:
profile();
break;
default:
users();
error404();
break;
}
}
function index() {
echo 'Login';
}
function homepage() {
echo 'Home page';
}
function profile() {
global $loggedUser;
echo $loggedUser;
echo '<br>profile';
}
function users() {
$users = ['accruz', 'acsantos', 'acrodriguez']; // from db
global $urlSegments;
global $loggedUser;
if (count($urlSegments) == 3) {
$user = $urlSegments[2];
if ($user != $loggedUser && in_array($user, $users)) {
echo $user;
echo '<br> other user';
exit;
}
}
}
function error404() {
header("HTTP/1.0 404 Not Found");
echo 'Error 404, page not found!';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment