0

my problem is that the session variable did not get unset when running the below code. what is wrong?

<?php  
 session_start();
 session_unset();
 //session_destroy();
 header("location: user_form.php");
?> 

4 Answers 4

3

You've not actually created a session you've started the session engine but not created a session variable. If you have a session variable $_SESSION['userid'] for example then you can just unset that value or expire it or set its value to something that would fail your if clause for your header redirect.

Sign up to request clarification or add additional context in comments.

4 Comments

If he is asking how to remove the $_SESSION variables, probably (I presume) that he already have them started from another page.
you would assume so but since he's not unsetting or destroying the specific variables created its no surprise its not unsetting them.
Ahh, I've misunderstood what you mean, sorry :) That's why I've suggested something like a foreach to unset the vars.
Your method is greate if you want to unset all potential sessions but if he's looking to unset one specific session or is using sessions as a method of login security etc its not so good.
3

Usually I do something like:

<?php  
 session_start();

 if(!empty($_SESSION) && is_array($_SESSION)) {
     foreach($_SESSION as $sessionKey => $sessionValue)
         session_unset($_SESSION[$sessionKey]);
 }

 session_destroy();

 header("Location: user_form.php");
?> 

1 Comment

Edited, thanks @user1615903. Corrected the key in the array when unsetting.
1

Try this syntax (use a variable name in unset):

 <?php
    session_start();
    if(isset($_SESSION['views']))
      unset($_SESSION['views']);
    ?>

Comments

0

I'm guessing you already have variables within your session set, otherwise there would be nothing to "unset".

With session_unset the session itself would still exist, as it's just the equivalent of doing:

$_SESSION = array();

Unless of course you're using PHP 4.0.6 or below, then you would be expected to use:

unset ($_SESSION['varname']);

as per session_unset.

There isn't anything "wrong" with your code so to speak.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.