[PHP] How to load pages through "index.php".

RastaLulz

fight teh power
Staff member
May 3, 2010
3,926
3,921
Hello,

Today I will be showing you a very basic way of loading all your pages through "index.php", rather than having to make a separate file for each page with the same template, includes, etc.

PHP:
<?php
 
// here you could include the header of your site
// require_once 'skin/header.php';
 
/* CONFIG */
 
$path = 'path/to/pages/'; // path to the folder where you store pages
 
$default_page = 'home'; // if no page is set, this will be included
 
$default_404_page = '404'; // if the page does not exist, this will be included
 
/* SLAVE */
 
if(empty($_GET['page'])) { // check if you have set the page in the URL
 
    $page = $default_page; //set the default page set in the config since no page was set in the URL
 
}else{
 
    // the code below checks if the page contains only letters, numbers, underscores and/or dashes
    // it also checks if the file exists
 
    $page = (preg_match('/[^a-zA-Z0-9\ _-]/', $_GET['page']) || !file_exists($path . $_GET['page'] . '.php') ? $default_404_page : $_GET['page']);
 
}
 
// includes the page correct page
 
require_once $path . $page . '.php';
 
// here you could include the footer of your site
// require_once 'skin/footer.php';
 

gamermarcus555

New Member
Jan 27, 2012
3
0
Hi rasta. (dont laugh) so i just modify this code to my paths and insert the code to my "Content Div" example <div id="content">etc etc </div>
 

DaLightz

See ya'll in the afterlife.
May 19, 2012
1,136
262
Put this in your htaaccess!

Instead of going to:
You can do:

Here:
PHP:
RewriteEngine On
 
RewriteRule ^(|/)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9_-]+)(|/)$ index.php?page=$1
 

brsy

nah mang
May 12, 2011
1,530
272
Didn't mean to bump, but you didn't explain what they're suppose to do with this code, so I will. Once you have this code set, you need to add a GET parameter to your URL. This mean that you need to do name)

Or, if you want something less harmful for the eyes, you can do what DaLightz suggested with HTACCESS.
Put this in your htaccess!

Instead of going to:
You can do:

Add the following into a new file called .htaccess if it isn't already created!
Here:
PHP:
RewriteEngine On

RewriteRule ^(|/)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9_-]+)(|/)$ index.php?page=$1
 
Last edited:

AaidenX

Member
Jun 30, 2012
261
29
I wouldn't recommend anyone to use this nor would I use this. All this does is simply include files according to the URL. It would be much better if there was a Routing Library with this. .
 

Users who are viewing this thread

Top