A couple of years ago, I blogged about two helper functions I wrote to get HTML form data in PHP: getGet
and getPost
. These functions do a pretty good job, but I have since replaced them with a single function: getData
. Seeing as I haven't discussed it yet, I thought I would do so today. First, here's the function in its entirety:
/**
* Obtains the specified field from either the $_GET or $_POST arrays
* ($_GET always has higher priority using this function). If the value
* is a simple scalar, HTML tags are stripped and whitespace is trimmed.
* Otherwise, nothing is done, and the array reference is passed back.
*
* @return The value from the superglobal array, or null if it's not present
*
* @param $key (Required) The associative array key to query in either
* the $_GET or $_POST superglobal
*/
function getData($key)
{
if(isset($_GET[$key]))
{
if(is_array($_GET[$key]))
return $_GET[$key];
else
return (strip_tags(trim($_GET[$key])));
}
else if(isset($_POST[$key]))
{
if(is_array($_POST[$key]))
return $_POST[$key];
else
return (strip_tags(trim($_POST[$key])));
}
else
return null;
}
Using this function prevents me from having to do two checks for data, one in $_GET
and one in $_POST
, and so reduces my code's footprint. I made the decision to make $_GET
the tightest binding search location, but feel free to change that if you like.
As you can see, I first test to see if the given key points to an array in each location. If it is an array, I do nothing but pass the reference along. This is very important to note. I've thought about building in functionality to trim and strip tags on the array's values, but I figure it should be left up to the user of this function to do that work. Be sure to sanitize any arrays that this function passes back (I've been bitten before by forgetting to do this).
If the given key isn't found in either the $_GET
or $_POST
superglobals, I return null
. Thus, a simple if(empty())
test can determine whether or not a value has been provided, which is generally all you care about with form submissions. An is_null()
test could also be performed if you so desire. This function has made handling form submissions way easier in my various work with PHP, and it's one tool that's worth having in your toolbox.