Recently, I was working on a project and I needed to convert the relative URLs to their Absolute URLs. For those who come from a non technical background, we have absolute URL of a file on a site as www.example.com/image.jpg but mostly it is written as only “image.jpg” on the webpages. (Why?, just google ‘advantages of relative URLs’, I am feeling lazy right now.) Now the web server automatically searches for the ‘image.jpg’ in the current directory of the website. But if you want to download the file, you must have the complete absolute URL.
The RFC URL specification defines an “absolutize” algorithm for combining an absolute base URL with a relative URL to create a new absolute URL. This algorithm was already implemented and I found the PHP script for the algorithm at nadeausoftware.com. You can also find the article explaining each and every step of the code here, but if you just want to use the function keep reading.
I have created a project UrlToAbsolute at sourceforge, as I needed to use it in my several open source projects including FeedAPI ImageGrabber, Facebook-style Link Share and Feeds Image Grabber. As the script was released under BSD License, it was pretty easy to do so. Here is the link to the project UrlToAbsolute.
Usage Instructions
Extract the script (url_to_absolute.php) into your web directory, include it into your current php file using:
then, you can convert the relative url to absolute url by calling:
It return false on failure, otherwise returns the absolute url. If the $relativeUrl is a valid absolute url, it is returned without any modification.
I usually tweak this script available on sourceforge to make it more useful. I will list the main differences here (see changelog.txt for detailed information):
- Original script “percentage encodes” the URL after converting it into the absolute URL. For example: “http://www.google.com/search?q=hello” is converted to “http://www.google.com/search?q%3Dhello”. Due to this the query string becomes invalid. This issue has been corrected in v1.4 (I know that the encoding might be desirable sometimes, if so use v1.2 of the script available on sourceforge.net)








[...] for FeedAPI ImageGrabber PHP: Relative URL to Absolute URL Open Source Software and [...]
That’s exactly what I need. Thanks,
Hi there Nitin I’m testing this class as the script I’m puting together needs the ab/path to function, and wondering if you have any examples, thanks
hi,
as mentioned, it is very simple to use this function. just include it in your current file and call the function as mentioned above. You can look for the tutorial at nadeausoftware.com or the project i am currently using it in, feedapi imagegrabber.
regards,