Jump to content

Do not access superglobal directly


davej

Recommended Posts

So am I to understand that rather than using...

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
}

...or...

if(isset($_POST['submit')){
}

...I am supposed to instead use...

$in = filter_input(INPUT_SERVER,'REQUEST_METHOD',FILTER_SANITIZE_STRING);
if ($in == "POST") {
}

...and...

$in = filter_has_var(INPUT_POST, 'submit');
if($in == TRUE)) {
}

???

 

Link to comment
Share on other sites

I wouldn't bother with filter_input for $_SERVER or $_ENV in the vast majority of cases, and I also wouldn't bother using it with an if statement unless I need type checking (maybe I need an array from $_POST, for example). Otherwise, you would filter the input whenever you need to make sure that the data is sanitized. If you're using those values in a URL, console command, etc, then they need to be sanitized. If you're just checking in an if statement there isn't much point (although using filter_input can avoid having to use multiple checks like isset).

Link to comment
Share on other sites

Somebody in the Php world must feel there is a security issue since Php provides filter_input() and filter_has_var(). Netbeans seems to get the blame for providing a warning about this, but Netbeans didn't write those Php functions.

 

Based on some postings such as https://www.phparch.com/2010/07/never-use-_get-again/ (which is an old article dated way back in 2010) it seems that the basic idea is that this approach is intended to prevent any occasional, accidental, lack of sanitizing.

 

Has this idea died and if so, did it die for a good reason?

Link to comment
Share on other sites

I don't agree with the article. There's no single function that can predict how you intend to use the information supplied by the user.

 

If you intend to use it in your HTML:

$html = htmlspecialchars($_GET['data']);

If you intend to use it in SQL

$query = $pdo->prepare('SELECT * FROM table WHERE id = ?');
$query->execute(array($_GET['data']));

If you intend to use it in mathematical operations:

$float = (float) $_GET['data'];
$int = (int) $_GET['data'];

If you tried to use an escaped GET or POST value in a prepared statement you would end up with backslashes in your database table.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...