-2

session is not working in my code. i have a login form, and when a user is on db the the page redirects him in main.php but it's not working

//index.php
<?php
session_start();
include('connect.php');

if(isset($_POST['submit'])){

    $username = mysqli_real_escape_string($dbCon, $_POST['username']);
    $password = mysqli_real_escape_string($dbCon, $_POST['password']);

    $sql = "select username, password from users where username='$username'";
    $res = mysqli_query($dbCon, $sql);
    if(!$res){
        die(mysqli_errno);
    }

    while ($row = mysqli_fetch_assoc($res)){
        $usr  = $row['username'];
        $pass = $row['password'];
    }

    if($username == $usr && $password == $pass){
        $_SESSION["username"] = $username;
        header("Location: main.php");
        exit();
    } else {
        $error = "Invalid username or password";
    }

}
?>

and here is my main.php

//main.php
<?php

if(isset($_SESSION["username"])) {
    $username = $_SESSION["username"];
} else {
    header('Location: index.php');
    die();
}

?>

thanks

Rafael
  • 9
  • 8

3 Answers3

0

Your code is wrong in many aspects. First it breaks the very first rule from SOLID. Single responsibility one. You can't use the same class to load records from database and login a given user. You have to use repositories to handle almost anything that comes from database, and what modern php apps do is they use an ORM which deals with your models and database.

The second problem is with your query. You are testing if the given data are valid which are coming from request by checking if the given username exists. This is wrong in many ways and I'm not getting into details. To login a user you should match it's password as well and that password should be hashed.

But even if the query was right, you are looping through every record that comes from database while storing these data in 2 variables of a higher scope and this way you're checking against data from the last user which the username match.

And last but not least, you're not calling session_start(); for sure in your included scripts.

Make your code PSR-04 compatible so you can use composer to load your dependencies.

Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
0

Use session_start(); in the top of main.php for solving your problem.

Prashant
  • 394
  • 1
  • 6
  • 18
0

This is done in following ways,

1.Set session value after session_start()

2.Use header function to redirect

if($username == $usr && $password == $pass){
    session_start();
    $_SESSION["username"] = $username;
  header('location: main.php'); 

    exit();
} else {
    $error = "Invalid username or password";
}
amisha
  • 366
  • 1
  • 4
  • 15