dynamic include methods
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('a开发者_如何转开发bout.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.
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
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.
精彩评论