How to add http:// if it doesn't exist in the URL
PhpRegexPhp Problem Overview
How can I add http://
to a URL if it doesn't already include a protocol (e.g. http://
, https://
or ftp://
)?
Example:
addhttp("google.com"); // http://google.com
addhttp("www.google.com"); // http://www.google.com
addhttp("google.com"); // http://google.com
addhttp("ftp://google.com"); // ftp://google.com
addhttp("https://google.com"); // https://google.com
addhttp("http://google.com"); // http://google.com
addhttp("rubbish"); // http://rubbish
Php Solutions
Solution 1 - Php
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.
Solution 2 - Php
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()
Solution 3 - Php
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.
Solution 4 - Php
The best answer for this would be something like this:
function addhttp($url, $scheme="http://" )
{
return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}
The protocol flexible, so the same function can be used with ftp, https, etc.
Solution 5 - Php
Scan the string for ://
. If it does not have it, prepend http://
to the string... Everything else just use the string as is.
This will work unless you have a rubbish input string.
Solution 6 - Php
Try this. It is not watertight1, but it might be good enough:
function addhttp($url) {
if (!preg_match("@^[hf]tt?ps?://@", $url)) {
$url = "http://" . $url;
}
return $url;
}
1. That is, prefixes like "fttps://" are treated as valid.
Solution 7 - Php
nickf's solution modified:
function addhttp($url) {
if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Solution 8 - Php
<?php
if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
$_POST['url'] = 'http://'.$_POST['url'];
}
$url = $_POST['url'];
?>
This code will add http:// to the URL if it’s not there.
Solution 9 - Php
You should use this NPM package: normalize-url
normalizeUrl(url, {
removeTrailingSlash: false,
stripWWW: false,
})