Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Shivamyadav's avatar

session error?

why i am unable to get the session msg to the page.. login msg is accessable to the page through the session but at the time of destroy it doesn;t work for me ? my code for logout

session_start();
if(session_destroy()){
    $_SESSION['msg'] = "Logout successfull.";
    header("location: index.php");
}
0 likes
19 replies
jlrdw's avatar

Why aren't you using laravel built in Auth, and session helpers.

tykus's avatar

You're trying to set Session variables after destroying the Session??? What are you actually trying to achieve?

Shivamyadav's avatar

@tykus i am trying to do when a user logged out then it show a feedback msg that he has been logged out and redirected to the given page.. with the $_SESSION global variable..

tykus's avatar

@Shivamyadav yeah... but you destroyed the session, and you cannot use it without it being restarted.

Yorki's avatar

@Shivamyadav assuming you have controller with logout method:

public function logout (Request $request)
{
  Auth::logout();
  session()->push('msg', 'Logout successfull.');

  return redirect()->to('/');
}
tykus's avatar
tykus
Best Answer
Level 104

@Shivamyadav you restart the Session with a new start_session(). You probably want session_unset() before destroying to clear existing variables, e.g.

session_start();
if(session_unset() && session_destroy()){
	session_start();
    $_SESSION['msg'] = "Logout successfull.";
    header("location: index.php");
}

To be honest, it is more than a decade since I wrote PHP like this, so you'll want to check the docs to confirm.

1 like
Yorki's avatar

Ohh I see.. then how you handle the logged in user in session? Like you could just forget user_id or whatever field you use for logged in user ;)

frankhosaka's avatar

try

<?php
session_start();
if(session_destroy()){
        echo "Logout successfull";}
echo "<p><input type=submit onclick=location.replace('index.php')>";
Shivamyadav's avatar

@frankhosaka but i want to just show a info to the user that he is logged out and redirected to the given specific page . and by your code it take me the page index.php after i click on the page and echo loggeout msg is also looking wiered to a user

sididev's avatar

There are a few reasons why this might not be working as expected...

<?php
session_start();
if(session_status() == PHP_SESSION_ACTIVE){
    $_SESSION['msg'] = "Logout successful.";
    session_destroy();
    header("location: index.php");
    exit();
}
Yorki's avatar

Try this one:

session_start();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION['msg'] = "Logout successfull.";
header("location: index.php");
1 like

Please or to participate in this conversation.