Tartalomjegyzék

< PHP REST API

PHP REST API - Dolgozók példa

Adatbázis

create.sql
create table employees(
    id int not null primary key auto_increment,
    name varchar(50),
    city varchar(50),
    salary double
);

Kód

database.php
<?php
 
class Database {
    var $host = "localhost";
    var $user = "zoldzrt";
    var $pass = "titok";
    var $name = "zoldzrt";
    var $conn;
 
    function connectDb() {
        $con = mysqli_connect($this->host, $this->user, $this->pass, $this->name)
            or die('A kapcsolódás sikertelen: ' . mysqli_connect_error());
        if(mysqli_connect_errno()) {
            exit();
        }else {
            $this->conn = $con;
        }
        return $this->conn;
    }
}
employees.php
<?php
include('database.php');
 
$db = new Database();
$conn = $db->connectDb();
 
$request_method = $_SERVER["REQUEST_METHOD"];
switch($request_method) {
    case 'GET':
        getEmployees();
        break;
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        createEmployee($data["name"], $data["city"], $data["salary"]);
        break;
    case 'PUT':
        $id = intval($_GET["id"]);
        $data = json_decode(file_get_contents('php://input'), true);
        updateEmployee($id, $data["name"], $data["city"], $data["salary"]);
        break;
    case 'DELETE':
        $id = intval($_GET["id"]);
        deleteEmployee($id);
        break;
    default:
        header("HTTP/1.0 405 Method Not Implemented");
        break;
}
 
function createEmployee($name, $city, $salary) {
    global $conn;
    $sql = "insert into employees " . 
    "(name, city, salary) values " .
    "(\"$name\", \"$city\", $salary)";
    $response = array();
    if($conn->query($sql)) {
        header("HTTP/1.0 201");
        $response = array(
                'status' => 1,
                'message' => 'Ok. Employee Added.'
            );      
    }else {
        header("HTTP/1.0 400");
        $response = array(
                'status' => 0,
                'message' => 'Error! Employee Addition Failed.'
            );
    }
    header('Content-Type: application/json');
    echo json_encode($response);
}
 
function getEmployees() {
    global $conn;
    $sql = 'select * from employees';
    $result = $conn->query($sql);
    $response = array();
    if($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            array_push($response, $row);
        }
    }
    header('Content-Type: application/json');
    echo json_encode($response);
}
 
function updateEmployee($id, $name, $city, $salary) {
    global $conn;
    $sql = "update employees set name=\"$name\", " . 
    "city=\"$city\", salary=$salary where id=$id";
    $response = array();
    if($conn->query($sql)) {
        $response = array(
                'status' => 1,
                'message' => 'Ok. Employee Updated.'
            );      
    } else {
        header("HTTP/1.0 400");
        $response = array(
                'status' => 0,
                'message' => 'Error! Employee Updation Failed.'
            );
    }
    header('Content-Type: application/json');
    echo json_encode($response);
}
 
 
function deleteEmployee($id) {
    global $conn;
    $sql = "delete from employees where id=$id.";
    $response = array();
    if($conn->query($sql)) {
        header("HTTP/1.0 204"); 
    } else {
        header("HTTP/1.0 400");
        $response = array(
                'status' => 0,
                'message' => 'Error! Employee Deletion Failed.'
            );
    }
    header('Content-Type: application/json');
    echo json_encode($response);
}

Teszt HTTPie klienssel

http localhost:8000/employees.php
http post localhost:8000/employees.php
name="Erős István" city="Szeged" salary=395
http put localhost:8000/employees.php?id=4
name="Erős István" city="Szeged" salary=395
http delete localhost:8000/employees.php?id=5

Átirányítás

.htaccess
RewriteEngine On
RewriteRule ^employees/?$ employees.php [NC,L]
RewriteRule ^employees/?([0-9])/?$ employees.php?id=$1 [NC,L]

Azonosítás

auth.php
<?php
 
