file_get_contents僞造user_agent curl設置useragent的方法

file_get_contents 和 curl 這倆強悍的函數,在遠程抓取時候至關有用處.不過一些網站會根據來訪ip是否攜帶user_agent來判斷是正常的瀏覽器客戶端仍是機器.因此,咱們的任務就是給他們僞造user_agent.web


file_get_contents僞造user_agent 方法以下:
瀏覽器

ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;http://www.9qc.com)');服務器


curl僞造user_agent的方法:
curl

curl_setopt($c, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;http://www.9qc.com)'); 
函數



curl的完整函數方法:
網站

function curl_get_file_contents($URL)   
    {   
        $c = curl_init();   
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($c, CURLOPT_HEADER, 1);//輸出遠程服務器的header信息
curl_setopt($c, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;http://www.9qc.com)');
        curl_setopt($c, CURLOPT_URL, $URL);   
        $contents = curl_exec($c);   
        curl_close($c);
        if ($contents) {return $contents;}
            else {return FALSE;}
    }
這樣就能夠抓取了,user_agent能夠本身修改.  url


PS: (.*?):後面問號的意思是最少匹配(即懶惰匹配),若是沒有那個問號就會最多匹配(即貪婪匹配)。spa

相關文章
相關標籤/搜索