PHP检查空字段登录

时间:2015-09-14 12:33:41

标签: php

我有一个选择操作,我想检查字段usernamepassword是否都为空。我的问题是,如果其中一个是空的echo msg pops但是,如果两个都是空的,它会直接进入下一页。

<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();

if ($_POST['submit']) {
    include_once("connexion.php");
    $username = strip_tags($_POST['username']);
    $password = strip_tags($_POST['password']);

    $sql = "SELECT id, username, password  FROM users where username = '$username' and password ='$password'";
    $query = mysqli_query($dbCon,$sql);

    if ($query) {
        $row = mysqli_fetch_row($query);
        $userId = $row[0];
        $dbUsername = $row[1];
        $dbPassword = $row[2];
    }

    if ($username == $dbUsername && $password == $dbPassword) {
        $_SESSION['username'] = $username;
        $_SESSION['id'] = $userId;
        header('location:../index-2.php');
    } else {
        echo "wrong username or password";
    }
}
?>

编辑:我使用了Dharmesh Goswami解决方案:

if ($username == $dbUsername && !empty($username) && $password == $dbPassword && empty($password) )

它就像一个魅力!谢谢。

5 个答案:

答案 0 :(得分:2)

您可以在表单发布后立即应用empty()条件。

if (isset($_POST['submit'])) {
  $username = strip_tags($_POST['username']);
  $password = strip_tags($_POST['password']);
  $username = trim($username);
  $password = trim($password);
  if (empty($username) || empty($password)) {
    // Print your error.
  }
}

||将检查其中一个或两个字段是否为空。

答案 1 :(得分:2)

如果条件都不为空,请检查。

if ($username == $dbUsername && !empty($username) && $password == $dbPassword && !empty($password) )
{
    $_SESSION['username'] = $username;
    $_SESSION['id'] = $userId;
    header('location:../index-2.php');
}else
{
    echo "wrong username or password";
}

答案 2 :(得分:1)

您可以使用empty()函数检查输入字符串是否为空。要检查其中一个字段是否为空,可以使用XOR(^)运算符。如果失败,控制应传递给AND(&amp;&amp;)运算符,该运算符检查两个字段是否为空。如果那也失败了,你可以说没有一个字段是空的。希望这会有所帮助。

if(isset($_POST['submit']){
   if(empty($_POST['username'] ^ empty($_POST['password']){
   // code here to perform task if one field is left empty

   } else if(empty($POST['username'] && empty($_POST['password']){
   // code here to perform task if both fields are empty  

   } else {
   // code here to perform task when none of the fields is empty

   }

}

答案 3 :(得分:0)

You do like that

extract($_POST);
if($_POST['submit']) :
if($Username == "" && $Password == ""):
$_SESSION['error'] = "Can't Be Blanked User Name Or Password";
endif;
endif;

答案 4 :(得分:0)

我建议使用mysqli_real_escape_string

if(!empty($_POST['username'])) $username = mysqli_real_escape_string($dbCon, $_POST['username']);

相同的密码

$sql = 'SELECT id, username, password  FROM use...';
$result = $dbCon->query($sql);
$count = $conn->affected_rows;
if ($count == 1)
{
    $_SESSION['username'] = $username;
    $_SESSION['id'] = $userId;
    header('location:../index-2.php');
}else echo "wrong username or password";

另外,不会在会话中保存用户名。查阅更多有关确保会话的信息。