Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if string contains "HTTP://"

Tags:

string

php

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.

like image 935
somewalri Avatar asked Dec 20 '10 07:12

somewalri


People also ask

How do I know if my URL contains https?

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.

How do I find the URL of a string?

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.

How do you check if a string contains any value?

The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.

How do you check if a string contains a name?

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.


2 Answers

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)
like image 150
BoltClock Avatar answered Oct 18 '22 08:10

BoltClock


@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

like image 36
Russell Dias Avatar answered Oct 18 '22 10:10

Russell Dias