Changing the value of the SESSION variable

I’ve been trying to figure this out for a while, and it makes me go crazy. Mostly I have a form for American and Canadian users. At the bottom of the form there is a link for Canadian users, which directs users to can-sesssion.php, which contains:

<?php if (isset($_SESSION['can'])) { session_start(); session_destroy(); session_unset(); session_start(); $_SESSION['can'] = 2; } else { session_start(); $_SESSION['can'] = 1; } header('Location: '. $_SERVER['HTTP_REFERER'] . ''); ?> 

Basically, if they click on the link, it sets $ _SESSION ['can'] = 1. Now there is one more option, and if they click on this link, it will return them to this page, and the session should be destroyed and a new one should be established. value (well, what should he do). The problem is that I printed $ _SESSION ['can'] and still retains this old value after going to this page. Is there a better way to do this, or is there something wrong with my code? Thanks for the help.

+4
source share
2 answers

Here is what you wrote:

 if (isset($_SESSION['can'])) { session_start(); 

session_start is a function that reads the session file associated with the PHPSESSID cookie user and populates $_SESSION , so you are trying to read from the array before it has any values.

You need to call session_start before you check if $_SESSION['can'] has a value.

You also do not need to destroy and create a new session to change the value.

 <?php session_start(); if (isset($_SESSION['can'])) { $_SESSION['can'] = 2; } else { $_SESSION['can'] = 1; } header('Location: '. $_SERVER['HTTP_REFERER'] . ''); ?> 
+8
source

Try the following: (using only one session_start() )

 <?php session_start(); if (isset($_SESSION['can'])) { $_SESSION['can'] = 2; } else { $_SESSION['can'] = 1; } header('Location: '. $_SERVER['HTTP_REFERER'] . ''); ?> 
+1
source

All Articles