Creating a simple REST API in PHP

2016.11.28 08:37

졸리운_곰 조회 수:53

Creating a simple REST API in PHP

I’m the author of php-crud-api and I want to share the core of the application with you. It includes routing a JSON REST request, converting it into SQL, executing it and giving a meaningful response. I tried to write the application as short as possible and came up with these 65 lines of code:

1                   
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
 
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
 
// connect to the mysql database
$link = mysqli_connect('localhost', 'user', 'pass', 'dbname');
mysqli_set_charset($link,'utf8');
 
// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
 
// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
  if ($value===null) return null;
  return mysqli_real_escape_string($link,(string)$value);
},array_values($input));
 
// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
  $set.=($i>0?',':'').'`'.$columns[$i].'`=';
  $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
 
// create SQL based on HTTP method
switch ($method) {
  case 'GET':
    $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
  case 'PUT':
    $sql = "update `$table` set $set where id=$key"; break;
  case 'POST':
    $sql = "insert into `$table` set $set"; break;
  case 'DELETE':
    $sql = "delete `$table` where id=$key"; break;
}
 
// excecute SQL statement
$result = mysqli_query($link,$sql);
 
// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error());
}
 
// print results, insert id or affected row count
if ($method == 'GET') {
  if (!$key) echo '[';
  for ($i=0;$i<mysqli_num_rows($result);$i++) {
    echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
  }
  if (!$key) echo ']';
} elseif ($method == 'POST') {
  echo mysqli_insert_id($link);
} else {
  echo mysqli_affected_rows($link);
}
 
// close mysql connection
mysqli_close($link);

This code is written to show you how simple it is to make a fully operational REST API in PHP.

Running

Save this file as “api.php” in your (Apache) document root and call it using:

http://localhost/api.php/{$table}/{$id}

Or you can use the PHP built-in webserver from the command line using:

$ php -S localhost:8888 api.php

The URL when ran in from the command line is:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

http://localhost:8888/api.php/{$table}/{$id}

NB: Don’t forget to adjust the ‘mysqli_connect’ parameters in the above script!

REST API in a single PHP file

Although the above code is not perfect it actually does do 3 important things:

  1. Support HTTP verbs GET, POST, UPDATE and DELETE
  2. Escape all data properly to avoid SQL injection
  3. Handle null values correctly

One could thus say that the REST API is fully functional. You may run into missing features of the code, such as:

  1. No related data (automatic joins) supported
  2. No condensed JSON output supported
  3. No support for PostgreSQL or SQL Server
  4. No POST parameter support
  5. No JSONP/CORS cross domain support
  6. No base64 binary column support
  7. No permission system
  8. No search/filter support
  9. No pagination or sorting supported
  10. No column selection supported

Don’t worry, all these features are available in php-crud-api, which you can get from Github. On the other hand, now that you have the essence of the application, you may also write your own!

 

[출처] https://www.leaseweb.com/labs/2015/10/creating-a-simple-rest-api-in-php/

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
69 [함수] SQLite 와 php 의 연동 졸리운_곰 2017.04.26 58
68 2.워드프레스 소스코드 분석(wp-header.php) 졸리운_곰 2017.04.23 120
67 1.워드프레스 소스 분석(index.php) 졸리운_곰 2017.04.23 263
66 WAMP 설치파일 bitnami bitnami-wampstack-5.6.30-2-windows- file 졸리운_곰 2017.04.15 79
65 rbjn.kr 로봇저널리즘 소스코드 자료 file 졸리운_곰 2017.03.14 61
64 워드프레스 데이터베이스 들여다보기. file 졸리운_곰 2017.02.27 55
63 워드프레스 페이지 분석 file 졸리운_곰 2017.02.27 144
62 워드프레스 템플릿 계층 구조 쉽게 이해하기!(What is Template Hierarchy!?) file 졸리운_곰 2017.02.27 245
61 워드프레스 테마 구조 file 졸리운_곰 2017.02.27 57
60 기본적으로 알아야할 워드프레스 파일 구조 및 디렉터리 구조 file 졸리운_곰 2017.02.27 60
59 워드프레스 웹페이지 구조와 구성요소인 템플릿 파일 이해하기. file 졸리운_곰 2017.02.27 148
58 워드프레스의 기본 구조에 대해 알아보자 file 졸리운_곰 2017.02.27 35
57 워드프레스 DB 쿼리 사용법 총정리 졸리운_곰 2017.02.25 63
56 wordpress Database Description file 졸리운_곰 2017.02.25 49
55 Tour of the WordPress Database file 졸리운_곰 2017.02.25 48
54 Beginner’s Guide to WordPress Database Management with phpMyAdmin file 졸리운_곰 2017.02.25 330
53 Wordpress DB table 파헤치기 file 졸리운_곰 2017.02.09 46
52 워드프레스 영문판 설치 후 한글화 하려면? 졸리운_곰 2017.02.08 33
51 fuelphp 도입부터 scaffolding 사용까지 졸리운_곰 2017.02.06 98
50 cake php 사용법 file 졸리운_곰 2017.01.15 2436
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED