Sometimes I’m not sure what is going to be in the $_POST array and what is not. As a result I often get a stack of “Notices” such as:
Undefined index: detail_level in /blah.php on line 58
Is it okay to turn notices off and just not worry about it, or is it considered poor programming to leave these things?
If it’s not considered good, how do I get around it in the most elegant way possible?
I’ve tried
if ($_POST["detail_level"]) // check if it exists
... // do my stuff
But that just gives the same notice.
Thanks
try this:
if (isset($_POST["detail_level"])) // check if it exists
{
... // do my stuff
}else{
echo 'Yes we have no $_POST["detail_level"]';
}
[/php/
Most advanced PHP frameworks/applications provide wrapper functions for accessing GET, POST, COOKIE and SESSION.
Besides checking for is_set() or array_key_exists() , these functions can perform additional tasks such as cleansing of user input and other common sense chores. An example of this would be checking the magic_quotes_gpc setting and, if necessary, removing the slashes added by PHP.
I suggest that you look at the API of any open source application and learn how they handle the GET/POST variables.
xgoannax:
If it’s not considered good, how do I get around it in the most elegant way possible?
I’ve tried
if ($_POST["detail_level"]) // check if it exists
... // do my stuff
But that just gives the same notice.
The standard technique is to create a variable that will hold the value, check if the $_POST value exists, and if so, copy it to the created variable.
$detail_level = '';
if (isset($_POST['detail_level'])) {
$detail_level = $_POST['detail_level'];
}
If you’re PHP is version 5.2 or better, you can use filter_input instead
$detail_level = filter_input(INPUT_POST, 'detail_level');
which has some useful sanitizers and [url=“http://www.php.net/manual/en/filter.filters.validate.php”]validators
For example:
$detail_level = filter_input(INPUT_POST, 'detail_level', FILTER_SANITIZE_STRING);
or
$detail_level = filter_input(INPUT_POST, 'detail_level', FILTER_VALIDATE_INT);