28c08be5625baaaae134156efef35b9d

Using HTTP HEAD request for better performance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

    // tinyurl.php?c=

    $num = $_GET['c'];

    if($fp = fsockopen ("tinyurl.com", 80, $errno, $errstr, 30))
    {
    if ($fp) {
    fputs ($fp, "HEAD /$num HTTP/1.0\r\nHost: tinyurl.com\r\n\r\n");
    while (!feof($fp)) {$headers .= fgets ($fp,128);}
    fclose ($fp);
    }
    $arr1=explode("Location:",$headers);
    $arr=explode("\n",trim($arr1[1]));
    echo trim($arr[0]);
    }
?>

Refactorings

No refactoring yet !

Avatar

KangOl

October 27, 2007, October 27, 2007 09:49, permalink

No rating. Login to rate!
Avatar

Meir

October 28, 2007, October 28, 2007 10:21, permalink

No rating. Login to rate!
1
2
3
4
5
6
7
8
<?php

$url     = 'http://tinyurl.com/'.$_GET['n'];
$headers = get_headers($url, true);

echo $headers['Location'][0];

?>
Ae0689b76b0fa370800323a71742c24f

Hubert Roksor

November 6, 2007, November 06, 2007 18:25, permalink

No rating. Login to rate!

Meir's solution looks good, and if you really want to use HEAD you can change the default context. Note: you should also make sure that $_GET['c'] contains a valid TinyURL token, otherwise your service may be used as a relay for DDOS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

if (preg_match('#^[a-z0-9]$#Di', $_GET['n']))
{
	stream_context_get_default(array(
		'http' => array(
			'method' => 'HEAD'
		)
	));

	$url     = 'http://tinyurl.com/'.$_GET['n'];
	$headers = get_headers($url, 1);

	echo $headers['Location'][0];
}

Your refactoring





Format Copy from initial code

or Cancel