How to add http:// if it doesn't exist in the URL PHP?

In PHP, you can automatically add "http://" to URLs that don't already have a protocol using preg_match() to check if the URL starts with http or https. This is useful when processing user input or validating URLs.

Syntax

if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
    $url = "http://" . $url;
}

Example

The following function checks if a URL starts with a protocol and adds "http://" if missing ?

<?php
function addHTTP($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

// Test with different URLs
echo addHTTP("example.com") . "<br>";
echo addHTTP("https://example.com") . "<br>";
echo addHTTP("ftp://files.example.com") . "<br>";
echo addHTTP("www.tutorialspoint.com") . "<br>";
?>
http://example.com
https://example.com
ftp://files.example.com
http://www.tutorialspoint.com

How It Works

The regular expression ~^(?:f|ht)tps?://~i breaks down as follows:

  • ^ − Start of string
  • (?:f|ht) − Non-capturing group matching "f" or "ht"
  • tps? − "tp" followed by optional "s"
  • // − Literal "//" characters
  • i − Case-insensitive flag

Alternative Method

You can also use parse_url() to check for existing schemes ?

<?php
function addHTTPAlternative($url) {
    $parsedUrl = parse_url($url);
    if (!isset($parsedUrl['scheme'])) {
        $url = "http://" . $url;
    }
    return $url;
}

echo addHTTPAlternative("google.com") . "<br>";
echo addHTTPAlternative("https://google.com") . "<br>";
?>
http://google.com
https://google.com

Conclusion

Both methods effectively add "http://" to URLs without protocols. Use preg_match() for more control over protocol patterns, or parse_url() for simpler scheme detection.

Updated on: 2026-03-15T09:29:38+05:30

570 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements