如何验证用户密码并将用户数据作为json字符串回显?

时间:2018-12-05 03:41:12

标签: php mysqli

我正在开发一个Android应用程序,一个Java应用程序,并且我要求从主机上上传的php文件进行响应,而我的响应是“ []”,我检查了php代码,但我不知道该怎么办问题是,我看到了一些帖子,这是一个编码问题,对此我一无所知,请您帮我,这是我的PHP代码。

<?php 

require_once '../includes/DbConnect.php';

$response =array(); 

if($_POST['username'] && $_POST['password']){
    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "SELECT * FROM users WHERE username=?";
    $stmt = mysqli_stmt_init($con);
    mysqli_stmt_bind_param($stmt,"s",$username);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    if($user = mysqli_fetch_assoc($result))
    {
        $passwordCheck = password_verify($password,$user['password']);
        if($passwordCheck == false){
            $response['error'] = true; 
            $response['message'] = "Invalid username or password";  
        }
        else if($passwordCheck == true) {

            $response['error'] = false; 
            $response['id'] = $user['idUsers'];
            $response['email'] = $user['email'];
            $response['username'] = $user['username'];
            $response['country']= $user['country'];
             $response['firstname']= $user['firstname'];
              $response['lastname']= $user['lastname'];
               $response['points']= $user['points'];
        }
    }
}



echo json_encode($response);

?>

1 个答案:

答案 0 :(得分:1)

我建议的调整:

<?php     
require_once '../includes/DbConnect.php';  // <-- change from procedural to obj-oriented
$response['error'] = true;                 // default value
if (!isset($_POST['username'], $_POST['password'])) { 
    $response['message'] = "Invalid username or password";
} elseif (!$con) {
    $response['message'] = "Database Connection Error: "; // for private debugging only: . $con->connect_error;
} elseif (!$stmt = $con->prepare("SELECT * FROM users WHERE username = ?")) {
    $response['message'] = "Prepare Syntax Error";  // for private debugging only: . $con->error
} elseif (!$stmt->bind_param("s", $_POST['username']) || !$stmt->execute() || !$result = $stmt->get_result()) {
    $response['message'] = "Statement Error";  // for private debugging only: . $stmt->error
} elseif (!$user = $result->fetch_assoc() || !password_verify($_POST['password'], $user['password'])) {
    $response['message'] = "Invalid username or password";  
} else {
    $response['error'] = false; 
    $response['id'] = $user['idUsers'];
    $response['email'] = $user['email'];
    $response['username'] = $user['username'];
    $response['country'] = $user['country'];
    $response['firstname'] = $user['firstname'];
    $response['lastname'] = $user['lastname'];
    $response['points'] = $user['points'];
}
echo json_encode($response);