Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Convert all POST data into SESSION variables

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

like image 394
RC. Avatar asked Oct 18 '09 06:10

RC.


4 Answers

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.

like image 125
meder omuraliev Avatar answered Oct 28 '22 16:10

meder omuraliev


The syntax error, is just because there is a bracket still open. it should be

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

It should work like that. If you use

if ($_POST[$v])...

it strips down empty data.

like image 42
Vali Avatar answered Oct 28 '22 15:10

Vali


Here you go,

if(isset($_POST) {
 foreach ($_POST as $key => $val) {
  if($val != "Submit")
   $_SESSION["$key"] = $val;
 }
}
like image 2
lemon Avatar answered Oct 28 '22 16:10

lemon


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.

like image 1
cletus Avatar answered Oct 28 '22 16:10

cletus