Last active
June 4, 2018 16:20
-
-
Save julianjupiter/36d3644f4b274976bc44a2d8ac2e6df0 to your computer and use it in GitHub Desktop.
Simple Routing in PHP
This file contains hidden or 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 | |
| $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