开发者

Only setting PHP session variable when it's updated

开发者 https://www.devze.com 2023-03-26 16:49 出处:网络
I have a fairly straightforward set of php forms that take users through a 3 step process before doing a final submit of their information.

I have a fairly straightforward set of php forms that take users through a 3 step process before doing a final submit of their information.

I'm using session variables to retain the data across each page and also pull in each session variable to fields that may have already been submit so that the forms are 'sticky'.

The problem is that once they get to the 3rd part of the form, if they go backwards using the link provided, it errors because there has not actually been a POST of the data from the 1st section so there is nothing to set for the session variables.

To counter this i added the following piece of code for all my variables:

    if(!isset($_SESSION['home_tel'])){
        session_register('home_tel');
        $_SESSION['home_tel'] = $_POST['home_tel'];                         
    }

this worked fine until I realised that this means if a user goes back to the first page, it will not update the session to the latest data as its already set so thinks it doesn't have to do anything.

Is there an easy way to check the sess开发者_如何学运维ion values to see if they have changed before updating the session variable? Alternatively is there just a way to check if its been posted or not and if so then created the variable. I tried if(isset($_POST['home_tel'])).... etc but that doesn't seem to work.

Any help would be great??

Many thanks, Jonny


if(isset($_POST['home_tel']) && ($_POST['home_tel'] != $_SESSION['home_tel'])){
    $_SESSION['home_tel'] = $_POST['home_tel'];
}

This will set $_SESSION['home_tel'] if a post submission has been made and if the new value is different than the old value.


You do not want to use session_register anymore:

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

http://www.php.net/session_register


First off, as you've discovered, storing transaction data in the session is a bad idea. You've already come across problems with the back button, soon you're going to find problems when the user opens a second window on the same session.

Is there an easy way to check the session values to see if they have changed before updating the session variable?

Why? There is no overhead in overwriting a session variable - indeed, the code has to write the session each time to stop it expiring. If you must use session variables just use unique names for your fields, and prepopulate the session accordingly....

$reserved_values=array('email','authenicated_user');
foreach ($_POST as $name=>$val) {
  if (!in_array($name, $reserved_values) 
      && array_key_exists($name, $_SESSION)) {
      $_SESSION[$name]=$val;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消