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
Release: 2024-11-28 07:23:11
Original
896 people have browsed it

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;
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template