Automatically prepend ‘http://’ to a URL
Here is a nifty little PHP function I made recently that utilises PHP’s substr() function, something I’ve been meaning to do for a while in fact. It’s really simple yet surprisingly useful.
When you’re outputting a URL into a webpage, it might not have the necessary http:// at the beginning by default. This will cause the link to be invalid and it will not direct your users to the intended location.
This is handy in WordPress if you are dealing with URLs that have been submitted via custom fields for example (average internet users will most likely not be aware that a link needs to start with http:// and therefore may not include it.
Try this function out (if in WordPress, add it to your functions.php template file):
// add http:// if necessary
function httpCheck($url) {
if(substr($url, 0, 4) == 'www.') {
$url = 'http://' . $url;
}
return $url;
}
Then, you can simply output a valid URL like so:
<a href="<?php echo httpCheck($someURL); ?>"><?php echo $someURL; ?></a>
You only need to include the httpCheck() function inside the href attribute, the second iteration of $someURL is there purely for display purposes (you could just set it to something like ‘click here’ if you like).
There you have it! Valid URLs without having to edit the value of $someURL manually.
Reactions
Thanks Darren, although I’m not entirely sure that would be necessary. I don’t really know of any apps that will convert a string to a link if it is missing both a ‘http://’ and a ‘www’.
Even the likes of Facebook will just class it as an ordinary string.


I would check for the lack of http as there is no guarantee that the URL will start www. If I state my URL to be mysite.com then your script as it is will miss it.