Create a Rest API in PHP and Consume it in React Part 3

1 year ago admin PHP

In the third part of this tutorial, we will add routes to our application and finally, we will set the default file.


Add routes

Next, inside the file index.php, we add routes to fetch events, and categories, and register login and logout users.

                                                    
                                                                                                                
<?php
//autoloading classes
require_once __DIR__.'/vendor/autoload.php';

//fix cross origin blocked
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
    header("HTTP/1.1 200 OK");
    die();
}

//events actions
use App\Controllers\EventController as EventController;
$event = new EventController;

//categories actions
use App\Controllers\CategoryController as CategoryController;
$category = new CategoryController;

//user actions
use App\Controllers\UserController as UserController;
$user = new UserController;

//break url to parts
$segments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

if($_SERVER['REQUEST_METHOD'] === 'GET' && empty($segments[1])) {
    $event->index();
    exit;
}else if($_SERVER['REQUEST_METHOD'] === 'GET' && $segments[1] === 'events' && empty($segments[2])) {
    $event->index();
    exit;
}else if($_SERVER['REQUEST_METHOD'] === 'GET' && $segments[1] === 'event' && isset($segments[2])) {
    $event->show($segments[2]);
    exit;
}else if($_SERVER['REQUEST_METHOD'] === 'GET' && $segments[1] === 'events' && isset($segments[2]) && $segments[2] === 'category' && isset($segments[3])) {
    $event->eventsByCategory($segments[3]);
    exit;
}else if($_SERVER['REQUEST_METHOD'] === 'GET' && $segments[1] === 'categories' && empty($segments[2])) {
    $category->index();
    exit;
}else if($_SERVER['REQUEST_METHOD'] === 'POST' && $segments[1] === 'register' && empty($segments[2])) {
    $data = (array) json_decode(file_get_contents('php://input'), true);
    $user->register($data);
    exit;
}else if($_SERVER['REQUEST_METHOD'] === 'POST' && $segments[1] === 'login' && empty($segments[2])) {
    $data = (array) json_decode(file_get_contents('php://input'), true);
    $user->login($data);
    exit;
}else if($_SERVER['REQUEST_METHOD'] === 'POST' && $segments[1] === 'logout' && empty($segments[2])) {
    $data = (array) json_decode(file_get_contents('php://input'), true);
    $data['api_key'] = $_SERVER['HTTP_X_API_KEY'] ?? '';
    $user->logout($data);
    exit;
}else {
    http_response_code(404);
    echo json_encode([
        'error' => true,
        'message' => 'The page you are looking for does not exist.'
    ]);
}

Set index.php as default

Next, to set index.php as default once the user visits our app add the following code inside the file .htaccess.

                                                        
                                                                                                                        
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . index.php [L]

Related Tuorials

How to Use Variables and Data Types in PHP (A Clear Guide for Absolute Beginners) Part 2

In the second part of this guide, we will see more PHP types.Also, we will see how to check a variab...


How to Use Variables and Data Types in PHP (A Clear Guide for Absolute Beginners) Part 1

The first thing you need to understand when learning PHP is variables and data types. In this g...


How to Install and Run PHP on Your Localhost (Step-by-Step Guide)

If you want to learn PHP or build a web application with it, the first step is to create a working l...


CRUD Application with PHP PDO Ajax, and MySQL Part 2

In the second part of this tutorial, we will get all the students from the database and display them...


CRUD Application with PHP PDO Ajax, and MySQL Part 1

In this tutorial we will see how to create a crud application with PHP PDO Ajax, and MySQL, the user...


How to Sort Associative Arrays in Descending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the key...


How to Sort Associative Arrays in Ascending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in ascending order according to the key v...


How to Sort Associative Arrays in Descending Order According to the Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the valu...


How to Sort Associative Arrays in Ascending Order According to the Value in PHP

in this lesson, we will see how to sort associative arrays in ascending order according to the value...


How Do you Sort an Array in Descending Order in PHP

In this lesson, we will see how to sort descending an array in PHP, we will use the rsort() function...