I want to know if my code is safe and if there are other safer alternatives to include external files..
So this is my code example, is it safe? How can I make it safer? Thanks!
<?php switch($_GET['p']){
case 'test1':
include 'test1.php';
break;
case 'test2':
include 'test2.php';
break;
case 'test':
echo 'something';
include 'pages/test.php';
echo 'something';
break;
default:
include 'main.php';
break;
} ?>
You code is fine. There is no issue conditionally including files like you are doing as the file names are hardcoded. The issue occurs when a the file included is based on an un-sanitized value from the user. E.g
include $_GET['p'];
Which can include whatever the user wants (depending on PHP settings it may also include files on other domains)
The other options are variations on what you are doing
require
and require_once
will fail if the file doesn't exist. inlucde_once
and require_once
ensure that the file is only included once, so it that file has been inlucded elsewhere in the program it won't be included.
include_once 'myfile.php';
include_once 'myfile.php'; //does nothing as the file is already included
If you have use classes, there is also the option of the autoloader. From the looks of your application you would have to re-structure it to be able to use it though.
You might consider examining the contents of $_GET['p']
prior to even entering the switch. If it contains special characters, rubbish or something else, your program may want to log the incident (and not waste time trying to render the page).
At the least, a nice and polite "Sorry, we could not process your request" page would be in order.
This still allows the switch to fall through to the main page, provided that p
contained something worthy of the switch evaluating in the first place.
This is especially true if the main page does any amount of queries in order to render. Sooner or later, someone will notice your URI structure and decide that it might be fun to play with it, don't burn CPU cycles on idiots :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With