php curl Moved Permanently解決方法


以前使用curl時出現了Moved Permanently錯誤,紀錄一下解決方式。

當時的狀況是使用curl發送post時,curl_exec回來的資料無論怎樣都出現Moved Permanently,依照網路的答案調整寫法後即可。

參考資料:stackoverflow

增加/調整的參數

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTREDIR, 3);

整段程式(觸發後不等待回應)

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://目標位置');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTREDIR, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
										'sendid' => '資料'
									)));
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
$r = curl_exec($ch);
curl_close($ch);
Tags : php