Home > Mobile >  PHP Session variable not updating After Form Submit
PHP Session variable not updating After Form Submit

Time:05-02

I have two files, one that contains the form and one that contains the action, and the action sends the user back to the form if the fields are blank. I know I can use the 'required' to make it have to be entered before the action is taken; however, I'm supposed to be doing it this way, where we check if they entered a username. if not display an error message stored as $_SESSION['error'].

No checking the SQL database yet, I have that part handled.

Here's my form (login.php):

<?php   
session_start();
?>

<div id="login-form-wrap">
  <h2>Login</h2>
  <form id="login-form" method="post" action="action.php">
    <p>
    <input type="text" id="username" name="username" placeholder="Username">
    </p>
    <p>
    <input type="password" id="password" name="password" placeholder="Password">
    </p>
    <p>
    <input type="submit" id="login" name="login" value="Login">
    </p>
  </form>
  <div id="create-account-wrap">
    <p>Not a member? <a href="create.php">Create Account</a><p>
  </div>
  <?php
    if(isset($_SESSION['error'])) { 
        echo $_SESSION['error']; 
    } else{ 
        echo "No errors."; 
    } 
  ?>
</div>

And here's my action.php:

<?php 
if (isset($_POST['login'])){ 
// checking if they hit the submit/login button

    if(empty($_POST['username'])){
        $_SESSION['error'] = "Please enter a username."; 
        //should change the session variable error, but doesn't;
        
        header("location:../login.php");
        //redirects to login.php, this part works fine.

    } else {
    // means they entered a username, I have tried to change the session variable here too 
    // but it never changes.
        $name = $_POST['username'];
        header("location:../login.php");
    }
}

CodePudding user response:

does your action.php same like above because you haven't started session. Use session first.

session_start();

CodePudding user response:

In your action.php file you did not start the session. In order to access session values in PHP, you have to use the session_start(); function first.

CodePudding user response:

you have to destroy session value after form submission

use this code after form submit in your else part where you want to clear session value and also you have to start session in action.php file before using session variable

    // destroy the session
    session_destroy(); 
  • Related