如何使用php或javascript检测自动重定向url?

时间:2016-11-24 03:39:56

标签: javascript php

使用PHP或JavaScript,如何检测用户何时提供重定向网址:

goo.gl/Vmnf

2 个答案:

答案 0 :(得分:0)

列出所有重定向网站,并针对这些网站检查网址。

$redirecters = array("goo.gl", "tinyurl.com", ...);
$domain = parse_url($url, PHP_URL_HOST);
if (in_array($domain, $redirecters)) {
    echo "That's a redirect URL!";
}

答案 1 :(得分:0)

此代码利用cURL根据定义的阈值跟踪任意重定向,以确定是否缩短了URL:

!defined('THRESHOLD')?define('THRESHOLD',2):null;
$i = 0;
$url = 'goo.gl/Vmnf';
while ($i<THRESHOLD)
{
    $ch = curl_init();

    // set URL and other appropriate options
    $options = array(CURLOPT_URL => $url,
                     CURLOPT_HEADER => true,
                     CURLOPT_CRLF => true,
                     CURLOPT_FOLLOWLOCATION => false,
                     CURLOPT_FRESH_CONNECT => true,
                     CURLOPT_TCP_NODELAY => true,
                     CURLOPT_RETURNTRANSFER => true,
                    );

    curl_setopt_array($ch, $options);

    // grab URL and pass it to the browser
    $trans = curl_exec($ch);

    // close cURL resource, and free up system resources
    curl_close($ch);

    // Processing
    preg_match('/^(?P<header>.*?)(?:\r?\n){2}(?P<body>.*)?$/s', $trans, $ptrans);
    if(empty($ptrans['header'])) break;
    $headers = preg_split('/\r?\n/', $ptrans['header']);
    preg_match('/^HTTP\/(?P<http_varsion>.*?)\s(?P<http_code>.*?)\s(?P<http_description>.*)?$/m', $headers[0], $matches);
    unset($headers[0]);
    if ((int)($matches['http_code']/100) != 3)
    {
        break;
    }
    for($j = 1; $j < count($headers); $j++)
    {
        preg_match('/^(?P<name>.*?):\s+(?P<value>.*)$/',$headers[$j], $header);
        $headers[$header['name']] = $header['value'];
        unset($headers[$j]);
    }
    $http = [
        'version' => $matches['http_varsion'],
        'code' => $matches['http_code'],
        'description' => $matches['http_description'],
        'header' => $headers,
        'body' => $ptrans['body'],
    ];
    if (empty($http['header']['Location']))
        break;
    $url = $http['header']['Location'];
    $i++;
}
echo $i;