PHP:如何扩展/收缩Tinyurls

2 php

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

Pau*_*xon 7

如果你想知道tinyurl的去向,可以使用fsockopen在端口80上获得与tinyurl.com的连接,并向它发送一个这样的HTTP请求

GET /dmsfm HTTP/1.0
Host: tinyurl.com
Run Code Online (Sandbox Code Playgroud)

你得到的回复看起来像

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
Run Code Online (Sandbox Code Playgroud)

示例代码...

<?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

}
?>
Run Code Online (Sandbox Code Playgroud)