On a php file that many variables are received by $_REQUEST[]
or $_POST[]
, and I have to check them in case the value is null
with the function isset()
, it is quite troublesome. Is there a better solution?
views:
103answers:
4How about using a combination of in_array
and array_map
, e.g.:
// array of possible parameters that can be passed by the client
$keys = array('username','password');
// this will store the names of the ones that are not present
$missing = array();
foreach($keys as $key) {
if(!in_array($key, $_POST)) {
$missing[] = $key;
}
}
$nullOffsets = array_map("is_null", $_POST);
echo 'Printing missing params:<br />';
print_r($missing);
echo 'Printing null existing params:<br />';
print_r($nullOffsets);
If you had the variables in an array (don't just use the request or post arrays) you could loop through them calling the isset()
function. Depending on what your current code is, this might be 'better'.
User input checking is troublesome, but its a necessary evil.
Personally I prefer not using $_GET
or $_POST
other than copying needed content to my own variables for processing.
At the top of my .php file, I keep an array with names of values that I wish to copy from $_GET
or $_POST
This adds up to:
// the following array needs to be modified when you change your input specs
$inputAllowed = array("name", "title", "company");
$input = array();
foreach($inputAllowed as $key)
if( array_key_exists( $key, $_POST ) )
$input[$key] = $_POST[$key];
else
$input[$key] = "";
Its easy to add an "is_null" check in there with handling for in case something shouldn't be null. Or you can first let the loop finish and then loop over $input
You can try wrapping the array in an object.
class ArrayWrapper {
private $data;
public function __get($var) {
if (!isset($this->data[$var])) {
return false;
}
else {
return $this->data[$var];
}
}
public function __construct($a) {
$this->data = $a;
}
}
$a = array('test' => 1);
$aw = new ArrayWrapper($a);
if ($aw->test != false) {
echo "test: ".$aw->test;
}
if ($aw->foo != false) {
echo "foo: ".$aw->foo;
}