How many times have you wanted to extract selected GET or POST or COOKIE variables into local/global variables to be used easily? Something like:
$submit = (int) $_REQUEST['submit']; $name = $_REQUEST['name']; $email = $_REQUEST['email']; $preference = (int) $_REQUEST['preference']; if ($submit) { if (!$name and !$email) { $error = 'Please fill in your name and email'; } else { sql("insert into POST values (?, ?, ?)", $name, $email, $preference); } }
And then at another page, you need to do the same thing over and over again (and you don't actually care whether it's GET or POST or...)
$start = (int) $_GET['start']; $length = (int) $_GET['length']; $locale = $_GET['locale'];
Solution: I have always been using this function to extract request variables to the global scope:
// first example getVars('submit name email preference'); echo "Your name is $name"; // the variable $name is now available // second example getVars('start length locale');
Isn't it convenient?
How does getVars() function look like?
function getVars($vars) { if (is_string($vars)) { $vars = split(' ', $vars); } foreach ($vars as $var) { $GLOBALS[$var] = $_REQUEST[$var]; } }
The trick is to move the variables from $_REQUEST to $GLOBALS.
Now let's enhance it so that it converts the variables to int when needed:
function getVars($vars) { if (is_string($vars)) { $vars = split(' ', $vars); } foreach ($vars as $var) { $modifier = ''; if (strpos($var, '/') !== false) { $tp = split('/', $var); $var = $tp[0]; $modifier = $tp[1]; } $value = $_REQUEST[$var]; if ($modifier == 'hex') { $value = pack("H*", $value); } elseif ($modifier == 'int') { $value = (int)$value; } $GLOBALS[$var] = $value; } }
We go back to the examples, we now have:
// first example getVars('submit/int name email preference/int'); // second example getVars('start/int length/int locale');
Such a useful function, Let us use it!
Tip: you can also write '/hex' to convert "414243" to "ABC"
No comments:
Post a Comment