Tinyurl API Example – Am i doing it right :D

we use super-long Hashes for the Registration of new Users in our Application. The Problem is that these Hashes break in some Email Clients – making the Links unusable.

I tried implementing the Tinyurl – API, with a simple Call, but i think it times out sometimes … sometimes the mail does not reach the user.

I updated the Code, but now the URL is never converted. Is Tinyurl really so slow or am i doing something wrong? (I mean hey, 5 Seconds is much in this Times)

Can anybody recommend me a more reliable service?

All my Fault, forgot a false in the fopen. But i will leave this sample of code here, because i often see this sample, wich i think does not work very reliable:

return file_get_contents('http://tinyurl.com/api-create.php?url='.$u);

This is the – i think fully working sample. I would like to hear about Improvements.

static function gettinyurl( $url ) {

    $context =
                'http' => array(
                    'timeout' => 5  // 5 Seconds should be enough

    // get tiny url via api-create.php
    $fp = fopen( 'http://tinyurl.com/api-create.php?url='.$url, 'r', $context); // open (read) api-create.php with long url as get parameter

    if( $fp ) { // check if open was ok
        $tinyurl = fgets( $fp ); // read response

        if( $tinyurl && !empty($tinyurl) ) // check if response is ok
            $url = $tinyurl; // set response as url

        fclose( $fp ); // close connection

    // return
    return $url; // return (tiny) url



You might want to use urlencode() for the url parameter.

It is also recommendable to check fgets() against false. Then, you could save the empty() function call by just comparing the response to an empty string, like:

$line = fgets($fp);

if ($line !== false && $line !== '') {
    // ...

Generally, it is advisable to check everything against false first, if the function returns values of different types such as integer or boolean. This can be crucial because 0 and false mean in comparisons the same. Because of PHP’s lack for type safety, it is strongly recommended to always check for type equality. There are even cases when the documentation recommends this explicitly, e.g. in the case of strpos(). Meanwhile, I’ve forced myself to use === over to ==, same for `!=’ etc. It requires more typing but it is definitely worth the effort because you eliminate possible pitfalls.

The rest of your code looks good to me.