Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Convert relative to absolute URL given a base URL, without modules

by Aristotle (Chancellor)
on Jan 17, 2006 at 06:07 UTC ( #523679=snippet: print w/replies, xml ) Need Help??

I wrote this mainly because someone asked how to do this in PHP. Turns out there is nothing in like the venerable URI module in all of PHP-dom (how pathetic is that for a language as web-centric as it?).

First, I tried writing this with mostly string functions, but that was too painful, so I switched to doing it using regexes, even though they’re piss-poorly supported. After a while, my eyes glazed over, so I resorted to writing and debugging the code in Perl first, and then compiling it down to machine code PHP.

I thought I’d post this byproduct here for posterity, in case someone needs it in some circumstance.

Tests included, but I’m pretty sure they’re not extensive enough to be 100% confident in the code. Proceed at your discretion.

sub abs_url {
    my ( $relative, $base ) = @_;

    return $relative if $relative =~ m{ \A http:// }ix;

    my ( $host, $hostrelative_abs ) = $base =~ m{
        http:// # skip scheme
        ([^/]*) # capture hostname
        /*      # skip front slashes
        (.*?)   # capture everything that follows, but
        [^/]*   # leave out the optional final non-directory component

    $hostrelative_abs = '' if $relative =~ m!^/!;

    my $abs_url = join '/', $host, $hostrelative_abs, $relative;

    # replace '//' or '/./' with '/'
    1 while $abs_url =~ s{ / \.? (?=/|\z) }{}x;

    # remove '/foo/..' (but be careful to skip '/../..')
    1 while $abs_url =~ s{ / (?!\.\.) [^/]+ / \.\. (?=/|\z) }{}x;

    return "http://$abs_url";
use Test::More;
my @test = qw(
 /foo/bar.gif    http://www.exam
 foo/bar.gif    http://www.exam
 ../../bar.gif    http://www.exam
 foo/bar.gif     http://www.exam
 ../foo/bar.gif     http://www.exam
 ../../foo/bar.gif http://www.exam
plan tests => @test / 3;
do { is abs_url( $test[0], $test[1] ), $test[2]; splice @test, 0, 3 } 
+while @test;
Replies are listed 'Best First'.
Re: Convert relative to absolute URL given a base URL, without modules
by cbarrette (Initiate) on Jun 23, 2015 at 18:09 UTC
Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://523679]
[dazz]: Also, I want to use Image::Magick to annotate and composite (not in a sub). How do I take a Image::Grab object and apply Image::Magick write methods to it??
[dazz]: At present, I am saving the Image::Grab image to disk, then creating a new Image::Magick object that reads the disk file.
[dazz]: .
[choroba]: Discipulus Sounds interesting. Any pictures of the puppets or paintings?

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (9)
As of 2017-03-27 07:44 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (317 votes). Check out past polls.