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

7 months 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 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...


How to Sort Ascending an Array in PHP

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


How to Remove a Key and its Value from an Associative Array in PHP

In this lesson, we will see how to remove a key and its value from an associative array in PHP,&nbsp...


How to Modify a Value in an Associative Array in PHP

In this lesson, we will see how to modify a value in an associative array in PHP, an Associative arr...


How to Add an Item to an Associative Array in PHP

In this lesson, we will see how to add an item to an associative array in PHP, an Associative array...


How to Add an Element to an Array in PHP

In this lesson, we will see how to add an element to an array in PHP, PHP has a built-in function th...