Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I Use PHP Superglobals or Filter Input to Retrieve $_GET data?

I really hate global variables - maybe its the C# programmer in me but when I'm working in PHP I grit my teeth every time I have to do something like this:

$strUsername = $_GET['username'];

Yes, I'm grossly oversimplifying it and yes yes I sanitize all of this properly. In fact, for the framework that I built, all of the superglobals are grabbed almost at the beginning of execution and are dependency-injected from there on out.

I ran across this function in the PHP manual (you truly learn something new every day): filter_input_array().

So now, technically, I can do this instead of grabbing everything from the GET superglobal:

$GETdata = filter_input_array(INPUT_GET);

.... and so on and so forth with the others like POST, REQUEST, etc. My question is: should I use filter_input_array and so avoid the scourge of superglobals, or is there some reason to stick with them and forget about using the filter_input functions? What is everyone else's experience with this?

EDIT: I forgot one thing - the filter_input functions are blind to any script-level modifications you make to the superglobals so if I do: $_GET['cheese'] = 'puff'; trying to do filter_input(INPUT_GET, 'cheese'); later will return null. This is fine since I dependency inject everything but it could catch somebody off guard later, if they are unaware.

like image 899
Jarrod Nettles Avatar asked Apr 14 '11 15:04

Jarrod Nettles


2 Answers

I use PHP superglobals, but only at the library level in my Framework. This is framework all controllers have access to the request object, which in turn access the superglobals. This allows you to write tests for your controller by making a mock request object populated with your test parameters. It's all about good OO design and good design patterns.

Accessing the superglobals directly everywhere without any abstraction in place is an anti-pattern.

like image 103
Easen Avatar answered Nov 09 '22 08:11

Easen


Using filter_input_array is still using superglobals because it's still getting its data from one of the superglobal arrays.

There's nothing wrong with getting your data from one of these arrays, its really the only way to get the data actually. You just have to make sure you escape it for whatever you're using it in.

htmlentities for html, prepared string for pdo, mysql_real_escape_String for mysql_ functions etc...

like image 39
Galen Avatar answered Nov 09 '22 08:11

Galen