开发者

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?


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;
    }
}


Use mysql_num_rows function to find then umber of rows returned. mysql_query will return FALSE on error but in your case, your SQL is still a valid SQL if email is blank. It will just return an empty result set.


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

if $_POST["email"] is empty string -> isset will return true

EDIT: add if ( isset($_POST["email"]) && isset ($_POST["password"]) ) to avoid empty passwords and make sure that $row is not empty when `if($row['password'] == $password)'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