alphadec
alphadec

Reputation: 21

php - redirect does not work

I have created a site with a login and register.It was working, but when I finished it something was very wrong, I can't login to the site.

I can register a new user and that is added in the mysql db but when I try to login the redirect does not work it will not goto the page index.php.

Can anyone look at this source because and see if you can find anything wrong.

<?php


session_start();

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

if ($username&&$password)
{

$connect = mysql_connect("localhost","root","") or DIE ("Could not connect");
mysql_select_db("case") or die ("could not find db");

$query = mysql_query("SELECT * FROM users WHERE username='$username'");

$numrows = mysql_num_rows($query);

if($numrows !=0)

{

while ($row = mysql_fetch_assoc($query))    

{

$dbusername = $row['username'];
$dbpassword = $row['password'];

}

if ($username==$dbusername&&$password==$dbpassword)
{

header('location: index.php'); 


/*echo "Login successful. <a href='membersarea.php'>click her to enter members erea<a/>"; */
/*$_SESSION['username']=$dbusername; */

}
else
    echo "Incorrect password";
}
else echo ("That username dows not exist");
}
else
    die ("Please enter a username and password");



?>

Upvotes: 0

Views: 94

Answers (3)

Alex M
Alex M

Reputation: 514

At first sight, I notice this:

while ($row = mysql_fetch_assoc($query)) {
    $dbusername = $row['username'];
    $dbpassword = $row['password'];
}

if ($username == $dbusername && $password == $dbpassword) {

The if is outside the loop. It will only be used against the last row.

If you only have one user, it should be working.

Upvotes: 0

potashin
potashin

Reputation: 44581

Get rid of php closing tag ?> and whitespaces, html, blank lines before php opening tag <?php. Also check if there is no output before :

header("Location:");

Like print,var_dump, echo and so on. Also check your if condition, maybe you are just skipping it.

Upvotes: 4

Zerquix18
Zerquix18

Reputation: 769

WARNING! you have an SQL injection ERROR. Try with:

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

Now, simplify your life:

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

Is it right?

if( mysql_num_rows($query) > 0 ) {
 header('location: index.php');
}

Upvotes: 0

Related Questions