Search code examples
phpformssessionmulti-page-application

PHP sessions not working on multiple page form when going back to the first page


I don't get the PHP $_SESSION working when I try to echo the result on the first page. The error message states basically that the variables are undefined.

The path i want to use:

  1. 1st page = form 1
  2. 2nd page = form 2
  3. Go back to 1st page = form 1 with all input filled from previous submit + all data from the 2 forms in a text.

Is that possible ?

Page 1 = index.php:

    <?php session_start(); ?>
    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    </head>
    
    <body>   
        <form action="overview.php" id="regForm" method="post">
            
            <div class="tab">
                <h2>1. Your info</h2>
                <p><input type="text" placeholder="Prénom"  name="fname" value="<?php echo htmlspecialchars($_SESSION['name']); ?>"></p>
                <p><input type="text" placeholder="Nom" name="name" value="<?php echo htmlspecialchars($_SESSION['name']); ?>"></p>
                <input type="submit" value="Valider">
            </div>
        </form>
    <?php echo "Your name is :",$_SESSION['name'], "and your first-name is ", $_SESSION['fname'];?>
<?php echo "Your e-mail is :", $_SESSION['email'] ;?>
    </body>
    </html>

Page 2 = overview.php:

<?php session_start(); ?>

<?php

   $_SESSION['fname'] = $_POST['fname'];
   $_SESSION['name'] = $_POST['name'];

?>

<form action="index.php" id="regForm" method="post">   
        <h2>1. Tes informations personnelles</h2>
        <p><input type="text" placeholder="e-mail" name="email"></p>
        <input type="submit" value="Valider">
</form>

Back to Page 1 = index.php:

<?php session_start(); ?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>   
    <form action="overview.php" id="regForm" method="post">
        
        <div class="tab">
            <h2>1. Your info</h2>
            <p><input type="text" placeholder="Prénom"  name="fname" value="<?php echo htmlspecialchars($_SESSION['name']); ?>"></p>
            <p><input type="text" placeholder="Nom" name="name" value="<?php echo htmlspecialchars($_SESSION['name']); ?>"></p>
            <input type="submit" value="Valider">
        </div>
    </form>

<?php echo "Your name is :",$_SESSION['name'], "and your first-name is ", $_SESSION['fname'];?>
<?php echo "Your e-mail is :", $_SESSION['email'] ;?>

</body>
</html>

Do you guys see any issue that prevents the code to run ?


Solution

  • Just found out the "WHY". I basically blocked cookies when I started the project which prevent $_sessions to work properly. So make guys sure that cookies are enabled on your website. The kind of things that waste an hour of work ...