1

I am attempting to build a password-protected area on my site. However, in my if statement, I'm having trouble determining if the array is empty or not. When the code is run, regardless of what is put into the user/pass fields, it's always testing as true. For reference, the database being accessed only has 1 row, containing 1 user/pass combo.

function verify(){

  $dbhost = "host";
  $dbname = "db";
  $dbuser = "user";
  $dbpass = "password";


  if (isset($_SESSION['valid_user']))return true;

  $user_name = $_POST["user_name"]; 
  $password = $_POST["password"];

  if ($user_name && $password){ 

    try{ 
      $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
    }
    catch(PDOException $pe){
      die('Connection error, because: ' .$pe->getMessage());
    }

    $sql = "SELECT user_name FROM users WHERE user_name = ':user_name' AND password = ':password'";     

    $q = $conn->prepare($sql);

    if(!$q){
      die("Execute query error, because: ". $conn->errorInfo());
    }; 

    $q->execute(array(':user_name'=>$user_name, ':password'=>$password));  

    $result = $q->fetchALL();

    if ($result['user_name']=$user_name){ 
      $valid_user = $user_name;
      $_SESSION['valid_user'] = $valid_user;
      return true;
    }
    else{  
      $text = "User Name and Password did not match";
      write_log_in($text);
    }
  }
  else {  
    $text = "This is a secure server. Please log in.";
    write_log_in($text);
  }
}

As a side note, I'm aware that my passwords should be stored in at least an MD5 hash format or something similar. I just wanted to get it working at all before adding in more stuff.

4

4 回答 4

2

This is your problem

if ($result['user_name']=$user_name){ 

it should be

if ($result['user_name']==$user_name){ 

But why you don't check if you have a result to determine if the user is correct. Because you pass the user in your SQL query.

于 2013-04-18T17:35:32.130 回答
1

Missing an equal sign:

if ($result['user_name'] == $user_name){ 
// ----------------------^
于 2013-04-18T17:35:06.083 回答
1

$result['user_name']=$user_name should be $result['user_name'] === $user_name.

Also, don't use MD5. Hash the passwords with a slow hashing function like hash_pbkdf2, which is expensive to attack.

于 2013-04-18T17:35:51.420 回答
-1

您可以使用: if (mysql_num_rows($result)==0) 因为如果没有结果,则输入密码的用户不正确

于 2013-04-18T17:43:54.493 回答