Simple tutorial on how to create nice SEF URL routing system without MVC and OOP.
Let’s begin with .htaccess file.
Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !^(.+)\.(css|js|jpg|gif|png|ico)$ RewriteRule ^(.*) index.php [QSA,L] |
This .htaccess configuration will redirect all requests to index.php except files ending .css, .js, …
Index.php will proceed all requests.
index.php
<?php $p=explode('/',$_SERVER['REQUEST_URI']); if ($p[1]=='') { $p[1]='index'; } if (file_exists($m=$p[1].'.ctrl')) { ob_start(); require $m; $content = ob_get_contents(); ob_end_clean(); } else { $content = 'page not found'; } include 'layout.php'; |
index.php with comments
<?php //reads the address and splits it with explode function //for example, adress /article/100-Hello/4, creates $p array ['','article','100-Hello','4'] //Chosen page will be in the array element with index 1 $p=explode('/',$_SERVER['REQUEST_URI']); //checks for home page with uri '/' then $p[1] will be '', if so we assign value 'index'. if ($p[1]=='') { $p[1]='index'; } //we check for file existence. For example files: index.ctrl, user.ctr, login.ctrl if (file_exists($m=$p[1].'.ctrl')) { //if exists, we do not output it but we execute file and save output in the variable $content. ob_start(); require $m; $content = ob_get_contents(); ob_end_clean(); } else { //if it doesn't exist, then we save in content that page cannot be found $content = 'page not found'; } //By now we have generated changing content of the page, we call for layout.php which will output all content including $content. include 'layout.php'; |
If /module/param1/param2/ will be called, index.php will call module.ctrl and generated output will be included in the layout.php file. There is nothing for it but to write needed layout.php and .ctrl files.
layout.php
<div>Header</div> <?php echo $content; ?> <div>Footer</div> |
index.ctrl
<b> You are in the home page </b> |
user.ctrl
Hi! I am <?php echo $p[2]; ?>. user. |
Now try to call /user/123 url.
For now for each new page you need to create new .ctrl file, where you can write suitable code for the page.
Is this thing on?
Safety last?!
What do you mean by safety last?
Do not name .php files .ctrl. requesting reveals their code.
.ctrl files should be stored outside public_html directory
Mozilla cant load the page /user/123 because “The page is not redirected properly”.
So basically this method is useless and bad.