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!