PHP REST API CRUD – Step 14
Step 14 Login User with JWT
- create new file core. php in config folder
- Create login function in user.php
//Login Student
public function readLogin($email, $password)
{
$query = "Select * from " . $this->table . " where email= '" . $email . " ' LIMIT 1";
try {
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
} catch (PDOException $e) {
echo json_encode(array("AuthenticationStudentSQLError" => $e->getMessage()));die;
}
}
- 3. Copy all the code of step8- Read API for user
- 4. The complete code is below
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require '../vendor/autoload.php';
use Firebase\JWT\JWT;
include_once '../config/core.php';
include "../config/database.php";
include "../objects/user.php";
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
// get posted data
$json = json_encode($_POST);
$data = json_decode($json);
//Read data with JWT
if (
!empty($data->email) &&
!empty($data->password)
) {
$stmt = $user->readLogin($data->email, $data->password);
$rowcount = $stmt->rowCount();
if ($rowcount > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
if (password_verify($data->password, $password)) {
array_push($payload, array('data' => array("email" => $user->email)));
$jwt = JWT::encode($payload, $key);
http_response_code(200);
echo json_encode(array("message" => "Login Successfully.", "token" => $jwt));
} else {
http_response_code(401);
echo json_encode(array("message" => "Username/Password Incorrect."));
}
}
} else {
http_response_code(401);
echo json_encode(array("message" => "Username/Password Incorrect."));
}
} else {
http_response_code(400);
echo json_encode(array("message" => "Unable to Find Student. Data is incomplete."));
}
This infomation is really good
inmative and easy guide