Search the Site

Sponsors

bottom corner

Shorten long URLs with Perl, cURL, and the short.to API

This sample Perl script illustrates how to use the cURL::Easy extension of libcurl to use short.to's API to shorten long URLs.

This page is filed under keyword(s): perl.

#!/usr/bin/perl

### This is the long URL we wish to ultimately shorten
$url = "http://ww2db.com/battle_spec.php?battle_id=10";



sub body_callback {
        my ($chunk,$context)=@_;
        push @{$context}, $chunk;
        return length($chunk);
}

use Curl::easy;

my $curl= Curl::easy::init();
Curl::easy::setopt ($curl, CURLOPT_SSL_VERIFYHOST, 0);
Curl::easy::setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
Curl::easy::setopt ($curl, CURLOPT_URL, "http://short.to/s.txt?url=$url");
Curl::easy::setopt ($curl, CURLOPT_WRITEFUNCTION, \&body_callback);
my @body;
Curl::easy::setopt ($curl, CURLOPT_FILE, \@body);
Curl::easy::setopt ($curl, CURLOPT_ERRORBUFFER, "errorBuffer");

if (Curl::easy::perform ($curl) != 0) {
	print "Fail: $errorBuffer\n";
}
else {
	### Now we have the URL stored within @body for our use.
	print "Success: @body\n";
};

Curl::easy::cleanup($curl);

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): perl.
Author: C. Peter Chen
Last updated: 2 Jul 2009

bottom corner