'$_SESSION variable is lost after redirecting using header function

In order to redirect from page 1 to page 2 I've used the header function so : I have two files : page1.php :

<?php
require_once('model/Manager.php');

function login() {
    $user = getUser($_REQUEST['login']);
    if(!empty($user)) {
        if($_REQUEST['login'] == $user['login'] && $_REQUEST['password'] == $user['password']) {
            $_SESSION['nom'] = $user['login'];
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['articles'] = getArticles($user['id']);
            if($user['role'] == 1) {
                header('location: view/Administration.php');
                //require('view/Administration.php');
            }
            else
            require('../view/accueil.php');
        }
        else
            echo 'Erreur Connexion';
}
echo 'Merci de vérifier vos données';
}

And Manager.php :

<?php
function dbConnect()
{
    try
    {
        $db = new PDO('mysql:host=localhost;dbname=mini_projet;charset=utf8', 'root', '');
        return $db;
    }
    catch(Exception $e)
    {
        die('Erreur : '.$e->getMessage());
    }
}

function getUser($login) {
    $db = dbConnect();
    $req = $db->prepare('SELECT * FROM utilisateur WHERE login = ?');
    $req->execute(array($_REQUEST['login']));

    $user = $req->fetch();
    
    return $user;
}

Router.php

<?php
require_once('controller/usercontroller.php');
if (isset($_REQUEST['login']) && isset($_REQUEST['password'])) {
    session_start();
    login();

}

Page2.php

<?= session_start(); ?>
<html lang="en">
<head>
    <title>Administration</title>
    <script>
        function validateForm() {
            let x = document.forms["myForm"]["marque"].value;
            if (x == "") {
            document.getElementById("marque_validation").innerHTML = "Merci de remplir ce champ";
            return false;        
  }
} 
    </script>
</head>
<body>
   Bienvenue admin : <?php echo $_SESSION['nom'] ?> 
</body>
</html>

When trying to redirect to page 2 using the header function as mentionned in the code, it show me the error : Notice: Undefined index: logged_user in C:\xampp1\htdocs..

it turns out that the session value is lost, please I need help. PS: I read the other questions related to my problem in stackoverflow but there's no solution.



Solution 1:[1]

You also need to call session_start() at the beginning of page1.php.

try:

<?php  # page1.php
session_start();
$_SESSION['logged_user'] = 'joe';
header('location: page2.php');

and

<?php  # page2.php
session_start();

echo $_SESSION['logged_user'];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1