使用PDO的PHP验证不起作用

时间:2014-01-03 23:20:46

标签: php validation pdo

我是PDO的新手。我已在以下代码中包含验证但它似乎无法正常工作,如果用户输入错误的用户名/密码,则不会显示任何消息。请告诉我我哪里出错了。我有无数次让这个工作,但没有运气。感谢

<?php 
require("config.php"); 
$submitted_username = ''; 
if(!empty($_POST)){ 
    $query = " 
        SELECT 
            id, 
            username, 
            password, 
            salt, 
            email 
        FROM users 
        WHERE 
            username = :username 
    "; 
    $query_params = array( 
        ':username' => $_POST['username'] 
    ); 

    try{ 
        $stmt = $db->prepare($query); 
        $result = $stmt->execute($query_params); 
    } 
    catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } 
    $login_ok = false; 
    $row = $stmt->fetch(); 
    if($row){ 
        $check_password = hash('sha256', $_POST['password'] . $row['salt']); 
        for($round = 0; $round < 65536; $round++){
            $check_password = hash('sha256', $check_password . $row['salt']);
        } 
        if($check_password === $row['password']){
            $login_ok = true;
        } 
    } 

    if($login_ok){ 
        unset($row['salt']); 
        unset($row['password']); 
        $_SESSION['user'] = $row;  
        header("Location: secret.php"); 
        die("Redirecting to: secret.php"); 
    } 
    else{ 
        print("Login Failed."); 
        $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); 
    } 
  } 
?> 

CONFIG.PHP

<?php 

// These variables define the connection information for your MySQL database 
$username = "xxxx"; 
$password = "xxxx"; 
$host = "xxxxxxx"; 
$dbname = "xxxxxx"; 

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 
try
{
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
} 
catch(PDOException $ex)
{
    die("Failed to connect to the database: " . $ex->getMessage());
} 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
header('Content-Type: text/html; charset=utf-8'); 
session_start(); 
?>

0 个答案:

没有答案