백엔드 개발 PHP 튜토리얼 PHP实现支持GET,POST,Multipart/form-data的HTTP请求类_PHP

PHP实现支持GET,POST,Multipart/form-data的HTTP请求类_PHP

May 31, 2016 pm 07:29 PM
http php 친절한 묻다

本文实例讲述了PHP实现支持GET,POST,Multipart/form-data的HTTP请求类及其应用,分享给大家供大家参考。具体如下:

HttpRequest.class.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

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

<&#63;php

/** HttpRequest class, HTTP请求类,支持GET,POST,Multipart/form-data

*  Date:  2013-09-25

*  Author: fdipzone

*  Ver:  1.0

*

*  Func:

*  public setConfig   设置连接参数

*  public setFormdata  设置表单数据

*  public setFiledata  设置文件数据

*  public send     发送数据

*  private connect    创建连接

*  private disconnect  断开连接

*  private sendGet    get 方式,处理发送的数据,不会处理文件数据

*  private sendPost   post 方式,处理发送的数据

*  private sendMultipart multipart 方式,处理发送的数据,发送文件推荐使用此方式

*/

  

class HttpRequest{ // class start

  

  private $_ip = '';

  private $_host = '';

  private $_url = '';

  private $_port = '';

  private $_errno = '';

  private $_errstr = '';

  private $_timeout = 15;

  private $_fp = null;

    

  private $_formdata = array();

  private $_filedata = array();

  

  

  // 设置连接参数

  public function setConfig($config){

    $this->_ip = isset($config['ip'])&#63; $config['ip'] : '';

    $this->_host = isset($config['host'])&#63; $config['host'] : '';

    $this->_url = isset($config['url'])&#63; $config['url'] : '';

    $this->_port = isset($config['port'])&#63; $config['port'] : '';

    $this->_errno = isset($config['errno'])&#63; $config['errno'] : '';

    $this->_errstr = isset($config['errstr'])&#63; $config['errstr'] : '';

    $this->_timeout = isset($confg['timeout'])&#63; $confg['timeout'] : 15;

  

    // 如没有设置ip,则用host代替

    if($this->_ip==''){

      $this->_ip = $this->_host;

    }

  }

  

  // 设置表单数据

  public function setFormData($formdata=array()){

    $this->_formdata = $formdata;

  }

  

  // 设置文件数据

  public function setFileData($filedata=array()){

    $this->_filedata = $filedata;

  }

  

  // 发送数据

  public function send($type='get'){

  

    $type = strtolower($type);

  

    // 检查发送类型

    if(!in_array($type, array('get','post','multipart'))){

      return false;

    }

  

    // 检查连接

    if($this->connect()){

  

      switch($type){

        case 'get':

          $out = $this->sendGet();

          break;

  

        case 'post':

          $out = $this->sendPost();

          break;

  

        case 'multipart':

          $out = $this->sendMultipart();

          break;

      }

  

      // 空数据

      if(!$out){

        return false;

      }

  

      // 发送数据

      fputs($this->_fp, $out);

  

      // 读取返回数据

      $response = '';

  

      while($row = fread($this->_fp, 4096)){

        $response .= $row;

      }

  

      // 断开连接

      $this->disconnect();

  

      $pos = strpos($response, "\r\n\r\n");

      $response = substr($response, $pos+4);

  

      return $response;

  

    }else{

      return false;

    }

  }

  

  // 创建连接

  private function connect(){

    $this->_fp = fsockopen($this->_ip, $this->_port, $this->_errno, $this->_errstr, $this->_timeout);

    if(!$this->_fp){

      return false;

    }

    return true;

  }

  

  // 断开连接

  private function disconnect(){

    if($this->_fp!=null){

      fclose($this->_fp);

      $this->_fp = null;

    }

  }

  

  // get 方式,处理发送的数据,不会处理文件数据

  private function sendGet(){

  

    // 检查是否空数据

    if(!$this->_formdata){

      return false;

    }

  

    // 处理url

    $url = $this->_url.'&#63;'.http_build_query($this->_formdata);

      

    $out = "GET ".$url." http/1.1\r\n";

    $out .= "host: ".$this->_host."\r\n";

    $out .= "connection: close\r\n\r\n";

  

    return $out;

  }

  

  // post 方式,处理发送的数据

