php 模拟浏览器 发送 post 和 get 请求(兼容curl + file_get_contents)

php 模拟浏览器 发送 post 和 get 请求(兼容curl + file_get_contents)

function http_data($url,Array $data,$method='get')
{
    $time_out = 30;//超时时间
    if(!function_exists('curl_init'))  //如果不支持curl,使用file_get_content进行采集
    {
        $data_query = http_build_query($data);
        if('post' == strtolower($method))
        {
            $opts = array(  
                'http'=>array(
                    'method'=>"POST",
                    'timeout'=>$time_out,
                    'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
                              "Content-length:".strlen($data_query)."\r\n",
                    'content' => $data_query,
                )
            );
            $format_url = $url;
        }
        else
        {
            $opts = array(
                'http'=>array(
                    'method'=>"GET",
                    'timeout'=>$time_out,
                )
            );
            $format_url = $url . (strpos($url,'?')===false ? ('?'.$data_query) : ('&' . $data_query));
        }
        $cxContext = stream_context_create($opts);
        $response = file_get_contents($format_url, false, $cxContext);
    }
    else
    {
        $ch = curl_init();
        //初始化一个 CURL对象 
        curl_setopt($ch, CURLOPT_TIMEOUT, $time_out);
        curl_setopt($ch, CURLOPT_HEADER, false);   //设定是否显示头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置CURL 参数,要求结果保存到字符串中还是输出到屏幕上
        //curl_setopt($curl, CURLOPT_NOBODY, true);//设定是否输出页面内容 
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $time_out);

        if('post' == strtolower($method))
        {
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        else
        {
            $data_query = http_build_query($data);
            $format_url = $url . (strpos($url,'?')===false ? ('?'.$data_query) : ('&' . $data_query));
            curl_setopt($ch, CURLOPT_URL, $format_url);
        }
        $response = curl_exec($ch);
        // 关闭URL请求 
        curl_close($ch);
    }

    return $response;
}

以上为个人综合各种资料整理出来的,欢迎拍砖

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值