TanguyH TanguyH - 2 months ago 16
PHP Question

PHP : $_SESSION empty after function execution

I started developing a platform mainly in php and sessions worked fine, until I stopped my Apache Server and started working on it a week later.

This is my problem :

index.php

<?php
include_once 'backend/login.php'; // DB connect + functions
include_once 'menu.php'; // menu include
check_logout(); // check if user logged out
?>
<?php
include_once 'widgets/widgets.php'; // widgets : login, agenda, events, languages
include_once 'footer.php'; // footer
?>


So basically these are the php parts of my page (the rest is HTML). backend/login includes login functions (and that file itself includes login to the DB followed by session_start()).

home.php

<?php
include_once 'backend/login.php'; // connect to DB, login functions
include_once 'backend/load_feed.php'; // feed functions
include_once 'menu.php'; // include main menu
?>
<script>
alert("<?php echo $_SESSION['first_name']; ?>");
</script>
<?php
check_login(); // ensure user is logged in
?>


When the login on index.php (form is hidden in widgets/widgets.php) is valid. It changes the window.location to home.php. The problem is that $_SESSION doesn't contain the information stored during the login.

dbconnect.php

<?php
/*
remote script used to conenct to the database
*/
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "DB";

// create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// check connection
if($conn->connect_error){
die("Connection failed : " . $conn->connect_error);
}
session_start();
?>


This is the script used to connect to the database, it functions properly (I am able to verify the validity of the user credentials)

Complementary Info :

- I have verified that all info stored is stored in $_SESSION when logging in. (information is present in the scope of the function).

- All files needing $_SESSION do include (directly or trough other includes) the dbconnect.php file, hence giving access to $_SESSION.

- No output is generated before calling session_start();


Does someone have any idea of what might be the source of my problem ?

Answer
<?php
    session_start();
    include_once 'backend/login.php';
    include_once 'menu.php';
    check_logout();
    include_once 'widgets/widgets.php';
    include_once 'footer.php'
?>

Try This!

I Hope This works & also do one thing, the list of files you have included above please make sure that you haven't called session_start() again in that files also, actually it doesn't matter but still give a try.

Also as you are saying that the function is giving problem, please also post the snapshot of the error so that it would me more helpful to understand the error.