curl 获取内容 get and post

public static function   getData($url, $method = 'get', $post_data = null)
    {

//        print_r("   <a target='_blank' href='$url'>$url</a><br>");
        return file_get_contents($url);
        $url = trim($url);
        $timeout = 20;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13');
        curl_setopt($curl, CURLOPT_HEADER, false); //设定是否显示头信息
//        curl_setopt($curl, CURLOPT_NOBODY, false); //设定是否输出页面内容

        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout); //在发起连接前等待的时间

//        Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3
//Accept-Language:zh-CN,zh;q=0.8


        $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3";
        $header[] = "Accept-Language: zh-CN,zh;q=0.8";
        $header[] = "Pragma: "; // browsers keep this blank.


        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); //设置cURL允许执行的最长秒数
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        if ($method === 'post') {
            if (!empty($post_data)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
            }
            curl_setopt($curl, CURLOPT_POST, 1);
            ob_start();
            curl_exec($curl);
            $content = ob_get_contents();
            ob_end_clean();
        } else {
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //post 无法使用
            $content = curl_exec($curl);
        }
        curl_close($curl);
        return $content;
    }

你可能感兴趣的:(curl 获取内容 get and post)