curl请求封装函数

发表于

1.get

 public function get($url, $cookie_file='', $isCookiesSave = false)
    {
        $proxy = "http://xxxx.xxxxx.xxxxx";
        // 初始化
        $curl = curl_init($url);
        curl_setopt ($curl, CURLOPT_PROXY, $proxy);
        $header = array();
        $header[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36';
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        // 不输出header头信息
        curl_setopt($curl, CURLOPT_HEADER, 0);
        if ($isCookiesSave) {
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_file); // 存储cookies
        } else {
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file);
        }
        // 保存到字符串而不是输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 是否抓取跳转后的页面
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        $info = curl_exec($curl);
        curl_close($curl);
        return $info;
    }

2.post

    function post($url, $data, $cookie_file)
    {
        $proxy = "http://xxxx.xxxx.xxxxxx";
        // 初始化
        $curl = curl_init($url);
        curl_setopt ($curl, CURLOPT_PROXY, $proxy);
        $header = array();
        $header[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36';
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        // 不输出header头信息
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 保存到字符串而不是输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file);
        // post数据
        curl_setopt($curl, CURLOPT_POST, 1);
        // 请求数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        // 是否抓取跳转后的页面
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        $response = curl_exec($curl);
        $rinfo=curl_getinfo($curl);
        $realurl = $rinfo['url'];

        curl_close($curl);
        return $realurl;
    }

根据实际需求更改

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注