PHP封装HTTP操作类支持POST和GET

PHP封装HTTP操作类支持POST和GET

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
class Helper_Http
{
public static function get($url, $header = array(),&$setcookie = '', $proxy = '')
{
$ch = curl_init();
$needheader = empty($setcookie) ? 0 : 1;
$opt = array(
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 0,
CURLOPT_HEADER=>$needheader
);
!empty($proxy) && $opt[CURLOPT_PROXY] = $proxy;
//$header=array('Content-type: text/plain', 'Content-length: 100')
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt_array($ch, $opt);
$result = curl_exec($ch);
if ($needheader == 1) {
list($header, $body) = explode("\r\n\r\n", $result, 2);
preg_match_all('/Set-Cookie:(.*);/iU', $header, $str);
if (!empty($str[1])) {
$setcookie = implode('; ', $str[1]) . ";";
}
return $body;
}
return $result;
}
public static function post($url, $data, $header = array(),&$setcookie = '', $proxy = '')
{
$ch = curl_init();
$needheader = empty($setcookie) ? 0 : 1;
$opt = array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data,
CURLOPT_URL => $url,
CURLOPT_FOLLOWLOCATION=>0,
CURLOPT_HEADER=>$needheader
);
!empty($proxy) && $opt[CURLOPT_PROXY] = $proxy;
//$header=array('Content-type: text/plain', 'Content-length: 100')
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt_array($ch, $opt);
$result = curl_exec($ch);
if ($needheader == 1) {
list($header, $body) = explode("\r\n\r\n", $result, 2);
preg_match_all('/Set-Cookie: (.*;)/iU', $header, $str);
if (!empty($str[1])) {
$setcookie = implode('; ', $str[1]) . ";";
}
return $body;
}
return $result;
}
}