php用crul请求url资源方法makeRequest()

来源:互联网 发布:linux配置多个tomcat 编辑:程序博客网 时间:2024/06/08 07:55
function makeRequest($url, $argument = array(), $ttl = 5, $method = "GET", $cookie='', $follow=0){

    if (!$url) {
        throw new LogicException('$url不能为空');
    }

    if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://') {
        return array('result' => NULL, 'code' => '400');
    }
    if ($method == 'GET' && count($argument) > 0) {
        $url .= "?" . (http_build_query($argument));
        //echo $url;
    }
    $header = array(
        'Accept-Language: zh-cn,zh;q=0.8',
        'Connection: Keep-alive',
        'Cache-Control: max-age=0'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $argument);
    }
    if( file_exists($cookie) ){
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $ttl);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1707.0 Safari/537.36');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    if( $follow==1 ){
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    }
    $return = array();
    $return['result'] = curl_exec($ch);
    $return['code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    unset($ch);

    return $return;
}
0 0
原创粉丝点击