Search code examples
phpmysqleasyphp

Problem with blank submitted values and returned mysql query


<?php
$link = mysql_connect('127.0.0.1', 'ilhan', 'password123');
if(!$link)
    {
        die('Could not connect: ' . mysql_error());
    }
mysql_select_db("metu", $link);
mysql_set_charset('utf8',$link);

if(isset($_POST["email"])) // AND strlen($_POST["email"])>1 solves the problem
//  but I didn't get why the page is redirected...
    {
        $email = mysql_real_escape_string($_POST["email"]);
        $password = mysql_real_escape_string($_POST["password"]);

        $result = mysql_query("SELECT password, id FROM users WHERE email = '$email'");

        if (!$result)
            {
                die('Invalid query: ' . mysql_error());
            }

        $row = mysql_fetch_assoc($result);

        if($row['password'] == $password) 
            {
                $_SESSION['valid_user'] = $row['id'];
                mysql_close($link);
                header("Location: http://www.example.com");
            }
        else $login = false;


        mysql_close($link);
    }
else $login = false;
?>

Do you think that the page will be redirected if the user submits a blank email and blank password? It shouldn't but the page is redirected. Why is that? Bug?


Solution

  • I've overlooked the issue at first. here it is:

    if($row['password'] == $password) 
    

    empty $row['password'] is equal to empty $password. evaluated to true

    here is what I'd do it

    <?php
    include 'db.php';    
    if(isset($_POST["email"]))
    {
        $sql = "SELECT id FROM users WHERE email='%s' AND password='%s'";
        $id  = dbGetOne($sql,$_POST["email"],MD5($_POST["email"].$_POST["password"]));
        if($id) 
        {
            $_SESSION['valid_user'] = $row['id'];
            header("Location: http://www.example.com");
            exit;
        }
    }