I am trying to resolve long URLs from Twitter's short URLs, My function is,
public function expand_short_url($url = '')
{
if($url != '')
{
$headers = get_headers($url);
$headers = array_reverse($headers);
foreach($headers as $header) {
if (strpos($header, 'Location: ') === 0) {
$url = str_replace('Location: ', '', $header);
break;
}
}
}
return $url;
}
This function has a huge performance impact. I benchmark the JSON response,
Without resolving : 1.73 seconds
With URL resolving : 1.2 min
Any other suggestion, or faster way to resolve short urls?
Well, at first take a look at The media entity
section in Tweet Entities (you can get the expanded url with) if it helps. Also, by default get_headers uses a GET
(is slower than HEAD) request to fetch the headers. If you want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers('http://example.com');
Curl is even faster but I recommend you to read Resolve Short URLs To Their Destination URL with PHP (such as T.co, bit.ly & tinyurl.com), it could be very helpful, the title describes it clearly and i think this is exactly what you are looking for.