php实现访问远程url的方式有很多种,例如用file_get_contents方式获取内容;用fopen打开ur方式获取内容;用fsockopen函数打开url方式获取等等。不过最推荐的还是使用curl进行访问。
<?php
/**
* =======================================
* created by zhihua_w.
* author: zhihua_w
* date: 2016/12/12 0008
* time: 下午 2:17
* project: php开发小技巧
* power: curl请求
* =======================================
*/
/**
* curl请求
* @param $url 请求url地址
* @param $method 请求方法 get post
* @param null $postfields post数据数组
* @param array $headers 请求header信息
* @param bool|false $debug 调试开启 默认false
* @return mixed
*/
function httprequest($url, $method, $postfields = null, $headers = array(), $debug = false)
{
$method = strtoupper($method);
$ci = curl_init();
/* curl settings */
curl_setopt($ci, curlopt_http_version, curl_http_version_1_0);
curl_setopt($ci, curlopt_useragent, "mozilla/5.0 (windows nt 6.2; wow64; rv:34.0) gecko/20100101 firefox/34.0");
curl_setopt($ci, curlopt_connecttimeout, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
curl_setopt($ci, curlopt_timeout, 7); /* 设置curl允许执行的最长秒数 */
curl_setopt($ci, curlopt_returntransfer, true);
switch ($method) {
case "post":
curl_setopt($ci, curlopt_post, true);
if (!empty($postfields)) {
$tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
curl_setopt($ci, curlopt_postfields, $tmpdatastr);
}
break;
default:
curl_setopt($ci, curlopt_customrequest, $method); /* //设置请求方式 */
break;
}
$ssl = preg_match('/^https:\/\//i', $url) ? true : false;
curl_setopt($ci, curlopt_url, $url);
if ($ssl) {
curl_setopt($ci, curlopt_ssl_verifypeer, false); // https请求 不验证证书和hosts
curl_setopt($ci, curlopt_ssl_verifyhost, false); // 不从证书中检查ssl加密算法是否存在
}
//curl_setopt($ci, curlopt_header, true); /*启用时会将头文件的信息作为数据流输出*/
curl_setopt($ci, curlopt_followlocation, 1);
curl_setopt($ci, curlopt_maxredirs, 2);/*指定最多的http重定向的数量,这个选项是和curlopt_followlocation一起使用的*/
curl_setopt($ci, curlopt_httpheader, $headers);
curl_setopt($ci, curlinfo_header_out, true);
/*curl_setopt($ci, curlopt_cookie, $cookiestr); * *cookie带过去** */
$response = curl_exec($ci);
$requestinfo = curl_getinfo($ci);
$http_code = curl_getinfo($ci, curlinfo_http_code);
if ($debug) {
echo "=====post data======\r\n";
var_dump($postfields);
echo "=====info===== \r\n";
print_r($requestinfo);
echo "=====response=====\r\n";
print_r($response);
}
curl_close($ci);
return $response;
//return array($http_code, $response,$requestinfo);
}
$url = "http://zhutuan.chuangkeweilai.cn/jiancai/admin/index.php?act=cache&op=kppwcache";
httprequest($url, $method, $postfields = null, $headers = array(), $debug = true)
?>
相关文章:
php利用curl发起get请求时url的参数问题
php中的使用curl发送请求(get请求和post请求)
php使用curl函数发送post请求的注意事项实例详解
以上就是php开发技巧(八)-curl请求的代码详情的详细内容。