How to update a session variable How to update a session variable ajax ajax

How to update a session variable


You can update the $_SESSION like you update a simple variable. The $_SESSION is a global var and you can access it after session_start() declaration.

It's not required to unset the session when you want to change because you are working at the same memory address.

For example:

index.php

<?php    session_start();   $_SESSION['key'] = 'firstValue';

anotherpage.php

<?php   session_start();   session_regenerate_id() // that's not required   $_SESSION['key'] = 'newValue';

checkpage.php

<?php   session_start();   echo $_SESSIOn['key'];

Navigation

index.php -> anotherpage.php -> checkpage.php // output 'newValue'


If you want to create a persistent session between pages, you need to call session_start at the start of every script that the session should apply to, not just the first one.

The PHP docs for session_start say that the function will cause the session to persist if it already exists.


Thats how $_SESSION should work. Because same variable might be in use at different pages, and under processing and so changing values will be unacceptable.

In your case, you are trying to update $_SESSION['name'] and need to keep all other session values intact. The possible solution is

<?phpsession_start();unset($_SESSION['name']);//remove $_SESSION['name']session_regenerate_id();//Copies all other session variables on to new id$_SESSION["name"] = $newValue;//Create new session variable 'name'.session_write_close();?>