0

I am trying to create a login form, I created the html form and wrote this PHP code but I keep on getting an error about session_start(); and header already sent

The error:

Warning: session_start(): Cannot send session cookie - headers already sent by

<?php
session_start();
if($_POST['submit'])
{
include_once('my_connection.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);

$sql = "SELECT id,username,password FROM users WHERE username = '$username'  AND password = '$password'";
$query = mysqli_query($connect,$sql);
if($query) {
$row = mysqli_fetch_row($query);
$id = $row[0];
$dbusername = $row[1];
$dbpassword = $row[2];
if($username == $dbusername && $password == $dbpassword)
{
    $_SESSION['username'] = $username;
    $_SESSION['id'] =$id;
    header('Location:home.php');
}else {

    echo "Incorrect username or password.";
} } }?>

I put the session_start() on the top of the code but still don't work

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149

1 Answers1

1

Warning: session_start(): Cannot send session cookie

To start with, always have your start_session() at the top. Yes, adding ob_start() above it may fix it and adding ob_flush() at the bottom could but it looks like it hasn't so:

If you're requiring the same file or another file, ensure the file you're requiring does not have a session_start() function within it. Ensure you have no duplicates of session_start() anywhere else either in the same code.

Also, a big reason actually may be because you're missing syntax in your header() and the program is not finishing/ending, only requiring.

Change it to this:

header('Location: home.php');
exit;

Sources to further help you:

Source 1
Source 2

Community
  • 1
  • 1
Jaquarh
  • 6,493
  • 7
  • 34
  • 86