Home > Backend Development > PHP Tutorial > PHP makes a cross-platform restfule interface based on curl extension_PHP tutorial

PHP makes a cross-platform restfule interface based on curl extension_PHP tutorial

WBOY
Release: 2016-07-13 09:54:11
Original
827 people have browsed it

PHP makes a cross-platform restfule interface based on curl extension

This article mainly introduces the relevant information and detailed code of making a cross-platform restfule interface in PHP based on curl extension. There are Friends who need it can refer to it.

Restfule interface

Applicable platforms: cross-platform

Depends on: curl extension

 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

{

/**

* Client request method

* @var string

*/

private $method = '';

/**

* Data sent by the client

* @var [type]

*/

protected $param;

/**

* The resource to be operated

* @var [type]

*/

protected $resourse;

/**

* Resource id to be operated

* @var [type]

*/

protected $resourseId;

/**

* Constructor, obtains the client request method and the transmitted data

* @param object can customize the passed in object

*/

public function __construct()

{

//First verify the client’s request

$this->authorization();

$this->method = strtolower($_SERVER['REQUEST_METHOD']);

//All requests are in pathinfo mode

$pathinfo = $_SERVER['PATH_INFO'];

//Map pathinfo data information to the actual request method

$this->getResourse($pathinfo);

//Get the specific parameters of transmission

$this->getData();

//Execute response

$this->doResponse();

}

/**

* Obtain data according to different request methods

* @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;

}

}

// Map pathinfo data information to the actual request method

private function getResourse($pathinfo){

/**

* Map pathinfo data information to the actual request method

* GET /users: List all users page by page;

* POST /users: Create a new user;

* GET /users/123: Returns the detailed information of user 123;

* PUT /users/123: Update user 123;

* DELETE /users/123: Delete user 123;

*

* According to the above rules, map the first parameter of pathinfo to the data table that needs to be operated,

* The second parameter is mapped to the id of the operation

*/

$info = explode('/', ltrim($pathinfo, '/'));

list($this->resourse, $this->resourseId) = $info;

}

/**

* Verification request

*/

private function authorization(){

$token = $_SERVER['HTTP_CLIENT_TOKEN'];

$authorization = md5(substr(md5($token), 8, 24).$token);

if($authorization != $_SERVER['HTTP_CLIENT_CODE']){

//Verification fails and error message is output to the client

$this->outPut($status = 1);

}

}

/**

* [getData gets the transmitted parameter information]

* @param [type] $pad [description]

* @return [type] [description]

*/

private function getData(){

//All parameters are passed by get

$this->param = $_GET;

}

/**

* Get resource operation

* @return [type] [description]

*/

protected function _get(){

//The logic code is implemented according to your actual project needs

}

/**

* Add new resource operation

* @return [type] [description]

*/

protected function _post(){

//The logic code is implemented according to your actual project needs

}

/**

* Delete resource operation

* @return [type] [description]

*/

protected function _delete(){

//The logic code is implemented according to your actual project needs

}

/**

* Update resource operation

* @return [type] [description]

*/

protected function _put(){

//The logic code is implemented according to your actual project needs

}

/**

* Data information returned by the server in json format

*/

