PHP:如何扩展/收缩Tinyurls

时间:2020-03-05 18:53:18  来源:igfitidea点击:

在PHP中,如何在search.twitter.com上复制Tinyurls的扩展/收缩功能?

解决方案

回答

如果要找出tinyurl的去向,请使用fsockopen在端口80上连接tinyurl.com,并向其发送一个HTTP请求,如下所示

GET /dmsfm HTTP/1.0
Host: tinyurl.com

我们收到的回复看起来像

HTTP/1.0 301 Moved Permanently
Connection: close
X-Powered-By: PHP/5.2.6
Location: http://en.wikipedia.org/wiki/TinyURL
Content-type: text/html
Content-Length: 0
Date: Mon, 15 Sep 2008 12:29:04 GMT
Server: TinyURL/1.6

示例代码...

<?php
$tinyurl="dmsfm";

$fp = fsockopen("tinyurl.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET /$tinyurl HTTP/1.0\r\n";
    $out .= "Host: tinyurl.com\r\n";
    $out .= "Connection: Close\r\n\r\n";

    $response="";

    fwrite($fp, $out);
    while (!feof($fp)) {
        $response.=fgets($fp, 128);
    }
    fclose($fp);

    //now parse the Location: header out of the response

}
?>

回答

以下是使用TinyURL API收缩任意URL的方法。通用调用模式如下所示,它是带有参数的简单HTTP请求:

http://tinyurl.com/api-create.php?url=http://insertyourstuffhere.com

这将返回http://insertyourstuffhere.com的相应TinyURL。在PHP中,我们可以将其包装在fsockopen()调用中,或者为了方便起见,只需使用file()函数来检索它即可:

function make_tinyurl($longurl)
{
  return(implode('', file(
    'http://tinyurl.com/api-create.php?url='.urlencode($longurl))));
}

// make an example call
print(make_tinyurl('http://www.joelonsoftware.com/items/2008/09/15.html'));

回答

另一种简单的方法:

<?php
function getTinyUrl($url) {
return file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
}
?>

回答

当人们以编程方式回答了如何创建和解决tinyurl.com重定向时,我想(强烈地)提出一些建议:缓存。

在推特示例中,如果每次我们单击"扩展"按钮时,它都会对/api/resolve_tinyurl/http://tinyurl.com/abcd执行XmlHTTPRequest,则服务器会创建与tinyurl的HTTP连接.com,并检查了标头,该标头将破坏twitter和tinyurl的服务器。

一种更明智的方法是执行类似Python'y伪代码的操作。

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

缓存中的项目神奇地备份到内存和/或者文件中,而query_tinyurl()就像保罗·迪克森的答案一样工作。

回答

如果只需要该位置,则执行HEAD请求而不是GET。

$tinyurl  = 'http://tinyurl.com/3fvbx8';
$context  = stream_context_create(array('http' => array('method' => 'HEAD')));
$response = file_get_contents($tinyurl, null, $context);

$location = '';
foreach ($http_response_header as $header) {
    if (strpos($header, 'Location:') === 0) {
        $location = trim(strrchr($header, ' '));
        break;
    }
}
echo $location;
// http://www.pingdom.com/reports/vb1395a6sww3/check_overview/?name=twitter.com%2Fhome

回答

这是通过CURL库解码短网址的另一种方法:

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];
}

在这里描述。

回答

在PHP中,还有一个get_headers函数可用于解码微小的url。