简体   繁体   中英

How to detect auto redirect url using php or javascript?

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

goo.gl/Vmnf

Make a list of all the redirect sites, and check the domain of the URL against them.

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

This code utilises cURL to follow arbitrary redirects based on defined threshold to determine if the URL is shortened:

!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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM