function fetchURL($url, $postmode=false, $postdata=array()) {
// CURL 參數
$tmpf = tmpfile();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_FILE => $tmpf,
CURLOPT_ENCODING => \'deflate,gzip\', // !! 讓 cURL 自動解壓縮
CURLOPT_HTTPHEADER => array(
\'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)\',
\'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\',
\'Accept-Language: zh-tw,en-us;q=0.7,en;q=0.3\',
\'Accept-Charset: UTF-8,*\',
\'Keep-Alive: 115\',
\'Connection: keep-alive\',
\'Cookie: wd=1440x682\',
\'Cache-Control: max-age=0\'
)
);
// 處理 POST 欄位
if($postmode) {
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $this->encodePostData($postdata);
}
// 執行 CURL
$ch = curl_init();
curl_setopt_array($ch,$options);
curl_exec($ch);
curl_close($ch);
// 讀暫存檔
$httpall = \'\';
fseek($tmpf,0);
while(!feof($tmpf)) $httpall.=fread($tmpf,8192);
fclose($tmpf);
// Header/Body 分離
$nlx2 = strpos($httpall,"\\r\\n\\r\\n");
if($nlx2>0) {
$httpheader = substr($httpall,0,$nlx2);
$httpbody = substr($httpall,$nlx2+4);
} else {
$httpheader = $httpall;
$httpbody = \'\';
}
// 分析 Header 內容
$headers = array();
$response = array();
//$lines = split("\\r\\n",$httpheader);
$lines = preg_split(\'/\\r\\n/\',$httpheader);
if(preg_match(\'/HTTP\\/[0-9]\\.[0-9] ([0-9]+) (.+)/\',$lines[0],$matches)) {
$response[\'STATUS_CODE\'] = $matches[1];
$response[\'STATUS_DESC\'] = $matches[2];
for($i=1;$i $kvstr = $lines[$i];
$semi = strpos($kvstr,\':\');
$key = trim(substr($kvstr,0,$semi));
$val = trim(substr($kvstr,$semi+1));
$headers[$key] = $val;
}
$response[\'HEADERS\'] = $headers;
$response[\'BODY\'] = $httpbody;
} else {
$response[\'STATUS_CODE\'] = \'999\';
$response[\'STATUS_DESC\'] = \'Unknown Error\';
}
return $response;
}
|