GM wrote:Code: Select all
foreach($_POST as $key=>$data) {
$$key = $data;
}
If your going for this method, then your far better to use
extract() and avoid looping all together. A more recommended method is check for expected variables, usually followed with their validation rules..
I usually do something along the lines of
Code: Select all
<?php
/**
* Params array
* param name => validation pattern, required (true)/optional (false)
*/
$params = array(
'firstname' => array('/[a-Z]+/', true),
'lastname' => array('/[a-Z]+/', true),
'somekey' => array('/[0-9]+/', false)
);
$validation = new Validation($params, $_POST);
if ($validation->isValid())
{
//do some action because all required params are valid and present
}
else
{
echo '<pre>';
print_r($validation->getInvalidParams());
echo '</pre>';
}
?>
the validation object looking roughly like
Code: Select all
class Validation()
{
protected $invalid;
protected $params;
protected $source;
public function __construct($params, $source)
{
$this->params = $params;
$this->source = $source;
}
public function isValid()
{
if (!is_array($this->params) && !count($this->params))
{
throw Exception('Must supply array of required paramaters');
}
foreach ($this->params as $param => $rules)
{
if (empty($this->source[$param]) && $rules[1] == true)
{
array_push($this->invalid, $param);
}
elseif (isset($this->source[$param]) && !preg_match($rules[0], $this->source[$param]))
{
array_push($this->invalid, $param);
}
}
return (is_array($this->params) && count($this->params) ? true : false);
}
public function getInvalidParams()
{
if (!is_array($this->params) && !count($this->params))
{
throw Exception('Method cannot be called unless invalid params recognized');
}
return $this->invalid;
}
}