CodeIgniter RESTful And Basic Security

Bước 1 : Setup Project
1.1 Download CodeIgniter
Đầu tiên các bạn download CodeIgniter.Ở đây mình dùng version 3 download
Sau khi giải nén các bạn đổi tên folder root thành rest nhé
1.2 Cấu hình .htaccess
Cấu hình file config

// rest\application\config\config.php
$config['base_url'] = 'http://localhost/rest/';
$config['index_page'] = '';

Tạo file .htaccess ở folder root

<IfModule mod_php5.c>
    php_value always_populate_raw_post_data -1
</IfModule>
RewriteEngine On
RewriteBase /rest
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [PT,L,QSA]

Bước 2: Setup CodeIgniter RestServer
2.1 Setup package
Chạy lệnh sau để cài package

composer require chriskacerguis/codeigniter-restserver

Download file RestController.php ở đây Sau đó copy file này override file rest\vendor\chriskacerguis\codeigniter-restserver\src\RestController.php
Tiếp theo copy file rest.phprest\vendor\chriskacerguis\codeigniter-restserver\src\rest.php tới folder rest\application\config
2.2 Test
Tạo file Api.php ở folder Controller với code như sau:

Sao đó test trên trình duyệt

http://localhost/rest/api/users/ will return the list of all users
http://localhost/rest/api/users/id/1 will only return information about the user with id = 1

Chú ý các method cho phép [‘get’, ‘delete’, ‘post’, ‘put’, ‘options’, ‘patch’, ‘head’]
Cách đặt tên function là name function + _method
Ví dụ:Get list user listuser_get()
Bước 3: Tạo database test
Tạo database tên là restci
Connect database:

//rest\application\config\database.php
$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'restci',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Tạo table users

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Tạo table keys dùng để chứa key auth

CREATE TABLE `keys` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `key` varchar(40) NOT NULL,
 `level` int(2) NOT NULL,
 `ignore_limits` tinyint(1) NOT NULL DEFAULT '0',
 `is_private_key` tinyint(1) NOT NULL DEFAULT '0',
 `ip_addresses` text,
 `date_created` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Insert key

INSERT INTO `keys` (`id`, `user_id`, `key`, `level`, `ignore_limits`, `is_private_key`, `ip_addresses`, `date_created`) VALUES
(1, 0, 'CODEX@123', 0, 0, 0, NULL, '2017-10-12 13:34:33');

Bước 4 : Enable rest key
Open file rest\application\config\rest.php Sửa $config[‘rest_enable_keys’] = false; thành $config[‘rest_enable_keys’] = true;
Bước 5: Tạo model user ở application/models
getRows() – Fetch the user data from the users table and returns single row or multiple rows.
insert() – Insert user data in the users table.
user_put() – Update user data in the users table based on the given ID.
user_delete() – Delete user from the users table based on the given ID.

Bước 5:Tạo controller Api.php

Bước 6:Test
Insert User Data via REST API

<?php
//API key
$apiKey = 'CODEX@123';

//insert data
$url = 'http://localhost/rest/api/user/';
//user information
$userData = array(
    'first_name' => 'John',
    'last_name' => 'Doe',
    'email' => 'john@example.com',
    'phone' => '123-456-7890'
);

//create a new cURL resource
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $userData);

$result = curl_exec($ch);

//close cURL resource
curl_close($ch);

Retrieve User Data via REST API

<?php
//API key
$apiKey = 'CODEX@123';
//API URL
$url = 'http://localhost/rest/api/user/';

//API key
$apiKey = 'CODEX@123';
//create a new cURL resource
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey));

$result = curl_exec($ch);
//close cURL resource
curl_close($ch);
print_r($result);

Update User Data via REST API

<?php
//API key
$apiKey = 'CODEX@123';
//API URL
$url = 'http://localhost/rest/api/user/';

//API key
$apiKey = 'CODEX@123';

//Auth credentials

//user information
$userData = array(
    'id' => 2,
    'first_name' => 'John2',
    'last_name' => 'Doe2',
    'email' => 'john2@example.com',
    'phone' => '098-765-4321'
);

//create a new cURL resource
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-KEY: '.$apiKey, 'Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($userData));

$result = curl_exec($ch);

//close cURL resource
curl_close($ch);

Delete User Data via REST API

<?php
//API key
$apiKey = 'CODEX@123';
//API URL
$url = 'http://localhost/rest/api/user/1';

//API key
$apiKey = 'CODEX@123';

//API key
$apiKey = 'CODEX@123';

//Auth credentials

//create a new cURL resource
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');

$result = curl_exec($ch);

//close cURL resource
curl_close($ch);

Để nhanh thì các bạn có thể dùng postman nhé
Nguồn tham khảo ở đây

0 Shares

Leave a Reply

avatar
  Subscribe  
Notify of