Search the Site


bottom corner

Shorten long URLs with Perl, cURL, and the API

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

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


### This is the long URL we wish to ultimately shorten
$url = "";

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, "$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";


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