我正在使用 cURL 库开发 php 应用程序。
我想获得重定向 url(以防 301 或 302 http 代码)。在 Windows 中很简单,我只需要调用 curl_getinfo($ch)。此方法返回带有 redirect_url 的关联数组,我稍后将使用它。
当我将我的应用程序移动到 Linux 服务器时遇到问题。这种方法(curl_getinfo)也返回数组,但没有“redirect_url”索引。我虽然可以尝试将 header 读取为字符串。我设置了
curl_setopt(CURLOPT_HEADERFUNCTION, callback)
并将响应 header 保存为字符串。然后我使用简单的解析器来获取我感兴趣的字段。但是现在我有另一个问题。重定向 url(http header LOCATION)返回相对 url(而在 Windows 中它是绝对的)。
为什么windows cURL 和linux 有差异?我该怎么做才能使此应用程序抵抗操作系统更改?最后,如何在 linux 中将此字段(重定向 url)作为绝对 url。
感谢您的帮助:)
来自 Windows 的示例:
Array
(
[url] => http:// wiadomosci.wp.pl/kat,1342,title,Ciag-dalszy-sporu-wokol-poslow-PiS-Nie-moge-tego-zrobic,wid,13927471,wiadomosc.html
[content_type] => text/html
[http_code] => 302
[header_size] => 2407
[request_size] => 384
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.046
[namelookup_time] => 0
[connect_time] => 0.015
[pretransfer_time] => 0.015
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0.046
[redirect_time] => 0
[certinfo] => Array
(
)
[redirect_url] => http:// wiadomosci.wp.pl/kat,1342,title,Ciag-dalszy-sporu-wokol- poslow-PiS-Nie-moge-tego-zrobic,wid,13927471,wiadomosc.html?ticaid=1d436
)
和窗口:
Array
(
[url] => http:// wiadomosci.wp.pl/kat,1342,title,Ciag-dalszy-sporu-wokol-poslow-PiS-Nie-moge-tego-zrobic,wid,13927471,wiadomosc.html
[content_type] => text/html
[http_code] => 302
[header_size] => 2425
[request_size] => 384
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.023254
[namelookup_time] => 0.001938
[connect_time] => 0.004836
[pretransfer_time] => 0.004847
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0.023068
[redirect_time] => 0
[certinfo] => Array
(
)
)
最佳答案
有一个替代解决方案适用于每个(当前支持的)操作系统。
您可以要求 curl 跟随重定向并将其限制为一个深度,然后使用 curl_getinfo($ch); 中的 url 键;
例子:
<?php
$url = 'http://jigsaw.w3.org/HTTP/300/301.html';
$expectedUrl = 'http://jigsaw.w3.org/HTTP/300/Overview.html';
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 1);
$content = curl_exec( $ch );
$response = curl_getinfo( $ch );
curl_close ( $ch );
if ($response['url'] == $expectedUrl)
echo "I have the correct redirect url\n";
else
echo "I do not have the correct redirect url\n";
如果您只想要结束 url,无论可能有多少重定向,您都可以删除 CURLOPT_MAXREDIRS 选项(或将其设置为高以防止循环)
关于php - cURL 响应 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7889334/