class Auth {
	var $token = "4389e898393";
	function authenticate() {
		$headers = getallheaders();
		print_r($headers);
		if(!array_key_exists('Authorization', $headers)) {
			header("HTTP/1.0 400");
			echo json_encode(["error" => "Authorization header is missing!"]);
			exit();
		}
		if(substr($headers['Authorization'], 0, 7) !== 'Bearer ' ) {
			header("HTTP/1.0 400");
			echo json_encode(["error" => "Bearer keyword is missing!"]);
			exit();			
		}
		$inputToken = trim(substr($headers['Authorization'], 7));
		return $inputToken === $this->token;
	}
}

Kiegészítjük a .htaccess fájlt:

.htaccess
RewriteEngine On
RewriteRule ^employees/?$ employees.php [NC,L]
RewriteRule ^employees/?([0-9])/?$ employees.php?id=$1 [NC,L]
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

Végül kiegészítjük az employees.php fájlt:

$auth = new Auth();
$isAuthorized = $auth->authenticate();
 
if(!$isAuthorized) {
	header("HTTP/1.0 401");
	exit();
}

Az egész fájl:

employee.php
<?php
include('database.php');
include('auth.php');
 
 
$auth = new Auth();
$isAuthorized = $auth->authenticate();
 
if(!$isAuthorized) {
	header("HTTP/1.0 401");
	exit();
}
 
 
$db = new Database();
$conn = $db->connectDb();
 
$request_method = $_SERVER["REQUEST_METHOD"];
switch($request_method) {
	case 'GET':
		getEmployees();
		break;
	case 'POST':
		$data = json_decode(file_get_contents('php://input'), true);
		createEmployee($data["name"], $data["city"], $data["salary"]);
		break;
	case 'PUT':
		$id = intval($_GET["id"]);
		$data = json_decode(file_get_contents('php://input'), true);
		updateEmployee($id, $data["name"], $data["city"], $data["salary"]);
		break;
	case 'DELETE':
		$id = intval($_GET["id"]);
		deleteEmployee($id);
		break;
	default:
		header("HTTP/1.0 405 Method Not Implemented");
		break;
}
 
function createEmployee($name, $city, $salary) {
	global $conn;
	$sql = "insert into employees " . 
	"(name, city, salary) values " .
	"(\"$name\", \"$city\", $salary)";
	$response = array();
	if($conn->query($sql)) {
		header("HTTP/1.0 201");
		$response = array(
	            'status' => 1,
	            'message' => 'Ok. Employee Added.'
        	);		
	}else {
		header("HTTP/1.0 400");
		$response = array(
	            'status' => 0,
	            'message' => 'Error! Employee Addition Failed.'
        	);
	}
	header('Content-Type: application/json');
	echo json_encode($response);
}
 
function getEmployees() {
	global $conn;
	$sql = 'select * from employees';
	$result = $conn->query($sql);
	$response = array();
	if($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {
			array_push($response, $row);
		}
	}
	header('Content-Type: application/json');
	echo json_encode($response);
}
 
function updateEmployee($id, $name, $city, $salary) {
	global $conn;
	$sql = "update employees set name=\"$name\", " . 
	"city=\"$city\", salary=$salary where id=$id";
	$response = array();
	if($conn->query($sql)) {
		$response = array(
	            'status' => 1,
	            'message' => 'Ok. Employee Updated.'
        	);		
	} else {
		header("HTTP/1.0 400");
		$response = array(
	            'status' => 0,
	            'message' => 'Error! Employee Updation Failed.'
        	);
	}
	header('Content-Type: application/json');
	echo json_encode($response);
}
 
 
function deleteEmployee($id) {
	global $conn;
	$sql = "delete from employees where id=$id.";
	$response = array();
	if($conn->query($sql)) {
		header("HTTP/1.0 204");	
	} else {
		header("HTTP/1.0 400");
		$response = array(
	            'status' => 0,
	            'message' => 'Error! Employee Deletion Failed.'
        	);
	}
	header('Content-Type: application/json');
	echo json_encode($response);
}