Login page goes directly to the site without checking credentials

88 views Asked by At

I am currently having a problem in which the login page to my website goes directly to the homepage without checking the users credentials stored in my data base. The code I use to register the users works just fine but for some reason I cant get this working properly.

<?php
    session_start();
    $dbhost = 'localhost:3036';
    $dbuser = 'mredd';
    $dbpass = 'csc255pass';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    //mysql_select_db( 'USERS_DB' );
    if(! $conn )
        {
            die('Could not connect: ' . mysql_error());
        }
    $db_selected = mysql_select_db("USERS_DB",$conn);

    if (!$db_selected)
     {
        die ("Can\'t use test_db : " . mysql_error());
     }


    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
    $user = $_POST['username'];
    $pass = $_POST['password'];


$sql="SELECT * FROM log_tbl Where username='$user' AND password='$pass'";
$retval = mysql_query( $sql, $conn );

$row = mysql_num_rows($retval);
if ($row == 1)
    $_SESSION['user'] = $user;
    header("Location: homepage.php");

    }   
  ?>    
1

There are 1 answers

1
parker.sikand On

Doh! You fell into the trap of not using brackets with your If statement. The final chunk should read

$sql="SELECT * FROM log_tbl Where username='$user' AND password='$pass'";
$retval = mysql_query( $sql, $conn );

$row = mysql_num_rows($retval);
if ($row == 1) { //need this bracket
  $_SESSION['user'] = $user;
  header("Location: homepage.php");
 }  //and this one
} // this closes the 'POST' clause
?>

The code you wrote will only set the session if the row is returned, and will ALWAYS redirect to homepage.php. An If statement without brackets only controls the next command.