Help with warning: Unable to change header information - already sent headers (output starts with errors C: \ ##

db_connect file:

<?php
//connects to the database
    $username = "username";
    $password = "password";
    $hostname = "host";
    $database="database";
    $link=mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL".mysql_error());
    mysql_select_db($database, $link) or die("Could not select the database".mysql_error());
    ?>

      

login file:

<?php session_start();
include "DB_connect.php";
  if( !isset($_SESSION) )
  $username=$_POST["UserName"];
  $password=$_POST["Password"];
  $errormessage = "";

  $sql="SELECT * FROM members  where UserName='$username' and Password='$password'";
  $result = mysql_query($sql, $link)  or exit('$sql failed: '.mysql_error()); 
  $num_rows = mysql_num_rows($result);
  if($num_rows==0){header("Location:login.php");} 
  else {
    header("Location:MyPage.php");
    exit;
  }?>

      

Help identify errors?

+2


source to share


4 answers


I would suggest removing PHP end tags ( ?>

) from your code files. They are not required by the parser, and any space characters after ?>

will result in an exit to the browser and interfere with calls to setcookie()

and header()

. <?php

Make sure there are no spaces at the top of your files before open tags . I am assuming your db_connect file has spaces at the end.

As an aside, you have a glaring SQL injection vulnerability as you put variables $_POST

directly into your query without sanitizing them. You have to do this:



$sql="SELECT * FROM members  where UserName='".
    mysql_real_escape_string($username)."' and
    Password='".mysql_real_escape_string($password)."'";

      

+6


source


Before overriding headers with the header () function, you must not send any character in the HTTP body, which means not starting the main body of the response.

Check that there is no blanck line of char at the beginning or end in any included file, and check for echoes before calling header ().



This problem always occurs when characters are sent before calling header (), always.

+1


source


Somewhere before the code you posted, you have either an empty string that is being sent, or most likely some actual content is being sent. Once PHP has started sending the page content, you can no longer update the headers (since they are sent before the page content).

+1


source


When working with sessions and logins, etc. you should use output buffering to prevent header errors. Something like that:

//Start the output buffer so we don't create any errors with headers
ob_start();

//Check to see if it has been started
if(session_started()){
    echo 'The session has been started.<br />';
}else{
    echo 'The session has not been started.<br />';
}

//Start the session
echo 'Starting Session...<br />';
session_start();

      

+1


source







All Articles