PHP REST API CRUD – Step 13

PHP REST API CRUD – Step 13

Step 13 Register User with JWT

  1. Create a new file called register.php in user folder
  2. Download composer using command in api folder: composer require firebase/php-jwt
  3. create new file core. php in config folder
  4. Copy all the code of step5- Create API for user and use below lines in the starting of register. php files

<?php

require ‘..\vendor\autoload.php’;

use Firebase\JWT\JWT;

include_once ‘../config/core.php’;

?>

5. and the following insert code change and use JWT

// create the user
if (
    !empty($user->name) &&
    !empty($user->email) &&
    !empty($user->password) &&
    $user->create()
) {
    // set response code - 201 created
    http_response_code(201);

    array_push($payload, array('data' => array("email" => $user->email)));
    $jwt = JWT::encode($payload, $key);
    // tell the user

    echo json_encode(array("message" => "Registration successfully.", "token" => $jwt));
}

// message if unable to create user
else {

    // set response code
    http_response_code(400);
    // display message: unable to create user
    echo json_encode(array("message" => "Unable to Register user."));
}

6. The complete code is below

<?php
require '..\vendor\autoload.php';
use Firebase\JWT\JWT;
include_once '../config/core.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");

// files needed to connect to database
include '../config/database.php';
include '../objects/user.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// instantiate user object
$user = new User($db);

// get posted data
$json = json_encode($_POST);
$data = json_decode($json);

// set user property values
$user->name = $data->name;
$user->email = $data->email;
$user->password = $data->password;

// create the user
if (
    !empty($user->name) &&
    !empty($user->email) &&
    !empty($user->password) &&
    $user->create()
) {
    // set response code - 201 created
    http_response_code(201);

    array_push($payload, array('data' => array("email" => $user->email)));
    $jwt = JWT::encode($payload, $key);
    // tell the user

    echo json_encode(array("message" => "Registration successfully.", "token" => $jwt));
}

// message if unable to create user
else {

    // set response code
    http_response_code(400);
    // display message: unable to create user
    echo json_encode(array("message" => "Unable to Register user."));
}
One thought on “PHP REST API CRUD – Step 13

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*