public function outPut($stat, $data=array()){

$status = array(

//0 status means the request is successful

0 => array(

'code' => 1,

'info' => 'Request successful',

'data' =>$data

),

//Verification failed

1 => array(

'code' => 0,

'info' => 'Illegal request'

)

);

try{

if(!in_array($stat, array_keys($status))){

throw new Exception('The entered status code is illegal');

}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 design guide]

*/

/*** * * * * * * * * * * * * * * * * * * * * * * * * * ***

* Define the routing request method *

* *

* $url_model=0 *

* Use traditional URL parameter mode *

* http://serverName/appName/?m=module&a=action&id=1 *

* * * * * * * * * * * * * * * * * * * * * * * * * * * * *

* PATHINFO mode (default mode) *

* Set url_model to 1 *

* http://serverName/appName/module/action/id/1/ *

** * * * * * * * * * * * * * * * * * * * * * * * * * * **

*/

class restClient

{

//Requested token

const token='yangyulong';

//Request url

private $url;

//Type of request

private $requestType;

//Requested data

private $data;

//curl instance

private $curl;

public $status;

private $headers = array();

/**

* [__construct construction method, initialization data]

* @param [type] $url requested server address

* @param [type] $requestType Method to send request

* @param [type] $data The data sent

* @param integer $url_model routing request method

*/

public function __construct($url, $data = array(), $requestType = 'get') {

//url must be passed, and it must be a path that conforms to the PATHINFO mode

if (!$url) {

return false;

}

$this->requestType = strtolower($requestType);

$paramUrl = '';

//PATHINFO mode

if (!empty($data)) {

foreach ($data as $key => $value) {

$paramUrl.= $key . '=' . $value.'&';

}

$url = $url .'?'. $paramUrl;

}

//Initialize the data in the class

$this->url = $url;

$this->data = $data;

try{

if(!$this->curl = curl_init()){

throw new Exception('curl initialization error: ');

};

}catch (Exception $e){

echo '

';</p>
            <p>print_r($e->getMessage());</p>
            <p>echo '
';

}

curl_setopt($this->curl, CURLOPT_URL, $this->url);

curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);

}

/**

* [_post sets the parameters of get request]

* @return [type] [description]

*/

public function _get() {

}

/**

* [_post sets the parameters of the post request]

* post new resources

* @return [type] [description]

*/

public function _post() {

curl_setopt($this->curl, CURLOPT_POST, 1);

curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);

}

/**

* [_put set put request]

* put update resource

* @return [type] [description]

*/

public function _put() {

curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');

}

/**

* [_delete delete resource]

* delete delete resource

* @return [type] [description]

*/

public function _delete() {

curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');

}

/**

* [doRequest executes sending request]

* @return [type] [description]

*/

public function doRequest() {

//Send verification information to the server

if((null !== self::token) && self::token){

$this->headers = array(

'Client_Token: '.self::token,

'Client_Code: '.$this->setAuthorization()

);

}

//Send header information

$this->setHeader();

//How to send a request

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;

}

//Execute curl request

$info = curl_exec($this->curl);

//Get curl execution status information

$this->status = $this->getInfo();

return $info;

}

/**

* Set the header information sent

*/

private function setHeader(){

curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);

}

/**

* Generate authorization code

* @return string authorization code

*/

private function setAuthorization(){

$authorization = md5(substr(md5(self::token), 8, 24).self::token);

return $authorization;

}

/**

* Get status information in curl

*/

public function getInfo(){

return curl_getinfo($this->curl);

}

/**

* Close curl connection

*/

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>
            <p>print_r($info);</p>
            <p>echo '
';

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(); //Get status information in curl $status = $rest->status; echo '
';
            print_r($info);
            echo '
';

  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 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<🎜> <🎜>{<🎜> <🎜>/**<🎜> <🎜>* First execute the method in apiServer and initialize the data<🎜> <🎜>* @param object $obj The global object that can be passed in [database object, framework global object, etc.]<🎜> <🎜>*/<🎜> <🎜> <🎜> <🎜>private $obj;<🎜> <🎜> <🎜> <🎜>function __construct()//object $obj<🎜> <🎜>{<🎜> <🎜>parent::__construct();<🎜> <🎜>//$this->obj = $obj; //$this->resourse; 父类中已经实现,此类中可以直接使用 //$tihs->resourseId; 父类中已经实现,此类中可以直接使用 }   /** * Get resource operation * @return [type] [description] */ protected function _get(){ echo "get"; //逻辑代码根据自己实际项目需要实现 }   /** * Add new resource operation * @return [type] [description] */ protected function _post(){ echo "post"; //逻辑代码根据自己实际项目需要实现 }   /** * Delete resource operation * @return [type] [description] */ protected function _delete(){ //逻辑代码根据自己实际项目需要实现 }   /** * Update resource operation * @return [type] [description] */ protected function _put(){ echo "put"; //逻辑代码根据自己实际项目需要实现 } }   $server = new testServer();

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/998362.htmlTechArticlephp is based on curl extension to make a cross-platform restfule interface. This article mainly introduces php to make a cross-platform restfule interface based on curl extension. If you need relevant information and detailed code of the restfule interface...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template