How to add http:// if it doesn't exist in the URL
A modified version of @nickf code:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Recognizes ftp://
, ftps://
, http://
and https://
in a case insensitive way.
At the time of writing, none of the answers used a built-in function for this:
function addScheme($url, $scheme = 'http://')
{
return parse_url($url, PHP_URL_SCHEME) === null ?
$scheme . $url : $url;
}
echo addScheme('google.com'); // "http://google.com"
echo addScheme('https://google.com'); // "https://google.com"
See also: parse_url()
Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.
if (false === strpos($url, '://')) {
$url = 'http://' . $url;
}
Note: This may be a simple and straightforward solution, but Jack's answer using parse_url
is almost as simple and much more robust. You should probably use that one.