tags:

views:

367

answers:

5

I am using the following code to invalidate the session. I have linked to logout.php in many pages. If that logout link is clicked the logout.php page is called. The following is the code in logout.php.

unset($_SESSION['admin']);
session_destroy();
header('Location: index.php');

Once the session is invalidated I want to open the page index.php. But I am geting the following error:

Warning: session_destroy() [function.session-destroy]: Trying to destroy uninitialized session in C:\xampp\htdocs\Selection\logout.php on line 3

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\Selection\logout.php:3) in C:\xampp\htdocs\Selection\logout.php on line 4

What is wrong?

+5  A: 

I think that you don't have called the session_start() function before destroy the session.

mck89
Why ever downvoted, he's right.
BeowulfOF
Thanks...anyway the session_start() must be called at the begin of the script.
mck89
+4  A: 

You`ll need to call session_start() on top of the page to remind php that this pagecall belongs to the session. - At least PHP manual tells that.

The notes on that manual page give hint, that session_unset() is only to be used in older environments that are not using $_SESSION variable.

BeowulfOF
well it's a good thing that he's not using `session_unset()` then...
nickf
@nickf: correct, did not recognize correctly
BeowulfOF
+1  A: 

You have to open the session first:

header('Location: index.php');
session_start();
session_unset();
session_destroy();
rodrigoap
I think that the redirection must be placed at the end, because writing the code like this the script does the redirection and doesn't execute the other functions
mck89
No, it works as expected.
rodrigoap
It only works as expected because the script still finishes execution after the header is sent. However you should place the header after the session is destroyed to lessen the confusion of the code.
MitMaro
A: 

The problem is that you can't destroy a session which hasn't been started. That is then raising a warning which is being echoed to the browser. The next problem is that you can't send headers after there's been output to the browser, so it raises another warning.

You just need to check if a session exists first:

if (session_name() != '') {
    session_destroy();
}
nickf
A: 

You must ALWAYS use session_start(); BEFORE using a session function/variable. So start all PHP files with session_start();. Also logout.php:

session_start();
session_destroy();
header('Location: index.php');

You also don't need to unset it.

Time Machine