Reputation: 77
Ok, I am trying to do an IF / else IF statement that doesn't act as i would expect. I am trying to check that a URL address someone enters for certain things. The way I have done it is probably crap but I am not that good at programming.
All the IF parts work except for this bit if (strpos($URLcheck, "http://") == false)
It is supposed to check if the URL has http:// in it. But whether it does or doesn't it still acts exactly the same way.
I even tried forcing the http:// into the URL by stripping it of http:// or https://.
When I echo the variable ($URLcheck) , it shows the URL with the http://.....so why doesn't my code work? Thanks
$URL = htmlspecialchars($_POST["URL"]);
$URLREMOVESarray = array('https//:', 'http//:');
$URLhttp = str_replace($URLREMOVESarray, "", $URL);
$URLcheck = "http://" . $URLhttp;
$URLsearchcheck2 = 'property-profile/';
$URLsearchcheckDomain = "domain";
if (strpos($URL, $URLsearchcheck2) !== false) {
echo "Test 1";
}
else if (strpos($URLcheck, "http://") == false) {
echo "Test 2";
echo $URLcheck;
}
else if (strpos($URLcheck, $URLsearchcheckDomain) == false) {
echo "Test 3";
}
else if (strpos($URLcheck, $URLsearchcheckDomain) == true) {
Continue1();
}
Update: Still no solutions to why this doesn't work? I have even copy and pasted the code from this page and it still doesn't work.
Upvotes: 0
Views: 116
Reputation: 77
ok, nothing worked that I tried from the suggestions so I went with this code and it works. No idea why the other code wouldn't work
$pos = strpos($URLhttp, 'example.com');
if ($pos === false) {
echo "Test 1";
}
Upvotes: 0
Reputation: 79
strpos($URLcheck, "http://")
searches for "http://" in the $URLcheck
string and returns its position if it's found. In your case, it is indeed found at position 0 (start of $URLcheck string).
If strpos()
doesn't find what it's looking for, it returns a false
, which is not the same as 0, even though it sometimes seems so in PHP. This is the source of confusion for many less-experienced php devs, I advise to at least take a look at http://php.net/manual/en/types.comparisons.php
Anyway, in your case, the 0
that strpos
returns is then checked if it equals false
(with ==
). But since 0
is an integer type and false
is a boolean type, PHP has to convert the 0
to boolean and the best match for zero between true
and false
is obviously false
. That's why your if
statement behaves as it does, it's actually perfectly correct behaviour.
So what you need to do is check whether your strpos()
output is identical to false
instead of whether it equals it. You do this by simply adding another =
to your condition, so it reads strpos($URLcheck, "http://") == false
.
Upvotes: 2
Reputation: 1581
use the same !== false
statement:
$URLcheck = 'http://www.google.com';
if (strpos($URLcheck, "http://") !== false) {
echo "Test 2";
echo $URLcheck;
}
Upvotes: 3