php基于curl扩展制作跨平台的restfule 接口
这篇文章主要介绍了php基于curl扩展制作跨平台的restfule 接口的相关资料以及详细的代码,有需要的小伙伴可以参考下。
restfule 接口
适用的平台:跨平台
所依赖:curl扩展
git:https://git.oschina.net/anziguoer/restAPI
ApiServer.php
?
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
/** * @Author: yangyulong * @Email : anziguoer@sina.com * @Date: 2015-04-30 05:38:34 * @Last Modified by: yangyulong * @Last Modified time: 2015-04-30 17:14:11 */
class apiServer { /** * 客户端请求的方式 * @var string */ private $method = '';
/** * 客户端发送的数据 * @var [type] */ protected $param;
/** * 要操作的资源 * @var [type] */ protected $resourse;
/** * 要操作的资源id * @var [type] */ protected $resourseId;
/** * 构造函数, 获取client 请求的方式,以及传输的数据 * @param object 可以自定义传入的对象 */ public function __construct() { //首先对客户端的请求进行验证 $this->authorization();
$this->method = strtolower($_SERVER['REQUEST_METHOD']);
//所有的请求都是pathinfo模式 $pathinfo = $_SERVER['PATH_INFO'];
//将pathinfo数据信息映射为实际请求方法 $this->getResourse($pathinfo);
//获取传输的具体参数 $this->getData();
//执行响应 $this->doResponse(); }
/** * 根据不同的请求方式,获取数据 * @return [type] */ private function doResponse(){ switch ($this->method) { case 'get': $this->_get(); break; case 'post': $this->_post(); break; case 'delete': $this->_delete(); break; case 'put': $this->_put(); break; default: $this->_get(); break; } }
// 将pathinfo数据信息映射为实际请求方法 private function getResourse($pathinfo){
/** * 将pathinfo数据信息映射为实际请求方法 * GET /users: 逐页列出所有用户; * POST /users: 创建一个新用户; * GET /users/123: 返回用户为123的详细信息; * PUT /users/123: 更新用户123; * DELETE /users/123: 删除用户123; * * 根据以上规则,将pathinfo第一个参数映射为需要操作的数据表, * 第二个参数映射为操作的id */
$info = explode('/', ltrim($pathinfo, '/')); list($this->resourse, $this->resourseId) = $info; }
/** * 验证请求 */ private function authorization(){ $token = $_SERVER['HTTP_CLIENT_TOKEN']; $authorization = md5(substr(md5($token), 8, 24).$token); if($authorization != $_SERVER['HTTP_CLIENT_CODE']){ //验证失败,输出错误信息给客户端 $this->outPut($status = 1); } }
/** * [getData 获取传送的参数信息] * @param [type] $pad [description] * @return [type] [description] */ private function getData(){ //所有的参数都是get传参 $this->param = $_GET; }
/** * 获取资源操作 * @return [type] [description] */ protected function _get(){ //逻辑代码根据自己实际项目需要实现 }
/** * 新增资源操作 * @return [type] [description] */ protected function _post(){ //逻辑代码根据自己实际项目需要实现 }
/** * 删除资源操作 * @return [type] [description] */ protected function _delete(){ //逻辑代码根据自己实际项目需要实现 }
/** * 更新资源操作 * @return [type] [description] */ protected function _put(){ //逻辑代码根据自己实际项目需要实现 }
/** * 出入服务端返回的数据信息 json格式 */ public function outPut($stat, $data=array()){ $status = array( //0 状态表示请求成功 0 => array( 'code' => 1, 'info' => '请求成功', 'data' =>$data ), //验证失败 1 => array( 'code' => 0, 'info' => '请求不合法' ) );
try{ if(!in_array($stat, array_keys($status))){ throw new Exception('输入的状态码不合法'); }else{ echo json_encode($status[$stat]); } }catch (Exception $e){ die($e->getMessage()); } } } |
ApiClient.php
?
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
/** * Created by PhpStorm. * User: anziguoer@sina.com * Date: 2015/4/29 * Time: 12:36 * link: http://www.ruanyifeng.com/blog/2014/05/restful_api.html [restful设计指南] */ /*** * * * * * * * * * * * * * * * * * * * * * * * * * ***\ * 定义路由的请求方式 * * * * $url_model=0 * * 采用传统的URL参数模式 * * http://serverName/appName/?m=module&a=action&id=1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PATHINFO模式(默认模式) * * 设置url_model 为1 * * http://serverName/appName/module/action/id/1/ * ** * * * * * * * * * * * * * * * * * * * * * * * * * * ** */ class restClient { //请求的token const token='yangyulong';
//请求url private $url;
//请求的类型 private $requestType;
//请求的数据 private $data;
//curl实例 private $curl;
public $status;
private $headers = array(); /** * [__construct 构造方法, 初始化数据] * @param [type] $url 请求的服务器地址 * @param [type] $requestType 发送请求的方法 * @param [type] $data 发送的数据 * @param integer $url_model 路由请求方式 */ public function __construct($url, $data = array(), $requestType = 'get') {
//url是必须要传的,并且是符合PATHINFO模式的路径 if (!$url) { return false; } $this->requestType = strtolower($requestType); $paramUrl = ''; // PATHINFO模式 if (!empty($data)) { foreach ($data as $key => $value) { $paramUrl.= $key . '=' . $value.'&'; } $url = $url .'?'. $paramUrl; }
//初始化类中的数据 $this->url = $url;
$this->data = $data; try{ if(!$this->curl = curl_init()){ throw new Exception('curl初始化错误:'); }; }catch (Exception $e){ echo ' '; <p>print_r($e->getMessage());</p> <p>echo '</p>'; }
curl_setopt($this->curl, CURLOPT_URL, $this->url); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
}
/** * [_post 设置get请求的参数] * @return [type] [description] */ public function _get() {
}
/** * [_post 设置post请求的参数] * post 新增资源 * @return [type] [description] */ public function _post() {
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
}
/** * [_put 设置put请求] * put 更新资源 * @return [type] [description] */ public function _put() {
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT'); }
/** * [_delete 删除资源] * delete 删除资源 * @return [type] [description] */ public function _delete() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
/** * [doRequest 执行发送请求] * @return [type] [description] */ public function doRequest() { //发送给服务端验证信息 if((null !== self::token) && self::token){ $this->headers = array( 'Client_Token: '.self::token, 'Client_Code: '.$this->setAuthorization() ); }
//发送头部信息 $this->setHeader();
//发送请求方式 switch ($this->requestType) { case 'post': $this->_post(); break;
case 'put': $this->_put(); break;
case 'delete': $this->_delete(); break;
default: curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE); break; } //执行curl请求 $info = curl_exec($this->curl);
//获取curl执行状态信息 $this->status = $this->getInfo(); return $info; }
/** * 设置发送的头部信息 */ private function setHeader(){ curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers); }
/** * 生成授权码 * @return string 授权码 */ private function setAuthorization(){ $authorization = md5(substr(md5(self::token), 8, 24).self::token); return $authorization; } /** * 获取curl中的状态信息 */ public function getInfo(){ return curl_getinfo($this->curl); }
/** * 关闭curl连接 */ public function __destruct(){ curl_close($this->curl); } } |
testClient.php
?
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 |
/** * Created by PhpStorm. * User: anziguoer@sina.com * Date: 2015/4/29 * Time: 12:35 */
include './ApiClient.php';
$arr = array( 'user' => 'anziguoer', 'passwd' => 'yangyulong' ); // $url = 'http://localhost/restAPI/restServer.php'; $url = 'http://localhost/restAPI/testServer.php/user/123';
$rest = new restClient($url, $arr, 'get'); $info = $rest->doRequest();
//获取curl中的状态信息 $status = $rest->status; echo ' '; <p>print_r($info);</p> <p>echo '</p>'; |
testServer.php
?
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 66 |
/** * @Author: anziguoer@sina.com * @Email: anziguoer@sina.com * @link: https://git.oschina.net/anziguoer * @Date: 2015-04-30 16:52:53 * @Last Modified by: yangyulong * @Last Modified time: 2015-04-30 17:26:37 */
include './ApiServer.php';
class testServer extends apiServer { /** * 先执行apiServer中的方法,初始化数据 * @param object $obj 可以传入的全局对象[数据库对象,框架全局对象等] */
private $obj;
function __construct()//object $obj { parent::__construct(); //$this->obj = $obj; //$this->resourse; 父类中已经实现,此类中可以直接使用 //$tihs->resourseId; 父类中已经实现,此类中可以直接使用 }
/** * 获取资源操作 * @return [type] [description] */ protected function _get(){ echo "get"; //逻辑代码根据自己实际项目需要实现 }
/** * 新增资源操作 * @return [type] [description] */ protected function _post(){ echo "post"; //逻辑代码根据自己实际项目需要实现 }
/** * 删除资源操作 * @return [type] [description] */ protected function _delete(){ //逻辑代码根据自己实际项目需要实现 }
/** * 更新资源操作 * @return [type] [description] */ protected function _put(){ echo "put"; //逻辑代码根据自己实际项目需要实现 } }
$server = new testServer(); |
以上所述就是本文的全部内容了,希望大家能够喜欢。

데이터베이스 스토리지 세션 사용의 주요 장점에는 지속성, 확장 성 및 보안이 포함됩니다. 1. 지속성 : 서버가 다시 시작 되더라도 세션 데이터는 변경되지 않아도됩니다. 2. 확장 성 : 분산 시스템에 적용하여 세션 데이터가 여러 서버간에 동기화되도록합니다. 3. 보안 : 데이터베이스는 민감한 정보를 보호하기 위해 암호화 된 스토리지를 제공합니다.

SessionHandlerInterface 인터페이스를 구현하여 PHP에서 사용자 정의 세션 처리 구현을 수행 할 수 있습니다. 특정 단계에는 다음이 포함됩니다. 1) CustomsessionHandler와 같은 SessionHandlerInterface를 구현하는 클래스 만들기; 2) 인터페이스의 방법 (예 : Open, Close, Read, Write, Despare, GC)의 수명주기 및 세션 데이터의 저장 방법을 정의하기 위해 방법을 다시 작성합니다. 3) PHP 스크립트에 사용자 정의 세션 프로세서를 등록하고 세션을 시작하십시오. 이를 통해 MySQL 및 Redis와 같은 미디어에 데이터를 저장하여 성능, 보안 및 확장 성을 향상시킬 수 있습니다.

SessionId는 웹 애플리케이션에 사용되는 메커니즘으로 사용자 세션 상태를 추적합니다. 1. 사용자와 서버 간의 여러 상호 작용 중에 사용자의 신원 정보를 유지하는 데 사용되는 무작위로 생성 된 문자열입니다. 2. 서버는 쿠키 또는 URL 매개 변수를 통해 클라이언트로 생성하여 보낸다. 3. 생성은 일반적으로 임의의 알고리즘을 사용하여 독창성과 예측 불가능 성을 보장합니다. 4. 실제 개발에서 Redis와 같은 메모리 내 데이터베이스를 사용하여 세션 데이터를 저장하여 성능 및 보안을 향상시킬 수 있습니다.

JWT 또는 쿠키를 사용하여 API와 같은 무국적 환경에서 세션을 관리 할 수 있습니다. 1. JWT는 무국적자 및 확장 성에 적합하지만 빅 데이터와 관련하여 크기가 크다. 2. 쿠키는보다 전통적이고 구현하기 쉽지만 보안을 보장하기 위해주의해서 구성해야합니다.

세션 관련 XSS 공격으로부터 응용 프로그램을 보호하려면 다음 조치가 필요합니다. 1. 세션 쿠키를 보호하기 위해 Httponly 및 Secure 플래그를 설정하십시오. 2. 모든 사용자 입력에 대한 내보내기 코드. 3. 스크립트 소스를 제한하기 위해 컨텐츠 보안 정책 (CSP)을 구현하십시오. 이러한 정책을 통해 세션 관련 XSS 공격을 효과적으로 보호 할 수 있으며 사용자 데이터가 보장 될 수 있습니다.

PHP 세션 성능을 최적화하는 방법 : 1. 지연 세션 시작, 2. 데이터베이스를 사용하여 세션을 저장, 3. 세션 데이터 압축, 4. 세션 수명주기 관리 및 5. 세션 공유 구현. 이러한 전략은 높은 동시성 환경에서 응용의 효율성을 크게 향상시킬 수 있습니다.

THESESSION.GC_MAXLIFETIMESETTINGINSTTINGTINGSTINGTERMINESTERMINESTERSTINGSESSIONDATA, SETINSECONDS.1) IT'SCONFIGUDEDINPHP.INIORVIAINI_SET ()

PHP에서는 Session_Name () 함수를 사용하여 세션 이름을 구성 할 수 있습니다. 특정 단계는 다음과 같습니다. 1. Session_Name () 함수를 사용하여 Session_Name ( "my_session")과 같은 세션 이름을 설정하십시오. 2. 세션 이름을 설정 한 후 세션을 시작하여 세션을 시작하십시오. 세션 이름을 구성하면 여러 응용 프로그램 간의 세션 데이터 충돌을 피하고 보안을 향상시킬 수 있지만 세션 이름의 독창성, 보안, 길이 및 설정 타이밍에주의를 기울일 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Dreamweaver Mac版
시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.
