php Curl 最完整封装

180it 2020-11-10 PM 1653℃ 0条

函数源码

<?php
/**
 * curl最完整封装
 * @param  String  $url     要请求的连接,支持https
 * @param  integer $post    post参数
 * @param  integer $referer url来源
 * @param  integer $cookie  cookie
 * @param  integer $header  是否显示响应头
 * @param  integer $ua      自定义ua头
 * @param  integer $nobody  是否显示响应体
 * @return String           响应的结果
 */
function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobody = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $httpheader[] = "Accept:*/*";
    $httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
    $httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
    $httpheader[] = "Connection:close";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    if ($header) {
        curl_setopt($ch, CURLOPT_HEADER, true);
    }
    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if ($referer) {
        curl_setopt($ch, CURLOPT_REFERER, $referer);
    }
    if ($ua) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0");
    }
    if ($nobody) {
        curl_setopt($ch, CURLOPT_NOBODY, 1);
    }
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}

使用示例

<?php
//get提交
$result = get_curl("http://www.moleft.cn");
//post提交
$result = get_curl("http://www.moleft.cn/api.php","key1=value1&key2=value2...");
//带来源提交
$result = get_curl("http://www.moleft.cn",0,"http://moleft.cn");
//带cookie提交
$result = get_curl("http://www.moleft.cn/api.php",0,0,"name=value;name2=value2;...");
//显示响应头
$result = get_curl("http://www.moleft.cn",0,0,0,1);
//不显示响应体
//如果$header为0并且$nobody为1,则返回的是空
$result = get_curl("http://www.moleft.cn",0,0,0,1,0,1);
//自定义ua提交
//ua头可以去百度搜索,这里模拟的是IE9
$result = get_curl("http://www.moleft.cn/api.php",0,0,0,0,"User-Agent,Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;");

利用 php 获取 ua 头
方法:新建一个 php 文件,填写以下代码

<?php
//利用php获取ua
echo $_SERVER['HTTP_USER_AGENT'];
?>
ua 的更多用法
可以利用 ua 来判断是否为 QQ / 微信的内置浏览器

//更多浏览器自行探索
if(strpos($_SERVER['HTTP_USER_AGENT'], 'QQ/')!==false){
    echo "这是QQ内置的浏览器";
}else if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')!==false){
    echo "这是微信的内置浏览器"
}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php Curl 最完整封装