checking username and password PHP

时间:2017-08-04 13:01:26

标签: php

I'm trying to create a php username and password checker but can't get it to work, here is the code:

<?php
$servername = "iphere";
$user = "userhere";
$pass = "passwordhere";
$dbname = "databasehere";

try {
    $username = $_GET['username'];
    $password = $_GET['password'];
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT username FROM users WHERE username = :name AND password = :password");
    $stmt->bindParam(':name', $username);
    $stmt->bindParam(':password', $password);
    $stmt->execute();
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    if($username == $result && $password == $result)
    {
        echo "OK";
    }
    else
    {
        echo "not OK";
    }


}
catch(PDOException $e) {
    echo "Error";
}
$conn = null;
?>

It doesn't give any error or anything. It just echoes OK and thats it. By the way i use GET for my another project. So i will change it later.

2 个答案:

答案 0 :(得分:2)

Unless there is an error, this:

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

will always be the boolean value true.

You then perform this test:

if($username == $result && $password == $result)

Non-blank strings will always be equal to true.


Count the number of rows returned from the database instead.

答案 1 :(得分:0)

Ignoring the facts that:

  • your password is in plaintext
  • you're using bindParam for no reason

then the code that I'd use would be something like this (didn't test, beware):

$stmt = $pdo->prepare("SELECT COUNT(*) AS user_exists FROM users WHERE username = :username AND password = :password");

$stmt->execute([':username' => $username, ':password' => $password]);

// This will return the value of first column, our query will always produce 1 row with 1 column
$exists = $stmt->fetchColumn(); 

// If you are using MySQL ND (native driver), then the above result will be 
// accurately represented as an integer so we can use it in an if() statement like this
if($exists)
{
    echo "OK!";
}
else
{
    echo "Not ok!";
}