10

I'm using the following code to add http:// to the URL.

(substr(strtolower($url), 0, 7) == 'http://'?"":"http://").$url

but how can I check whether the original URL contains https? I don't want to use an OR clause.

1
  • 2
    "I don't want to use an or". Why not? Commented Sep 7, 2011 at 13:22

5 Answers 5

14
preg_match("@^https?://@", $url)
Sign up to request clarification or add additional context in comments.

1 Comment

Please help fighting the misconception that StackOverflow is a free code writing service, by augmenting your code-only answer with some explanation.
10

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.

Comments

3

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.

2 Comments

you forgot both string and regex delimiters ;)
you should have written preg_match('/^http(s)?:\/\//', $url)
1
strncmp($url, 'https:', 6) === 0

1 Comment

Please help fighting the misconception that StackOverflow is a free code writing service, by augmenting your code-only answer with some explanation.
-2

I think the best way is to use parse_url() function. Like this :

if (empty($url['scheme'])) {
   $url = 'https://' . $url;
} 

1 Comment

This answer must be deleted because it duplicates existing answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.