-1

Dear friends i am having strange error which i am unable to solve, need your help. The code is working fine when login is incorrect and when login is correct it still creates a session but do not redirect to index.php instead it throws an error of "Cannot modify header information - headers already sent by...". I already search for similar posts but was not able to solve the issue

here is the code

<?php include ("scripts/connection.php");
session_start();
$myusername = $_POST["myusername"];
$myusername = preg_replace('/[^a-zA-Z0-9\']/','',$_POST['myusername']);
$mypassword = $_POST["mypassword"];
$mypassword = preg_replace('/[^a-zA-Z0-9\']/','',$_POST['mypassword']);
$LoginQuery = "SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Login</title>
</head>
<body>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr><form name="form1" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<?php if($_SERVER["REQUEST_METHOD"] == "POST")
{ $result = $mysql->query($LoginQuery);
  if($result->num_rows ==1) 
{
$_SESSION['login_user']=$myusername;
header("Location:index.php");
exit();
}
else
{
echo '<tr><td width="78">&nbsp;</td><td width="6"></td><td width="294"><font style="color:#f00; font-weight:bold;">Invalid!</font></td></tr>';
}
}
?>
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</body>
</html>

Friends can u find what i did wrong and help me correct it please. Thank you

user1231648
  • 178
  • 4
  • 19
  • 2
    This error indeed strange. It has been answered 1000s times already and still people keep asking, despite of all the answers in the right column `--->` – Your Common Sense Feb 17 '13 at 14:07

2 Answers2

0

you should use function header before writing any other text

Solon
  • 362
  • 1
  • 13
0

You have to understand HTTP:

A redirct is realized by the HTTP-Header. In HTTP the header is send, before any output (like the webpage itself)

So you are trying to send a Redirect-Header after you send payload.

This is not possible.

In short, never use header() after you print out something on the page.

El Hocko
  • 2,581
  • 1
  • 13
  • 22