User Authentication using REST API and JSON Web Tokens (JWT) – Step 4

User Authentication using REST API and JSON Web Tokens (JWT) – Step 4

Create user folder and Create a new file called create_user.php and Following steps to be performed for this

1. We need to set headers on this new file so that it will only accept JSON data from a specific URL.

2. Connect to database and register table

3. Assign submitted data to object properties

4. Use the create () method

// 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->getConection();

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

// get posted data
$data = json_decode(file_get_contents("php://input"));

// 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) &&
) {

    // set response code

    // display message: user was created
    echo json_encode(array("message" => "User was created."));

// message if unable to create user
else {

    // set response code

    // display message: unable to create user
    echo json_encode(array("message" => "Unable to create user."));

Post Your Comments & Reviews

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