0%

PHP 常用

本着不想从各种源码中翻来覆去找函数方法,故将已经封装好的函数方法收集,方便用时直接复制。

Header 方法

1
2
3
4
error_reporting(0);
header('Access-Control-Allow-Origin: *');
header("Content-type: text/json; charset=utf-8");
header("Content-type: text/json; charset=GB2312");

正则方法

注意 $pattern 需要界定符和转义

1
2
3
4
5
function preg($pattern, $subject, $order)
{
preg_match_all($pattern, $subject, $_Return);
return $order == 0 ? $_Return : $_Return[$order];
}

输出方法

1
$json = json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_FORCE_OBJECT);

Http 方法

Get 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function curl_get($url)
{
$oCurl = curl_init();
if (stripos($url, "https://") !== FALSE) {
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurl, CURLOPT_COOKIE, '');
// curl_setopt($oCurl, CURLOPT_PROXY, "127.0.0.1");
// curl_setopt($oCurl, CURLOPT_PROXYPORT, "10809");
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if (intval($aStatus["http_code"]) == 200) {
return $sContent;
} else {
return false;
}
}

POST 请求

请求数据:数组 + http_build_query()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function curl_post($url, $data)
{

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$tmpInfo = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Errno' . curl_error($curl);
}
curl_close($curl);
return $tmpInfo;
}