[[oktatas:programozas:php:php_rest_api|< PHP REST API]]
====== PHP REST API - Dolgozók példa ======
* **Szerző:** Sallai András
* Copyright (c) 2024, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Adatbázis =====
create table employees(
id int not null primary key auto_increment,
name varchar(50),
city varchar(50),
salary double
);
===== Kód =====
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;
}
}
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 =====
RewriteEngine On
RewriteRule ^employees/?$ employees.php [NC,L]
RewriteRule ^employees/?([0-9])/?$ employees.php?id=$1 [NC,L]
===== Azonosítás =====
"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:
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:
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);
}