Using $_Request inside function PHP - php

1)
I have this:
function ObtainRequest($Field, $Method) {
$Returned = "";
if ($Method == "POST")
$Returned = $_POST[$Field];
else if ($Method == "GET")
$Returned = $_GET[$Field];
else
$Returned = $_REQUEST[$Field];
return $Returned;
}
Now, using the function:
if (isset(ObtainRequest("OneField","POST"))) {
DoSomething();
} else if (!isset(ObtainRequest("OneField","POST"))) {
DoOtherthing();
}
But my script isn't running (SHOWING PLANK PAGE)...
What's my mistake?
2)
The $_REQUEST is lost inside of function?
This code works!!:
if (isset($_REQUEST["OneField"])) {
DoSomething();
}
This code doesn't work!!:
if (isset(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
This code doesn't work!!:
if (empty(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
3)
Is it applicable to Session too?

Your mistake is here:
$Method == "Post"
But you passing uppercased POST:
ObtainRequest("OneField","POST")
Fix with strtoupper():
function ObtainRequest($Field, $Method) {
$Returned = "";
$Method = strtoupper($Method);
if ($Method == "POST")
$Returned = isset($_POST[$Field]) ? $_POST[$Field] : false;
else if ($Method == "GET")
$Returned = isset($_GET[$Field]) ? $_GET[$Field] : false;
else
$Returned = isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
return $Returned;
}
Also, this function might be shortened with switch construction:
function ObtainRequest($Field, $Method) {
switch(strtoupper($Method)){
case "POST": return isset($_POST[$Field]) ? $_POST[$Field] : false;
case "GET": return isset($_GET[$Field]) ? $_GET[$Field] : false;
default: return isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
}
}
Second problem is that isset() might be used with variables, but not with function results. Use boolean check instead:
if (ObtainRequest("OneField","POST") !== false) {
DoSomething();
} else if (ObtainRequest("OneField","POST") === false) {
DoOtherthing();
}
Is it applicable to Session too?
Well, if you interested in my opinion: I would not mix $_SESSION in such function with $_POST, $_GET and $_REQUEST, because $_SESSIONs meaning is different. Also, it exists differently, not like them.
However something like this function might be realized for $_SESSION itself.

The first problem which I can see that you are using post instead of POST...
yes you can do this with sessions too, but codes need to be modified a bit..

Related

Set and validate return value in IF in PHP

Could I do this in PHP?
if ($Var = $this->test1() == true) {
var_dump($Var);
}
public function test1() {
return true;
}
It echoes true, but I'm not sure if this is the correct way to check such return values.
Yes you can, but write:
if (($var = $this->test1()) === true) {
var_dump($var);
}
To be safe and to alert the reader there is something going on.
I wouldn't advise you to do this though, but in some cases this is acceptable; such as a complex if-else tree where lazy execution is desirable.
if (($result = slow_process()) !== false) {
return $result;
} else if (($result = slow_process1()) !== false) {
return $result;
} else if (($result = slow_process2()) !== false) {
return $result;
} else if (($result = slow_process3()) !== false) {
return $result;
}
This is overly simplified, but these situations do occur.
You can but there is 2 things you should be aware of :
When you do something like :
if ($Var = $this->test1() == true) {
The operators are confusing :
do you want to do $this->test1() == true and store result $var
do you want to do $var = $this->test1() and compare it with true
In your case, $this->test1() returns true so it does not matter. But if we change your code a bit :
if ($Var = $this->test1() == 5) {
var_dump($Var);
}
public function test1() {
return 3;
}
Someone who read your code will not understand if you want to store $this->test1() in $Var (so, make 3 in var) or if you want to put result of comparison $this->test1 == 5 in $Var (false).
What remains in $Var at the end may be a very good question at the PHP 5.3 Certification but not in a useful case.
To avoid mistakes, uses parenthesis :
if (($var = $this->test1()) == true) {
You should take care of types :
I give you an example of what could return something castable to true :
function test1() { return true; }
function test2() { return 3; }
function test3() { return 3.42; }
function test4() { return "x"; }
function test5() { return array('x'); } // array() == true returns false
function test6() { return new stdClass(); }
echo test1() == true;
echo test2() == true;
echo test3() == true;
echo test4() == true;
echo test5() == true;
echo test6() == true;
// outputs 111111 (1 = true)
To avoid mistakes, you should use === operator. Your final piece of code becomes :
if (($var = $this->test1()) === true) {
The == true part is unnecessary. What you have is valid syntax, but some find it confusing. You can always do:
$Var = $this->test1();
if ($Var) { ...
Just decide on the standard with your development team.
You can also do:
if ($Var = $this->test1()) {
var_dump($Var);
}
public function test1() {
return true;
}

I need a more efficient way of checking if multiple $_POST parameters isset

I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}

isset($) double if/elseif/else. Can it cleaner?

Okay, I got this code build up but i guess it is somehow ugly.
Can this been done better?
if (isset($_GET['lang'])) {
$lang = $_GET['lang'];
if ($lang == 'en') {
$_GET['method']($lang);
}
elseif ($lang == 'nl') {
$_GET['method']($lang);
}
else {
$_GET['method']($lang);
}
}
else {
$lang = '';
$_GET['method']($lang);
}
function GET($name, $default=null)
{
if ( !isset($_GET[$name]) )
return $default;
return $_GET[$name];
}
$method = GET('method'); // Don't forget to error-check $method too, or it will be a major security hole!
$method(GET('lang',''));
It appears that you intend to $_GET['method']($lang) no matter what the value of $lang is. So don't check the value; just determine it, and then use it.
if (isset($_GET['lang'])) { $lang = $_GET['lang']; }
else { $lang = ''; }
$_GET['method']($lang);
Won't
if (isset($_GET['lang'])){
$lang = $_GET['lang'];
if ($lang == 'en'){
$_GET['method']($lang);
} elseif ($lang == 'nl'){
$_GET['method']($lang);
} else {
$_GET['method']($lang);
}
} else {
$lang = '';
$_GET['method']($lang);
}
do exactly the same as
if (isset($_GET['lang'])){
$lang = $_GET['lang'];
$_GET["method"]($lang);
} else {
$lang = '';
$_GET['method']($lang);
}
#Highmastdon: To make the example complete see my correction
Since you're calling $_GET['method']($lang); in every case, including the else, you don't need all those conditions to do the same thing; the code you've given could be written as simple as this:
$lang = isset($_GET['lang']) ? $_GET['lang'] : '';
$_GET['method']($lang);
You could even combine those two lines into one like so:
$_GET['method'](isset($_GET['lang']) ? $_GET['lang'] : '');
...although that is starting to get a bit un-readable.
However, I would echo the point made by #Vilx- that calling a function name that is specified directly from the browser can be a major security risk, so you*really* need to vet the contents of method and lang. (imagine if the url looked like ?method=eval&lang=rm+index.php)
$_GET['method'](isset($_GET['lang']) ? $_GET['lang'] : '');
But please, please please don't do this. You have a massive security hole, if the user specifies method=eval (or any other function that you don't really want called).

Checking user input

I'm creating an edit page which should get called this way:
users.php?action=edit&id=5
This is my code for this:
} elseif (isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
As you see it's long. First a check with isset is needed. I know you can leave that out, but that way I'll get PHP notices when error reporting is set to 'E_ALL'.
I can create a function to make it shorter but that way I'll need to create too many functions as I have such code on different places in my scripts, each requiring different information.
Is there any way to make this code shorter?
Thanks!
Since action and id both are probably going to be used might as well set them at the top of the script:
$action = !empty($_GET['action'])?$_GET['action']:false;
$id = !empty($_GET['id'])?$_GET['id']:false;
switch ($action) {
case 'edit':
if ($id !== false) {
//processing here
}
break;
default:
echo 'No known action was passed through';
}
The initial variable declaration uses the ternary operator which is a shortened if/else as an fyi.
Extra Information
I prefer this method as appose to insane if/elseif/else statements, given that it is much easier to read and you do not have to think about your logic nearly as much, so it would make it less prone to errors.
You could write a function that takes an array of keys:
function check_get_params($keys) {
foreach ($keys as $key) {
if (! isset($_GET[$key]) ) {
return false;
}
}
return true;
}
Then your line above would be:
} elseif (check_get_params(array('action', 'id')) && $_GET['action'] == 'edit' && is_numeric($_GET['id'])) {
which would be cleaner as:
} elseif (check_get_params(array('action', 'id'))) {
if ($_GET['action'] == 'edit' && is_numeric($_GET['id'])) {
I would check parameters first:
$action = (isset($_GET['action']) && !empty($_GET['action'])) ? $_GET['action'] : false;
$id = (isset($_GET['id']) && !empty($_GET['id'])) ? $_GET['id'] : false;
settype($id, 'int'); // "123" became 123(int)
And then go with:
} elseif ($action && $id && $action == 'edit' && $id > 0) {
// here we are
}

What would you change in my code for best practices/maintenance?

I've got a small snippet of code below and I was curious what types of things you would change with regards to best practices/code maintainablity and so on.
function _setAccountStatus($Username, $AccountStatus)
{
if ($Username == '' || ($AccountStatus != 'Active' || $AccountStatus != 'Banned' || $AccountStatus != 'Suspended')) {
// TODO: throw error here.
}
$c1 = new Criteria();
$c1->add(UsersPeer::USERNAME,$Username);
$rs = UsersPeer::doSelect($c1);
if (count($rs) > 0) {
$UserRow = array_pop($rs);
$UserRow->setAccountStatus($AccountStatus);
try {
$UserRow->save();
} catch ( PropelException $e ) {
return false;
}
return true;
}
return false;
}
I would use the empty() instead of $Username == '' in your if statement. I haven't used propel before, but I would prefer to have this method be on my User object itself with the fetching and saving of the user object performed by a seperate object. Pseudo code would be something like this.
$user = userManager->getUser($username);
$user->setAccountStatus($accountStatus);
$userManager->saveUser($user);
An else clause before the last return false would be prefererred, just to make the code more readable.

Categories