PHP include () alternative?

I want to know if my code is safe and if there are other safer alternatives for including external files.

So this is my sample code, is it safe? How can I make it safer? Thank!

<?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; 
} ?>
+3
source share
6 answers

You have a good code. There is no problem conditionally, including files, as you do, because the file names are hard-coded. The problem occurs when the included file is based on an unsuccessful value from the user. for instance

include $_GET['p'];

Which may include everything that the user wants (depending on the PHP settings, he may also include files in other domains)

Other options are options for what you are doing.

require require_once , . inlucde_once require_once , , , .

include_once 'myfile.php';
include_once 'myfile.php'; //does nothing as the file is already included

, . , , .

+6

$_GET['p'] . , - , ( ).

, ", ", .

, , p -, , , .

, . - URI , , :)

+1

, , , , . , , . .

, include require, , -.

0

, .

, , , . script, , , , require('filename');.

0

, switch . , $__ POST, , .: D

0

, :

$safeIncludes = array('test1', 'test2', 'test3');
$p = $_GET['p'];
if(in_array($p, $safeIncludes)) {
    $scriptName = $p . '.php';
    include($scriptName);
}

, , .

-1

Source: https://habr.com/ru/post/1740672/


All Articles