【问题标题】:Find where URL redirects to using PHP使用 PHP 查找 URL 重定向到的位置
【发布时间】:2014-03-31 15:53:39
【问题描述】:

我正在寻找 URL 重定向到的位置,目前我正在使用 file_get_contents() 获取网页信息,但有些页面返回 301/302 标头状态,我想使用函数来查找 url页面重定向到;

function page_info($url) {
$fp = file_get_contents($url);
$title = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches);
$h1 = preg_match("/<h1>(.*)<\/h1>/siU", $fp, $h1_matches);
$h2 = preg_match("/<h2>(.*)<\/h2>/siU", $fp, $h2_matches);
$meta_desc = get_meta_tags($url);
$data = array("title"=>trim(preg_replace('/\s+/', ' ', $title_matches[1])), "metadesc" => $meta_desc['description'],"h1"=>trim(preg_replace('/\s+/', ' ', $h1_matches[1])), "h2"=>trim(preg_replace('/\s+/', ' ', $h2_matches[1])));
return $data;
}

有什么方法可以找出重定向的 url,以便我可以在正确的 URL 上运行 page_info() 函数?

【问题讨论】:

标签: php redirect curl file-get-contents


【解决方案1】:

您需要使用 php curl 库。您可以将其设置为跟随重定向,然后使用 getinfo 方法找到我们的目的地。

$curl = curl_init('http://example.org/someredirect');
curl_setopt($curl, CURLOPT_POSTFIELDS, "foo");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_POST, true);

curl_exec($curl);

if(!curl_errno($curl))
{
     $info = curl_getinfo($curl);
}

您可以将第二个参数传递给 curl_getinfo 方法以获取更具体的信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多