Shorten URLs with is.gd PHP and cURL

Here’s some quick stub-code for shortening urls using PHP + cURL and the http://is.gd/ api.



    function is_gd_shorten_url($url_to_shorten, $use_curl=false)
    {
        # uses cURL or fopen to return the short version of a URL
        # fopen requries the php.ini setting allow_url_open=on which
        # many web hosts don't allow, cURL requires PHP to be compiled
        # with cURL support. Many hosts allow/provide cURL. check a 
        # phpinfo() page if you don't know which vs. to use.
        $url_stem = "http://is.gd/api.php?longurl=";
        $url = $url_stem . urlencode($url_to_shorten);
        $shortened_url = '';

        if(!$use_curl) {
            $fp = fopen($url, 'r');
            while (!feof($fp)) {
                $shortened_url .= fread($fp, 8192);            
            }
            fclose($fp);
        } elseif(defined(curl_init)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            # return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $shortened_url = curl_exec($ch);
            curl_close($ch);  
        }        
        return $shortened_url;
    }

Update: added support for fopen in addition to curl.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s