0

希望我只是忽略了这一点。

我正在尝试使用 PHP 获取重定向链接的目标 URL。这是为了获取附属/隐藏链接的站点 URL。

最好的例子: http ://tinyurl.com/2tx去 google.com

注意:这是一个示例,链接是动态创建的

现在我通过 URL

www.mysite.com/redirect.php?link=http://tinyurl.com/2tx

这是来自该站点的代码 - 注意:由于 URL 中包含与号,因此我必须通过 GET 走这条路线。

<?php
    $name = http_build_query($_GET);
    // which you would then may want to strip away the first 'name='
    $name = substr($name, strlen('name='));
    //change link to a nice URL
    $url = rawurldecode($name);
?>

我有一个抓取 URL 的简单脚本,如何处理 URL 以获取目标 URL?

希望这不会太令人困惑。

干杯,罗伯

4

4 回答 4

4

下次您应该发布一些代码。我假设您正在使用cURL它来执行此操作。这很简单:

//sanitize
$ch = curl_init($_GET['link']);

//follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_exec($ch);

$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

编辑:根据 Dagon,您只想“知道网址但不去那里”。如果您只需要知道 url 而不需要获取其内容,则使用此设置会更有效:

curl_setopt($ch, CURLOPT_NOBODY, true);
于 2012-12-04T22:02:20.380 回答
0

向您拥有的 URL 发出 HTTP HEAD 请求。您将收到带有目标 URL 的 HTTP 301 或 302 响应。

示例:将您的 URL 放在这里以查看发出 HTTP 头请求时返回的响应。

于 2012-12-04T22:02:47.790 回答
0

这可能是编码问题。您的 URL 中的参数未编码,因此在尝试使用 $_GET 获取它时可能已损坏。

你想使用这个 URL:

www.mysite.com/redirect.php?link=http%3A%2F%2Ftinyurl.com%2F2tx

urlencode()您可以使用该函数在 PHP 中对 URL 变量进行编码。现在可以像这样访问(我认为)您想要的变量:

echo $_GET['link'];  // http://tinyurl.com/2tx
于 2012-12-04T22:36:24.907 回答
0

这是我的做法(阅读评论):

<?php

// Connect to the page:
$ch = curl_init("http://tinyurl.com/2tx");

// Don't get the body (remove if you want the body):
curl_setopt($ch, CURLOPT_NOBODY, true);

// Follow the page redirects:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

// Retun the data as a string (Remove to echo to the page):
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute:
curl_exec($ch);

// Get data:
print_r($data = curl_getinfo($ch));

// Get just the url:
echo $data["url"];
于 2012-12-04T22:43:01.197 回答