PHP: How to expand/contract Tinyurls

2020-06-25 05:15发布

In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com?

标签: php
8条回答
不美不萌又怎样
2楼-- · 2020-06-25 05:41

Here is another way to decode short urls via CURL library:

function doShortURLDecode($url) {
    $ch = @curl_init($url);
    @curl_setopt($ch, CURLOPT_HEADER, TRUE);
    @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
    @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $response = @curl_exec($ch);
    preg_match('/Location: (.*)\n/', $response, $a);
    if (!isset($a[1])) return $url;
    return $a[1];
}

It's described here.

查看更多
爷的心禁止访问
3楼-- · 2020-06-25 05:45

As people have answered programatically how to create and resolve tinyurl.com redirects, I'd like to (strongly) suggest something: caching.

In the twitter example, if every time you clicked the "expand" button, it did an XmlHTTPRequest to, say, /api/resolve_tinyurl/http://tinyurl.com/abcd, then the server created a HTTP connection to tinyurl.com, and inspected the header - it would destroy both twitter and tinyurl's servers..

An infinitely more sensible method would be to do something like this Python'y pseudo-code..

def resolve_tinyurl(url):
    key = md5( url.lower_case() )
    if cache.has_key(key)
        return cache[md5]
    else:
        resolved = query_tinyurl(url)
        cache[key] = resolved
        return resolved

Where cache's items magically get backed up into memory, and/or a file, and query_tinyurl() works as Paul Dixon's answer does.

查看更多
登录 后发表回答