Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a session variable

I am creating a multi-step form with Ajax and would like to change text displayed based on the value of a form field. I thought that a good way to do this would be with a session variable. How do I tell the session to update with the new field value? Currently, the session only seems to store the initial value, but not any updates to it. So if a user enters "John" as the first name and then later goes back and changes it to "Frank," "John" is the name stored.

if (!isset($_SESSION)) {
session_start();
$_SESSION['formStarted'] = true;
$_SESSION['timestamp'] = date("M d Y H:i:s");
$_SESSION[$key] = $value;

<p>Your name begins with the letter <?php if ($_SESSION['name'] =='Frank') 
  {echo 'F';}?><p>

jQuery:

$("#form").validate({
   //...
   submitHandler: function(form) {

   //... 
   $(form).ajaxSubmit({               
     type: "POST",
     data: {
       name : $('#name').val(),
//...
     },
     dataType: 'json',
     url: '../ajaxtest.php',
     error: function() {alert("There was an error processing this page.");},
     success: 
       function(data) {
         $('#output1').html(data.message.join(' ')).show(500);
         $('#ouput1').append(data);
//...

ajaxtest.php:

session_start();

$expected = array( 
'name'=>'string', 
//...
);

//...

$return['message']=array();
if(!empty($_POST['name'])){
   $return['message'][] = '' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
   } 
//...
echo json_encode($return);
like image 684
Ken Avatar asked May 27 '11 23:05

Ken


1 Answers

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'
like image 140
Andrei Todorut Avatar answered Oct 10 '22 01:10

Andrei Todorut