简体   繁体   中英

How to use session variables in different pages, when the “session_start()” function is already being used?

I have a problem trying to display some session variables in a different page in php. Most of the threads I've seen here are related to the lack of "session_start()". But I already have it at the top of my files.

I'm trying to create a "recover your password module". I have a form element wich has an action set to antoher page. I have a database with two tables. The form just allows the user to input his e-mail. When I click the sumbit button, a mysqli connection is supposed to look in both tables for the user with the e-mail stored in the form and then store the rest of the elements (name, password, recovery question and its answer) of the table in some php variables.

In an if contidional statement I check which table the e-mail is stored in and then create some session variables that store the whole information of said user.

In the other page I'm just trying to echo some text along with the session variable of the name of the user if that variable session is set. If not it will echo a "failed session" text.

Here is the form (the file where this thing is has the session_start() already in top):

<form action="cambio.php" method="post">
     <h1>RECUPERACIÓN DE CONTRASEÑA</h1><br>
     <p>Escriba su dirección de correo para modificar su contraseña:</p><br>
     <div class="form group">
        <label for="email">Correo electrónico:</label>
        <input type="email" class="form-control ancho" id="email" name="email" class="ancho"><br>
      </div>
      <button type="submit" class="btn btn-primary" name="recuperar">Recuperar contraseña</button>                
</form>

After connecting to the database, this is where I'm setting the session variables (in the same .php as the previous form code):

 if(isset($_POST['recuperar'])) {
                    $c = $_POST["email"];
                    $buscarAlumno="select nombre, correo, password, num_pregunta, respuesta from alumno where correo='$c';"; //first table
                    $buscarProfesor="select nombre, correo, password num_pregunta, respuesta from profesor where correo='$c';"; //second table
                    $resA = $conn->query($buscarAlumno);
                    $resP = $conn->query($buscarProfesor);
                    $rowA = $resA->fetch_array();
                    $rowP = $resP->fetch_array();

                    //Save the e-mail-matching fields (first table)
                    $rnA = $rowA["nombre"];
                    $rcA = $rowA["correo"];
                    $rpA = $rowA["password"];
                    $rnpA = $rowA["pregunta"];
                    $rrA = $rowA["respuesta"];
                    //Save the e-mail-matching fields (second table)
                    $rnP = $rowP["nombre"];
                    $rcP = $rowP["correo"];
                    $rpP = $rowP["password"];
                    $rnpP = $rowP["num_pregunta"];
                    $rrP = $rowP["respuesta"];

                    //In this statement, some of the variables above are going
                    //to be stored in session variables depending on the 
                    //table in which the e-mail was found
                    if (isset($c)) {
                        if ($c == $rcP) { 
                            $_SESSION['nomCorrecto'] = $rnP;
                            $_SESSION['corCorrecto'] = $rcP;
                            $_SESSION['pasCorrecto'] = $rpP;
                            $_SESSION['preCorrecto'] = $rnpP;
                            $_SESSION['resCorrecto'] = $rrP;
                        }                
                        elseif ($c == $rcA) {
                            $_SESSION['nomCorrecto'] = $rnA;
                            $_SESSION['corCorrecto'] = $rcA;
                            $_SESSION['pasCorrecto'] = $rpA;
                            $_SESSION['preCorrecto'] = $rnpA;
                            $_SESSION['resCorrecto'] = $rrA;
                        }
                        else {
                            echo "Usuario no registrado.";
                        }
                    }
                }

This code is in another page, where I want the results to be show (again, it already has the session_start() on top of the file).

        <?php            
            //This part should show the name of the user, but is not working
            if(isset($_SESSION['nomCorrecto'])) {
                echo "Hola " .$_SESSION['nomCorrecto']. ".";            
            }
            else {
                echo "Sesión fallida.";
            }
        ?>  

I don't know what I'm doing wrong, I don't know if the error is about the form statement or how I'm saving and echoing the session variables. I just get the "Sesión fallida" error text.

Any help is welcome.

Thanks in advance.

Ensure that you've initialize session_start(); before any sessions are being called.

For example, you can add something like this to the beginning of each page where session is used: if (session_status() == PHP_SESSION_NONE) session_start(); This will check whether the session is started or not, and if not it will start it.

You can also use var_dump($_SESSION); at every places where you use sessions in order to track / examine the session data.

Note : The common reason why your code is not working is if you failed to initialize session_start(); in places necessary. Failure to carry out some necessary checks on your code can also cause this. You can find more detail about session loss in the answer of this question .

Finally figured it out. I need to declare the session variables that I'm going to use right after the session_star() function.

Thanks for the help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM