-2

I do know that this has been posted many times before but I'm still having issues.

When I'm logging on to my website I want a session to start. When I start the session I get this error.

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home1/gretar/public_html/login.php:27) in /home1/gretar/public_html/login.php on line 30

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home1/gretar/public_html/login.php:27) in /home1/gretar/public_html/login.php on line 30

So this is how my code looks like

<?php
include('mysql_connect.php');

if($_SERVER['REQUEST_METHOD'] == 'POST') {

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$verified = mysql_real_escape_string($_POST['verified']);


$query = "SELECT * FROM members WHERE username='$username' AND password='$password'";
mysql_query("SELECT verified FROM members WHERE username='$username'");

$sql = mysql_query("SELECT verified FROM members WHERE username='$username'");
while($row = mysql_fetch_array($sql)){

$verified = $row["verified"];   
};
$result = mysql_query($query);
$query_rows = mysql_num_rows($result);


if($query_rows > 0) {
    if($verified == 1) {
    echo("User Verified");
    } else if($verified == 0) {
    echo("User not verified");
    }
        echo ("Succesfull login!");
session_start();
$_SESSION['login'] = "1";

    }else{
echo("Bad login!");
    }
}
?>
<html>
    <head> 
    <title>Login</title>
    </head>
        <body>
        <form action="login.php" method="post"/>
        Username: <input type="text" name="username"/><br>
        Password <input type="password" name="password"/> <br>
        <input type ="submit" value="Login!"/>

        </body>
</html>

This answer really helped me.

Community
  • 1
  • 1
IamGretar
  • 173
  • 2
  • 13

2 Answers2

1

The problem lies in this part:

echo("User Verified");
} else if($verified == 0) {
echo("User not verified");

You mustn't echo ANYTHING if you want to change the HTTP-Header (what is what you do, when you start a session).

Why don't you call session_start() at the very beginning of the file?

Please also note, that you execute the same mysql_query two times.

Chris
  • 612
  • 7
  • 16
0

Aside from setting the cookies and other headers before the first thing you echo you can also use an output buffer. The output buffer will allow you to buffer your output before printing allowing php to specify the order correctly. In the HTTP protocol the headers come first, then two carriage returns, and then your content.

http://php.net/manual/en/function.ob-start.php/

cogsmos
  • 806
  • 6
  • 11