tags:

views:

31

answers:

2

Among the following include methods which is the best to practice and why?

$page = $_GET['page'];

Method 1

$pages = array('home', 'blog', 'about');
if( in_array($page, $pages) )
{
    include($page.'.php');
{
else
{
   die('Nice Try.');
}

Method 2

if($page = 'home'){
include('home.php');
}else if($page = 'blog'){
include('blog.php');
}else if($page = 'about'){
include('about.php');
}

Method 3

if(str_replace("http://", "gth://", $page) == $page){
include_once $page;
}else{
       die('Nice Try.');
}

or any other solutions? I dont prefer method 1 and 2 as it always needs to be updated everytime i add a new page.

+2  A: 

extending/maintaining the first way is easiest, second way is worse. third way is no way to go, as it relies on user input to require pages... it is going to be a security hole

kgb
but it removes foreign pages from included..so i think its save, unless if they somehow upload the malicious php to the server.
Exoot
A: 

I believe that the first one is the best of the lot. You can try the second one, but it's for the freshers. And the third one is a BIG NO, because any fresher hacker could hack your "if" condition, & more loopholes will start creeping in.

As for your problem, on adding a new page to the array, every time a new page is created, for the first method, I have one solution:-
Let's say you're putting all the new pages in one folder "abc". Now just write one file code as the following, to read all the files / pages existing in that folder:-

<?php
$page = $_GET['page'];
$pages = array();
/**
 * If you are using all the pages existing in the current folder you are in,
 * then use the below variable as:-
 * $path = ".";
 */
$path = 'abc/'; // Change the Path here, related to this Folder name
$handle = opendir($path);
while (($file = readdir($handle)) !== false) {
    $pages[] = $file;
}
closedir($handle);

if( in_array($page, $pages) ) {
    include($page.'.php');
}
else {
    die('Nice Try.');
}
?>

So you see that the array is getting filled up dynamically, without the need to mention all the pages you create every time. And you are using the first method only. And keep the including pages in one separate folder, which you will need to include every time, in other main pages.

Hope it helps.

Knowledge Craving
wow, great idea! but wouldnt it cause any performance issues for checking the folder everytime?
Exoot
@Exoot - If your project is a small / medium sized one, then no problem will arise. But say if you are doing some SNS project (of Ning / Facebook caliber, or some very big Real Estate projects), then it may be a bit of concern. Still it shouldn't get you into trouble.
Knowledge Craving