views:

259

answers:

4

the 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());
    ?>

the process-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;
  }?>

could you help to identify the errors?

+1  A: 

Before redefining the headers with the header() function, you must not send any character to the HTTP body, meaning not begining the body part of the response.

Check any included file hasn't any blanck line of char at the begining or the end, and check there is no echo before the call to header().

This issue always happen when chars are sent before calling header(), always.

Sébastien Ros
+1  A: 

Somewhere before the code you posted you have either a blank line that is sent, or more likely some actual content has been sent. Once PHP has started to send the page content you can no longer update the headers (as they are sent before page content).

acrosman
+5  A: 

I would suggest removing the PHP end tags ( ?> ) from your code files. They are not required by the parser, and any whitespace characters after the ?> will result in output to the browser, and interfere with setcookie() and header() calls. Make sure there is no whitespace at the top of your files as well, before the open <?php tags. My guess is that your db_connect file has whitespace at the end of it.

As an aside, you have a glaring SQL injection vulnerability, since you are putting $_POST variables directly into your query without sanitizing them. You should do this:

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

When dealing with sessions and logins and such, you should use output buffering to prevent header errors. Something like this:

//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();
Levi Hackwith