Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it secure to use "require" with GET/POST data?

Tags:

security

php

Is it secure to use the following code:

require($_SERVER['DOCUMENT_ROOT'] . "/pages/" . $_GET['page'] . ".php") 
like image 534
iamart Avatar asked Jul 26 '12 19:07

iamart


Video Answer


3 Answers

No, it is not secure. Why?

Because sequence of two dots /../ means one directory back and the attacker could potentially include anything on your system, even above $_SERVER['DOCUMENT_ROOT']. (In an unfortunate configuration that means secret/sensitive OS config files.)

You have to IF or SWITCH for the allowed values to prevent malicious input. Example:

switch($_GET['page']) {
     case 'welcome': $page='welcome';
     case 'shop': $page='shop';
     default: $page='index';
}
require($_SERVER['DOCUMENT_ROOT'] . "/pages/" . $page . ".php")

Also check out in_array() for a little easier filtration.

like image 158
Rok Kralj Avatar answered Nov 11 '22 01:11

Rok Kralj


StackOverflow has a useful Q&A for how to sanitize user input with PHP. It's a few years old, but the principles haven't changed at all.

The quick answer is: if you can avoid the problem in the first place, you're better off.

Show us how you're trying to use this, and we may be able to offer suggestions for improvement.

like image 31
ghoti Avatar answered Nov 10 '22 23:11

ghoti


It's not secure. You can use array with allowed values. For example

$allowed_pages = array('index', 'test', 'my_page')
if (!in_array($_GET['page'], $allowed_pages)){
    echo 'good bye';
    die();
} else {
   //
}
like image 40
yAnTar Avatar answered Nov 11 '22 00:11

yAnTar