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
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
requireandrequire_oncewill fail if the file doesn’t exist.inlucde_onceandrequire_onceensure that the file is only included once, so it that file has been inlucded elsewhere in the program it won’t be 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.