I am wondering why this code is not working:
// check to see if string contains "HTTP://" in front
if(strpos($URL, "http://")) $URL = $URL;
else $URL = "http://$URL";
If it does find that the string doesn't contain "HTTP://" the final string is "HTTP://HTTP://foo.foo" if it contiains "http://" in front.
How do I know if my URL contains https? If the string to parse is also the page url then you could use $_SERVER["REQUEST_SCHEME"] which returns 'http' or 'https' or $_SERVER["HTTPS"] which returns 1 if the scheme is https.
Catch Exception from URL() Constructor To check if a string is a URL, pass the string to the URL() constructor. If the string is a valid URL, a new URL object will be created successfully. Otherwise, an error will be thrown.
The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.
The Java String contains() method is used to check whether the specific set of characters are part of the given string or not. It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise. It can be directly used inside the if statement.
Because it's returning 0 for that string, which evaluates to false. Strings are zero-indexed and as such if http://
is found at the beginning of the string, the position is 0, not 1.
You need to compare it for strict inequality to boolean false using !==
:
if(strpos($URL, "http://") !== false)
@BoltClock's method will work.
Alternatively, if your string is a URL you can use parse_url(), which will return the URL components in an associative array, like so:
print_r(parse_url("http://www.google.com.au/"));
Array
(
[scheme] => http
[host] => www.google.com.au
[path] => /
)
The scheme
is what you're after. You can use parse_url() in conjunction with in_array
to determine if http
exists within the URL string.
$strUrl = "http://www.google.com?query_string=10#fragment";
$arrParsedUrl = parse_url($strUrl);
if (!empty($arrParsedUrl['scheme']))
{
// Contains http:// schema
if ($arrParsedUrl['scheme'] === "http")
{
}
// Contains https:// schema
else if ($arrParsedUrl['scheme'] === "https")
{
}
}
// Don't contains http:// or https://
else
{
}
Edit:
You can use $url["scheme"]=="http"
as @mario suggested instead of in_array()
, this would be a better way of doing it :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With