Reputation: 1714
I've been attempting to figure this out for a little while now, and it's driving me nuts. Basically I have a form for US and Canadian users. There's a link at the bottom of the form 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's another option, and if they click that link, it takes them back to this page, and the session should be destroyed and a new value is set (well, that's what it's supposed to do). Problem is, I've printed out $_SESSION['can'], and it's still retaining that old value after going to that page. Is there a better way to do this, or is there something wrong w/ my code? Thanks for the help.
Upvotes: 5
Views: 49995
Reputation: 5
You may want to include
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
instead of just plain
session_start();
Upvotes: 0
Reputation: 146360
Try this: (using only one session_start()
)
<?php
session_start();
if (isset($_SESSION['can'])) {
$_SESSION['can'] = 2;
}
else {
$_SESSION['can'] = 1;
}
header('Location: '. $_SERVER['HTTP_REFERER'] . '');
?>
Upvotes: 2
Reputation: 52372
This is what you wrote:
if (isset($_SESSION['can'])) {
session_start();
session_start
is the function which reads the session file associated with the user's PHPSESSID
cookie and populates $_SESSION
, so you're 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 just to change a value.
<?php
session_start();
if (isset($_SESSION['can'])) {
$_SESSION['can'] = 2;
} else {
$_SESSION['can'] = 1;
}
header('Location: '. $_SERVER['HTTP_REFERER'] . '');
?>
Upvotes: 11