Home > Mobile >  Why my session is not writable and create a loop?
Why my session is not writable and create a loop?

Time:04-23

I want to create a required login to acces index.php and other page but I have this error. My code makes a loop when I publish online on secure .com domain. Can someone help me? Thank you.

index.php

include "server.php";
session_start();
  
  if (isset($_SESSION["log"]) == 0) {
    header('location: login.php');
  }

server.php

if (isset($_POST['login_user'])) {
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);

  
    if (empty($username)) {
        array_push($errors, "Username is required");
    }
    if (empty($password)) {
        array_push($errors, "Password is required");
    }
 if (count($errors) == 0) {
        $query = "SELECT * FROM admin WHERE name='$username' AND pass='$password'";
        $results = mysqli_query($db, $query);
        if (mysqli_num_rows($results) == 1) {
            while ($row = mysqli_fetch_assoc($results)){
                $_SESSION["log"] = $row['name'];
                header('location: index.php');
            }
        } 
      }
   }

CodePudding user response:

Please start a session in server.php.

Because you start a session after server.php, it doesn't work.

You need to add session_start(); at the top of index.php.

And you should not print anything in the buffer before session_start(). Otherwise, it will raise a warning.

  session_start();
  include "server.php";
  
  if (isset($_SESSION["log"]) == 0) {
    header('location: login.php');
  }  

CodePudding user response:

The session is not writable because the header has already been sent in server.php. The order you have to use is:

session_start();
// perform test to make sure user is logged in
// if not send to login page
header('location: login.php');
  •  Tags:  
  • php
  • Related