modern-web-design-and-development

(Brent) #1

include index.php and so on. All other requests would trigger the error
message. Note that the error message is in our control and not from the
server; or else you might display information that could be used for an
exploit.


Also, notice how defensive the script is. It checks if a page parameter has
been sent; then it checks if an entry for this value exists in the sites array;
then it checks if the file exists; and then, and only then, it includes it. Good
code does that... which also means it can be a bit bigger than expected.
That’s not exactly “Build your own PHP templating system in 20 lines of
code!” But it’s much better for the Web as a whole.


Generally, defining all of the variables you will use before you use them is a
good idea. This makes it safer even in PHP set-ups that have globals
registered. The following cannot be cracked by calling the script with an
authenticated parameter:


1 $authenticated = false;
2 if($_POST['username'] == 'muppet' &&

(^3) $_POST['password'] == 'password1') {
(^4) $authenticated = true;
5 }
6 if($authenticated) {
(^7) // do something only admins are allowed to do
8 }
The demo we showed earlier makes it possible to work around this,
because $authenticated was not pre-set anywhere.
Writing your own validator function is another option. For example, the
color demo could be made secure by allowing only single words and
numbers for the colors.

Free download pdf