  private function sendPost(){

  

    // 检查是否空数据

    if(!$this->_formdata && !$this->_filedata){

      return false;

    }

  

    // form data

    $data = $this->_formdata&#63; $this->_formdata : array();

  

    // file data

    if($this->_filedata){

      foreach($this->_filedata as $filedata){

        if(file_exists($filedata['path'])){

          $data[$filedata['name']] = file_get_contents($filedata['path']);

        }

      }

    }

  

    if(!$data){

      return false;

    }

  

    $data = http_build_query($data);

  

    $out = "POST ".$this->_url." http/1.1\r\n";

    $out .= "host: ".$this->_host."\r\n";

    $out .= "content-type: application/x-www-form-urlencoded\r\n";

    $out .= "content-length: ".strlen($data)."\r\n";

    $out .= "connection: close\r\n\r\n";

    $out .= $data;

  

    return $out;

  }

  

  // multipart 方式,处理发送的数据,发送文件推荐使用此方式

  private function sendMultipart(){

  

    // 检查是否空数据

    if(!$this->_formdata && !$this->_filedata){

      return false;

    }

  

    // 设置分割标识

    srand((double)microtime()*1000000);

    $boundary = '---------------------------'.substr(md5(rand(0,32000)),0,10);

  

    $data = '--'.$boundary."\r\n";

  

    // form data

    $formdata = '';

  

    foreach($this->_formdata as $key=>$val){

      $formdata .= "content-disposition: form-data; name=\"".$key."\"\r\n";

      $formdata .= "content-type: text/plain\r\n\r\n";

      if(is_array($val)){

        $formdata .= json_encode($val)."\r\n"; // 数组使用json encode后方便处理

      }else{

        $formdata .= rawurlencode($val)."\r\n";

      }

      $formdata .= '--'.$boundary."\r\n";

    }

  

    // file data

    $filedata = '';

  

    foreach($this->_filedata as $val){

      if(file_exists($val['path'])){

        $filedata .= "content-disposition: form-data; name=\"".$val['name']."\"; filename=\"".$val['filename']."\"\r\n";

        $filedata .= "content-type: ".mime_content_type($val['path'])."\r\n\r\n";

        $filedata .= implode('', file($val['path']))."\r\n";

        $filedata .= '--'.$boundary."\r\n";

      }

    }

  

    if(!$formdata && !$filedata){

      return false;

    }

  

    $data .= $formdata.$filedata."--\r\n\r\n";

  

    $out = "POST ".$this->_url." http/1.1\r\n";

    $out .= "host: ".$this->_host."\r\n";

    $out .= "content-type: multipart/form-data; boundary=".$boundary."\r\n";

    $out .= "content-length: ".strlen($data)."\r\n";

    $out .= "connection: close\r\n\r\n";

    $out .= $data;

  

    return $out;

  }

} // class end

  

&#63;>

로그인 후 복사

demo示例程序如下:

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

<&#63;php

require('HttpRequest.class.php');

  

$config = array(

      'ip' => 'demo.fdipzone.com', // 如空则用host代替

      'host' => 'demo.fdipzone.com',

      'port' => 80,

      'errno' => '',

      'errstr' => '',

      'timeout' => 30,

      'url' => '/getapi.php',

      //'url' => '/postapi.php',

      //'url' => '/multipart.php'

);

  

$formdata = array(

  'name' => 'fdipzone',

  'gender' => 'man'

);

  

$filedata = array(

  array(

    'name' => 'photo',

    'filename' => 'photo.jpg',

    'path' => 'photo.jpg'

  )

);

  

$obj = new HttpRequest();

$obj->setConfig($config);

$obj->setFormData($formdata);

$obj->setFileData($filedata);

$result = $obj->send('get');

//$result = $obj->send('post');

//$result = $obj->send('multipart');

  

echo '<pre class="brush:php;toolbar:false">';

print_r($result);

echo '

로그인 후 복사
'; ?>

完整实例代码可以点击此处本站下载。

希望本文所述对大家的PHP程序设计有所帮助。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

CakePHP 날짜 및 시간 CakePHP 날짜 및 시간 Sep 10, 2024 pm 05:27 PM

CakePHP 날짜 및 시간

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드

CakePHP 파일 업로드 CakePHP 파일 업로드 Sep 10, 2024 pm 05:27 PM

CakePHP 파일 업로드

CakePHP 라우팅 CakePHP 라우팅 Sep 10, 2024 pm 05:25 PM

CakePHP 라우팅

CakePHP 토론 CakePHP 토론 Sep 10, 2024 pm 05:28 PM

CakePHP 토론

CakePHP 프로젝트 구성 CakePHP 프로젝트 구성 Sep 10, 2024 pm 05:25 PM

CakePHP 프로젝트 구성

CakePHP 빠른 가이드 CakePHP 빠른 가이드 Sep 10, 2024 pm 05:27 PM

CakePHP 빠른 가이드

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법

See all articles