Oh... I thought my code could speak for itself but it seems not true though.
There aint need for doing anything else than what I showed above. No if conditions, no test for readable file, no need to check if item is in array, no foreach, etc. Let me introduce a more instructive and generally applicable perspective of the same idea:
Code: Select all
<pre><?php
// Copy the data from the URL's query string or set default value:
$_get_display = isset($_GETї'display']) ? $_GETї'display'] : 'home';
// All the following info could be stored in a database as kettle_drum
// courteously points out. Define a set of valid pages:
$valid_pages = array(
'home' => 'index',
'about' => 'the_company/index',
'work' => 'workforus',
'news/tech' => 'news/tech',
'news/science' => 'news/sci',
'news/politics' => 'under_construction',
'contact' => 'contact'
);
// Here is the key! Two arrays get merged, one containing the value 'error'
// for the $_get_display index ($_GETї'display'] in most cases) and the other
// is the set of valid pages as defined above. When they get merged, if by
// any case $_get_display indexes a value in $valid_pages (i.e. if exists
// $valid_pagesї$_get_display]) the value 'error' is replaced by the value in
// $valid_pages indexed by $_get_display (i.e. $valid_pagesї$_get_display]):
$pages = array_merge(array($_get_display => 'error'), $valid_pages);
// In short $pagesї$_get_display] can assume only 1 of 2 possible values:
// 1) 'error'
// 2) $valid_pagesї$_get_display]
// Let's take a look at $pages:
print_r($pages);
// Now it is sure this is either a valid page or the error page:
$page = $pagesї$_get_display] . '.php';
echo $page;
?></pre>
Let's test it! For a normal access, say '
query-string.php?display=news/science', here is the output:
Code: Select all
Array
(
їnews/science] => news/sci
їhome] => index
їabout] => the_company/index
їwork] => workforus
їnews/tech] => news/tech
їnews/politics] => under_construction
їcontact] => contact
)
news/sci.php
Now imagine one malicious user trying to hack the application. When she tries '
query-string.php?display=../include/class.dbconnect', this is what she gets:
Code: Select all
Array
(
ї../include/class.dbconnect] => error
їhome] => index
їabout] => the_company/index
їwork] => workforus
їnews/tech] => news/tech
їnews/science] => news/sci
їnews/politics] => under_construction
їcontact] => contact
)
error.php
As it becomes clear, only pages specifically defined as valid will get included. Even an attempt to crack the app with '
query-string.php?display=+_(-)*$%@!/\|%13%10?'[]"' will fail:
Code: Select all
Array
(
ї _(-)*$%@!/\\|?''ї]"] => error
їhome] => index
їabout] => the_company/index
їwork] => workforus
їnews/tech] => news/tech
їnews/science] => news/sci
їnews/politics] => under_construction
їcontact] => contact
)
error.php
I hope it will be useful. Soon I will post it in the Code Snippets forum, with bits of improvement.
Regards,
Scorphus.