views:

1259

answers:

3

Hey all,

There's got to be a much more elegant way of doing this.

How do I convert all non-empty post data to session variables, without specifying each one line by line? Basically, I want to perform the function below for all instances of X that exist in the POST array.

if (!empty($_POST['X'])) $_SESSION['X']=$_POST['X'];

I was going to do it one by one, but then I figured there must be a much more elegant solution

+6  A: 

I would specify a dictionary of POST names that are acceptable.

$accepted = array('foo', 'bar', 'baz');

foreach ( $_POST as $foo=>$bar ) {
    if ( in_array( $foo, $accepted ) && !empty($bar) ) {
        $_SESSION[$foo] = $bar;
    }
}

Or something to that effect. I would not use empty because it treats 0 as empty.

meder
I am fine with 0 being treated as empty, in fact it would help to clean up my data. Thanks!
RC
modified to fit your needs then.
meder
To be honest, you should avoid using empty() at all - kick the habit now, and you'll develop techniques that will work in EVERY situation, not just this one. There are appropriate functions for every data type. Use them!
iddqd
A: 

Well the first thing I would suggest is you don't do this. It's a huge potential security hole. Let's say you rely on a session variable of username and/or usertype (very common). Someone can just post over those details. You should be taking a white list approach by only copying approved values from $_POST to $_SESSION ie:

$vars = array('name', 'age', 'location');
foreach ($vars as $v) {
  if (isset($_POST[$v]) {
    $_SESSION[$v] = $_POST[$v];
  }
}

How you define "empty" determines what kind of check you do. The above code uses isset(). You could also do if ($_POST[$v]) ... if you don't want to write empty strings or the number 0.

cletus
Yes, thanks for the pointer. So I would have to, in effect, do it one by one, but I can whitelist it in an array to keep the code tidy.How do I implement a "not empty()" check into your code above, to ensure that only not-empty POST data get converted to session variables, even if it's in the whitelist? I am fine with "0" being registered as empty.
RC
A: 

Here you go,

if(isset($_POST) {
 foreach ($_POST as $key => $val) {
  if($val != "Submit")
   $_SESSION["$key"] = $val;
 }
}
lemon