Check whether the URL scheme is HTTP or HTTPS
I'm using the following code to add http://
to the URL.
(substr(strtolower($url), 0, 7) == 'http://'?"":"h开发者_Python百科ttp://").$url
but how can I check whether the original URL contains https
? I don't want to use an OR clause.
preg_match("@^https?://@", $url)
Answer
echo parse_url($url, PHP_URL_SCHEME);
Reference
docs https://www.php.net/manual/en/function.parse-url.php
parse_url(string $url, int $component = -1): mixed
parse_url
function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial and invalid URLs are also accepted, parse_url() tries its best to parse them correctly.
Use preg_match and a regular expression on your url :
preg_match(^http(s)?://);
If it returns true, then your URL is ok, whether it uses http of https.
strncmp($url, 'https:', 6) === 0
!empty($_SERVER['HTTPS']) ? 'https' : 'http'
I think the best way is to use parse_url() function. Like this :
if (empty($url['scheme'])) {
$url = 'https://' . $url;
}
精彩评论