gpt4 book ai didi

php - 在 curl php 中获取最后一个重定向的 url

转载 作者:行者123 更新时间:2023-12-04 16:50:00 25 4
gpt4 key购买 nike

您好,我知道这是 StackOverFlow 上一个非常常见的话题。我已经花了整整一周的时间来搜索它。

我有一个网址:abc.com/default.asp?strSearch=19875379

这进一步重定向到这个 url:abc.com/default.asp?catid={170D4F36-39F9-4C48-88EB-CFC8DDF1F531}&details_type=1&itemid={49F6A281-8735-4B74-A170-B6110AF6CC2D}

我已努力使用 Curl 在我的 php 代码中获取最终 url,但无法成功。

这是我的代码:

<?php
$name="19875379";
$url = "http://www.ikea.co.il/default.asp?strSearch=".$name;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
curl_close( $ch );
// the returned headers
$headers = explode("\n",$a);
// if there is no redirection this will be the final url
$redir = $url;
// loop through the headers and check for a Location: str
$j = count($headers);
for($i = 0; $i < $j; $i++){
// if we find the Location header strip it and fill the redir var
//print_r($headers);
if(strpos($headers[$i],"Location:") !== false){
$redir = trim(str_replace("Location:","",$headers[$i]));
break;
}
}
// do whatever you want with the result
echo $redir;
?>

它给了我 url "abc.com/default.asp?strSearch=19875379"而不是这个 url "abc.com/default.asp?catid={170D4F36-39F9-4C48-88EB-CFC8DDF1F531}&details_type=1&itemid= {49F6A281-8735-4B74-A170-B6110AF6CC2D}”

在此先感谢您的帮助:)

最佳答案

谢谢大家在我的情况下帮助我。

实际上我想用 php 开发一个 scraper 用于以色列的宜家网站(希伯来语)。花了很多时间后,我意识到我用来获取重定向 URL 的 URL 中没有服务器端重定向。它可能是 javascript 重定向。我现在已经实现了下面的代码,它对我有用。

<?php
$name="19875379";
$url = "http://www.ikea.co.il/default.asp?strSearch=".$name;

$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$header = curl_exec($ch);
$redir = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
//print_r($header);

$x = preg_match("/<script>location.href=(.|\n)*?<\/script>/", $header, $matches);
$script = $matches[0];
$redirect = str_replace("<script>location.href='", "", $script);
$redirect = "http://www.ikea.co.il" . str_replace("';</script>", "", $redirect);

echo $redirect;
?>

再次感谢大家:)

关于php - 在 curl php 中获取最后一个重定向的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20582717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com