我在 php 中很新。目前我面临着关于 php curl post 和重定向的问题。我写了很多代码来连接跨域 api。在此 API 中,响应会将我的页面重定向到另一个页面。
所以,现在我面临的是我也无法遵循 api 响应。 这意味着在我的 php 脚本中,我的 curl 收到了重定向页面的网页内容,但我的页面仍然存在。
请问php curl可以跟随API重定向吗?
有人知道如何解决这个问题吗?
下面是我的代码。
$url = "http://www.google.com.my"; //example this is an API
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_REFERER, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_string)));
$result = curl_exec($ch);
$response = curl_getinfo($ch);
curl_close($ch);
在 $result 中,我收到了 API 重定向页面。但它只是网络内容。
最佳答案
将 CURLOPT_FOLLOWLOCATION
设置为 true
以使 cURL 跟随重定向。
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
关于PHP CURL 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40148636/