Recently, I was working on a project and I needed to convert the relative URLs to their absolute URLs. An absolute URL such as “http://www.example.com/image.jpg” but mostly written as only “image.jpg” (relative URL) on the web pages. Web browser creates a complete URL using this relative URL and base URL. The base URL, must be absolute and it is often the URL of the web page containing the relative URL.
Now, if you need to access a file whose relative URL and base URL are known, you must combine them to create an 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. 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 Links and Feeds Image Grabber. As the original script was released under BSD License, it was pretty easy to fork it. Here is the link to the project UrlToAbsolute. You can also look at the step by step explanation of the script here.
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.
- Project page: http://sourceforge.net/projects/absoluteurl
- Original article: http://nadeausoftware.com/articles/2008/05/php_tip_how_convert_relative_url_absolute_url
- v1.6, March 12, 2010
- added encode_url function to convert an absolute url to its percentage
encoded equivalent, according to RFC 3986 (http://publicmind.in/blog/url-encoding/)
- v1.5, March 11, 2010
- fixed to allow spaces in the path of url
- v1.4, October 2, 2009
- Percentage encoding of the absolute url disabled.
- v1.0, February 27, 2009
- Initial release of the script on nadeausoftware.com