Monday, 12 December 2016

Create REST services in PHP

How to create REST services in PHP

Let's say we have our application directory structure like this

- api
- - request.php
- - .htaccess

Edit .htaccess file which is under api directory with below code


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)$ request.php?_url=$1 [QSA,NC,L]
</IfModule>

Every request comes with any pattern starting with "/api" will go to our "request.php"


This will handle any rest pattern with /api/*



Our request.php will look like

<?php

session_start();

$_url = $_GET['_url'];


switch ($_url) {
    case "products" :
        echo "All Products";
        break;
    case "product" :
        echo "One Product";
        break;
    case "product/save" :
        $request_body = file_get_contents('php://input');
        $data = json_decode($request_body);
        echo "Data saved to DB";
        break;
    default :
        header($_SERVER["SERVER_PROTOCOL"] . "404 Not Found", true, 404);
}


Write me back in comment, if have any query.


No comments:

Post a Comment