Home >Backend Development >PHP Tutorial >How Can I Ensure URLs Always Begin with a Protocol (http:// or https://)?

How Can I Ensure URLs Always Begin with a Protocol (http:// or https://)?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 07:23:11940browse

How Can I Ensure URLs Always Begin with a Protocol (http:// or https://)?

Adding HTTP Protocol to URLs

In web development, it's often desirable to ensure that a URL starts with a protocol (e.g. http:// or https://). This helps browsers interpret the URL correctly and load the appropriate content.

Solution

To add the "http://" protocol to a URL if it's missing, consider the following code:

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

This function handles different protocols such as "ftp://", "ftps://", "http://", and "https://" in a case-insensitive manner.

Examples

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

The above is the detailed content of How Can I Ensure URLs Always Begin with a Protocol (http:// or https://)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn