-2

Possible Duplicate:
Headers already sent by PHP

I am trying to make a login script. This is what I have so far, but it returns this when I try to login with a valid User:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/user/public_html/dir/login.php:3) in /home/user/public_html/dir/login.php on line 6

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/user/public_html/dir/login.php:3) in /home/user/public_html/dir/login.php on line 6

Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/dir/login.php:3) in /home/user/public_html/dir/login.php on line 31

Here is my code:

<?php
if(isset($_POST['login'])){
ob_start();
session_start();
$host="xxx";
$username_db="xxx"; 
$password_db="xxx";
$db_name="xxx";  
$tbl_name="xxx"; 

mysql_connect("$host", "$username_db", "$password_db")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$email=$_POST['email']; 
$password=$_POST['password']; 

$email = stripslashes($email);
$password = stripslashes($password);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$email' and password='$password'";
$result=mysql_query($sql);

$count=mysql_num_rows($result);

if($count==1){
$_SESSION['username'] = $email;
$_SESSION['password'] = $password;
header("location:main.php");
}
else {
echo"<br><center><div class=\"alert alert-error\">
Wrong email or password!</div></center>";

}
ob_end_flush();
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Login</title>
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
    <style type="text/css">
      html, body {
        background-color: #eee;


      }
      body {
        padding-top: 40px; 
      }
      .container {
        width: 300px;
      }

      .container > .content {
        background-color: #fff;
        padding: 20px;
        margin: 0 -20px; 
        -webkit-border-radius: 10px 10px 10px 10px;
           -moz-border-radius: 10px 10px 10px 10px;
                border-radius: 10px 10px 10px 10px;
        -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);
           -moz-box-shadow: 0 1px 2px rgba(0,0,0,.15);
                box-shadow: 0 1px 2px rgba(0,0,0,.15);
      }

      .login-form {
        margin-left: 65px;
      }

      legend {
        margin-right: -50px;
        font-weight: bold;
        color: #404040;
      }

    </style>

</head>
<body>


    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="#">hi</a>
          <div class="nav-collapse collapse">
            <ul class="nav">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="register.php">Register</a></li>
              <li><a href="contact.php">Contact</a></li>
            </ul>

          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>

    <div class="container">
        <div class="content">
            <div class="row">
                <div class="login-form">
                    <h2>Login</h2>
                    <form method="post" action="">
                        <fieldset>
                            <div class="clearfix">
                                <input name="email" type="text" placeholder="Email">
                            </div>
                            <div class="clearfix">
                                <input name="password" type="password" placeholder="Password">
                            </div>
<button name="login" class="btn btn-primary" type="submit">Sign in</button><br>

                        </fieldset>
                    </form>
                </div>
            </div>
        </div>
    </div> <!-- /container -->
</body>
</html>
Community
  • 1
  • 1
CJ Sculti
  • 759
  • 3
  • 12
  • 21
  • 1
    put **all** html after the call to `header()` Abd by the way `session_register()` is deprecated and the mysql function set has been superceded by mysqli and pdo. – dnagirl Oct 25 '12 at 18:32
  • sidenote: [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained and the [deprecation process](http://j.mp/Rj2iVR) has begun on it. See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – Nick Fury Oct 25 '12 at 18:48

2 Answers2

0

I see you are using ob_start() with no arguments, so you understand that you can use it to prevent headers being sent early. However you seem to have missed the point a bit: It must be called before ANY page content is sent. In this case, it should be BEFORE the <!DOCTYPE.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

You need to do all you session handling before you start outputting HTML to the browser. Basically, you just need to move all your PHP to the beginning of the code and then handle the login success/failure messaging conditionally within your HTML output content.

You should probably get in the habit of doing most of your code logic up front in your script and then only having minimal amount of PHP within the area of your script where you output the content.

Eventually, as you become more experienced, you will probably also begin to want to separate out your script logic from your output entirely (i.e. place in different files altogether). Over time, most find this approach (i.e. separation of application logic and display logic) leads to code that is much easier to maintain.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • I just moved all my php to the beginning of the code, and I still get the same error, I don't understand what you mean by "handle the login success/failure conditionally within your HTML output content." – CJ Sculti Oct 25 '12 at 18:41
  • You shouldn't be getting the exact same error messages if you moved all the PHP content to the beginning, as the errors related to output having started should have gone away. Basically you shouldn't be using session_register anyway. Just make a call to `session_start()` at the very beginning of your script, then set values in session like `$_SESSION['username'] = $username`. Make sure this is all done before you send any headers or output to the browser. – Mike Brant Oct 25 '12 at 18:49
  • I updated the question with my new code. It still gets the same errors. – CJ Sculti Oct 25 '12 at 19:03
  • Can you update the new error messages(as the ones shown are still the old ones). – Mike Brant Oct 25 '12 at 19:08
  • You also don't need your output buffer anymore. – Mike Brant Oct 25 '12 at 19:09
  • What is at this line of code - `/home/user/public_html/dir/login.php:3`? This is where some output has started. My guess is you have whitespace before your opening ` – Mike Brant Oct 25 '12 at 19:21
  • I may have whitespace before opening tag. The whole file is named login.php – CJ Sculti Oct 25 '12 at 19:49