遇到PHP和SQL问题

时间:2016-02-22 22:40:54

标签: php sql

我试图在php中显示错误消息($ error =“用户名或密码无效”; )当用户名或密码不在数据库中时。但是甚至没有运行代码(在index.php中单击登录,显示错误消息。谢谢:)

<?php

    session_start(); // Starting Session
    $error=''; // Variable To Store Error Message
    if (isset($_POST['submit'])) {

    }

    if (isset($_POST['submit'])) {



    // Define $username and $password
     $name=$_POST['username'];
     $pass=$_POST['password'];

    $servername = "localhost";
    $username = "root";
    $password = "root";
    $dbname = "company";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection


    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT id, username, password FROM login";
    $result = $conn->query($sql);


    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            //echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["password"]. "<br>";
            if($name==$row["username"] && $pass== $row["password"]){
                header("location: profile.php"); // Redirecting To Other Page
            }else{
                $error="Username or Password is invalid";
            }

        }

    }




         else {
        echo "Server is down";
    }
    $conn->close();
    }

    ?>

我的index.php

<?php
include('../php/login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: ../php/profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

我稍微更新了你的安全性。确保始终验证用户输入。下面的代码可以防止SQL注入。无法注射!此外,HEX攻击也是不可能的。

<?php
if (!isset($_SESSION)) { session_start(); }

$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "company";

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}   

$errmessage = $error = '';

function checkUsername($data) {
    if (preg_match('/[^A-Za-z0-9.]{8,50}/', $data)) { // A-Z, a-z, 0-9, . (dot), min-length: 8, max-length: 50
        $data = false;
    } 
    return $data;
}

function checkPassword($data) {
    if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,50}$/', $data)) { // A-Z, a-z, 0-9, !, @, #, $, %, min-length: 8, max-length: 50
        $data = false;
    }
    return $data;
}

if (isset($_POST['submit']) && isset($_POST['username']) && isset($_POST['password'])) {

    $username = $_POST['username'];
    $password = $_POST['password'];

    if (checkUsername($username) === false) {
        $error = "Username is not valid!";
        exit();
    }
    if (checkPassword($password) === false) {
        $error = "Password is not valid!";
        exit();
    }

    $secure_name = bin2hex(htmlspecialchars($username));
    //$secure_pass = hashpassword($securepass); // Hash your passwords!
    $secure_pass = bin2hex(htmlspecialchars($password));

    $sql = "SELECT * FROM login WHERE username = UNHEX('$username') AND password = UNHEX('$password')";
    $result = $conn->query($sql);

    if ($result->num_rows == 1) {
        session_regenerate_id();
        $_SESSION['login_user'] = true;
        header("location: profile.php");
    } else {
        $error = "Username and/or Password is invalid";
    }
    $conn->close();

} else {
    echo "Error";
}
?>

HEX反对注射的来源:How can I prevent SQL injection in PHP?(Zaffy的回答)

额外信息:

不要仅检查会话登录是否存在,还要检查其值!

if(isset($_SESSION['login_user'])){
    header("location: ../php/profile.php");
}

必须

if (isset($_SESSION['login_user']) && $_SESSION['login_user'] === true){
    header("location: ../php/profile.php");
    exit();
} else {
    // Loginscript
}

答案 1 :(得分:0)

PHP脚本似乎从DB

中获取所有用户名/密码对

$sql = "SELECT id, username, password FROM login";

稍后在while循环中,第一对与用户输入不匹配将触发错误消息分配