Tartalomjegyzék

< PHP REST API

PHP REST API JSON fájlból

Bevezetés

A jelenlegi leírás egyszerű API felületet nyújt azonosítás nélkül.

Projekt szerkezet

app01/
  `-src/
     |-api/
        |-products/
        |  `-index.php
        `-database.json

Az index.php

src/products/index.php
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
$request = $_SERVER['REQUEST_URI'];
 
switch($method) {
    case 'POST':
        create_data($request);
        break;
    case 'GET':
        read_data();
        break;
    case 'PUT':
        update_data($request);
        break;
    case 'DELETE':
        delete_data($request);
        break;
    default:
        echo "Hiba! Nem használható metódus";
}
 
function create_data($request) {
    $data = file_get_contents('php://input');
    $a_data = json_decode($data);
 
    $inp = file_get_contents('../database.json');
    $tmp_array = json_decode($inp);
    $last_element = end($tmp_array->{'products'});
    $last_id = $last_element->id;
    $a_data->id = ++$last_id;
    array_push($tmp_array->{'products'}, $a_data);
    $jsonData = json_encode($tmp_array,
    JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    file_put_contents('../database.json', $jsonData);
    print_r($data);
}
 
function read_data() {
    $page = file_get_contents('../database.json');
    $obj = json_decode($page);
    $res = json_encode(
        $obj->{'products'}, 
        JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT 
    );
    echo $res;
}
 
function update_data($request) {
    header('Content-Type: text/html');
    $req_array = explode('/', $request);
    $id = $req_array[3];
 
    $data = file_get_contents('php://input');
    $a_data = json_decode($data);
 
    $inp = file_get_contents('../database.json');
    $tmp_array = json_decode($inp);
 
    $length = count($tmp_array->{'products'});
    for($i=0;  $i<$length; $i++) {
        if ($tmp_array->{'products'}[$i]->id == $id) {
            print_r($data);
            $tmp_array->{'products'}[$i]->name = $a_data->name;
            $tmp_array->{'products'}[$i]->price = $a_data->price;
        }
    }
    $jsonData = json_encode($tmp_array,
    JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    file_put_contents('../database.json', $jsonData);   
}
function delete_data($request) {
    $req_array = explode('/', $request);
    $id = $req_array[3];
 
    $inp = file_get_contents('../database.json');
    $tmp_array = json_decode($inp);
 
    $length = count($tmp_array->{'products'});
    for($i=0;  $i<$length; $i++) {
        if ($tmp_array->{'products'}[$i]->id == $id) {
            print_r(
                json_encode($tmp_array->{'products'}[$i])
            );            
            unset($tmp_array->{'products'}[$i]);
        }
    }
    $jsonData = json_encode($tmp_array,
    JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    file_put_contents('../database.json', $jsonData);
}