Shorten URLs with PHP and cURL

Here’s some quick stub-code for shortening urls using PHP + cURL and the 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 = "";
        $url = $url_stem . urlencode($url_to_shorten);
        $shortened_url = '';

        if(!$use_curl) {
            $fp = fopen($url, 'r');
            while (!feof($fp)) {
                $shortened_url .= fread($fp, 8192);            
        } 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);
        return $shortened_url;

Update: added support for fopen in addition to curl.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s