Need Help - Close Database and Redirect Not Working

Fran_3

New member
On my local network... I'm running Apache, PHP, and MariaDB on a Linux machine.
The following code doesn't work.

I'm trying to close MariaDB, clear Session variables, lose/destroy the Session and... Redirect to another page.

Redirect works if it is the only thing in the code but then how do I get all the other stuff done?

Thanks for any help.

<?php // login check
session_start();
if (!$_SESSION['loggedin']){
header('Location: user_signin.php'); // if not loggedin goto signin page
exit;
}
?>
<?php
mysqli_close($con); // close MariaDB
session_start();
$_SESSION = array(); // Clear Session Variables
session_destroy(); // destroy the Session
header("location: index.php"); // rediredt to welcome page
exit;
?>
 
The problem is that I don't see that you are saving anything in the logged in session.
supposedly this: $_SESSION['loggedin'] must contain something stored so that when closing the session it knows which session to close
 
On my local network... I'm running Apache, PHP, and MariaDB on a Linux machine.
The following code doesn't work.

I'm trying to close MariaDB, clear Session variables, lose/destroy the Session and... Redirect to another page.

Redirect works if it is the only thing in the code but then how do I get all the other stuff done?

Thanks for any help.

<?php // login check
session_start();
if (!$_SESSION['loggedin']){
header('Location: user_signin.php'); // if not loggedin goto signin page
exit;
}
?>
<?php
mysqli_close($con); // close MariaDB
session_start();
$_SESSION = array(); // Clear Session Variables
session_destroy(); // destroy the Session
header("location: index.php"); // rediredt to welcome page
exit;
?>
There is no need to close the connection. PHP does this automatically.
The code contains a logical flaw that can lead to unexpected behavior during session management. Specifically, the session is started twice, and the session destruction logic is placed in a context that may not be executed as intended.
Try this:
PHP:
<?php
session_start(); // Start the session. Only required once

// Login check
if (!isset($_SESSION['loggedin']) || !$_SESSION['loggedin']) {
    header('Location: user_signin.php'); // If not logged in, go to signin page
    exit;
}

// Logout logic
if (isset($_GET['logout'])) { // Check if logout is requested
    $_SESSION = array(); // Clear Session Variables
    session_destroy(); // Destroy the Session
    header("Location: index.php"); // Redirect to welcome page
    exit;
}
?>
 
Back
Top