前言
前端可以發送請求,後端也可以,php裏的curl提供了這個操作,下面是我封裝的curl,支持post和get方式,大家覺得寫得還不錯可以直接拿來用哦
正文
private static function doCurl($url, Array $data = [], $isPost = 0, $header = [], $timeOut = 25, $cookie = '')
{
$ch = curl_init();
if ( $isPost ) {
curl_setopt($ch, CURLOPT_POST, $isPost);
$dataFormat = true;
foreach($header as $value) {
if (strpos($value, 'application/json') !== false) $dataFormat = false;
}
if ( $dataFormat ) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} else {
if ( $data ) {
$url .= strpos($url, '?') !== false ? '&' : '?';
$url .= http_build_query($data);
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , $timeOut);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
最後
謝謝大家的閱讀,原創不易,喜歡就點個贊,這將是我最強的寫作動力。如果你覺得文章對你有所幫助,也蠻有趣的,就關注一下我的博客,謝謝。