Domanda

I am creating a simple login system and am encountering that everytime I try to login the session fails to set and returns my error to me.

The code is posted below.

  • Form:

    <form action="login_system.php" method="post">
    Username<br>
    <input type="text" name="username"><br>
    Password<br>
    <input type="password" name="password"><br>
    <input type="submit" name="submit" value="login">
    </form>
    
  • login_system.php:

    error_reporting(E_ALL ^ E_NOTICE);
    
    $user = $_POST['username'];
    $pass = $_POST['password'];
    
    if (isset($_POST['submit']) && $user == 'test' && $pass == 'test') {
        session_start();
        $_SESSION['logged_in'] == 'yes';
        if ($_SESSION['logged_in'] == true) {
            echo '<META HTTP-EQUIV="Refresh" Content="0; URL=main_index.php">'; 
        }
    }
    
  • Page to login to:

    session_start();
    require('login_system.php');
    
    
    if ($_SESSION['logged_in'] == 'true') {
        echo 'ok';  
    } else {
        die ('You do not have permission to view this webpage.');   
    }
    
È stato utile?

Soluzione

the session is being called on the login page. Try removing it and it should fix your issue.

Altri suggerimenti

session_start() must got at the top of each page you use sessions on. In your "Login_system" page it is not. It should look like this:

session_start();
error_reporting(E_ALL ^ E_NOTICE);

$user = $_POST['username'];
$pass = $_POST['password'];

if (isset($_POST['submit']) && $user == 'test' && $pass == 'test') {
    $_SESSION['logged_in'] = 'yes';
    if ($_SESSION['logged_in'] == true) {
        echo '<META HTTP-EQUIV="Refresh" Content="0; URL=main_index.php">'; 
    }
}

Also,

$_SESSION['logged_in'] == 'yes';

should only have one equal sign:

$_SESSION['logged_in'] = 'yes';

Two equal signs are a comparison operator. You want one which is the assignment operator.

You have the following which is a comparison operator. A assignment operator is just =

$_SESSION['logged_in'] == 'yes';
                       ^
if ($_SESSION['logged_in'] == true) {#you can probably remove this line

Which should be

$_SESSION['logged_in'] = 'yes';# or true?

Then you have 'true' which is actually 'yes' or unless you are looking for == true and not string true

if($_SESSION['logged_in'] == 'true') {

Which should be one of the following but make sure you are consistent

if($_SESSION['logged_in'] == 'yes') {

OR

if($_SESSION['logged_in'] == true) {
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top