PHP if / if else statement not working as expected (Probably Simple) - php

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.

use the same !== false statement:
$URLcheck = 'http://www.google.com';
if (strpos($URLcheck, "http://") !== false) {
echo "Test 2";
echo $URLcheck;
}

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.

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";
}

Related

If statement is true OR not false [duplicate]

This question already has answers here:
Is there a difference between !== and != in PHP?
(7 answers)
difference between != and !== [duplicate]
(4 answers)
The 3 different equals
(5 answers)
Closed 3 years ago.
I have two statements like this:
$ready = true;
if($ready === true) {
echo "it's ready!";
}
And this:
$ready = true;
if($ready !== false) {
echo "it's ready!";
}
I know those mean the same thing as === true and !== false is the same thing. I see people use the negation type (is not false or is not {something}). like this: https://stackoverflow.com/a/4366748/4357238
But what are the pros and cons of using one or the other? Are there any performance benefits? Any coding benefits? I would think it is confusing to use the negation type rather than the straight forward === true. Any input would be appreciated! thank you
These do not mean the same thing, and you can see this demonstrated below:
$ready = undefined;
if($ready === true) {
console.log("it's ready 1");
}
if($ready !== false) {
console.log("it's ready 2");
}
When in doubt, stick with ===. You're comparing to exactly what it should be. "This should exactly be equal to true" vs "This should be equal to anything but exactly false" are 2 separate statements, the second including a lot of values that would be true (As demonstrated above, undefined is not exactly false, so this would be true).
Most PHP functions return false as failure, such as strpos, from the manual it says:
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So it returns an integer or false, then it is wrong to use strpos() === true
strpos() !== false is the right way to check the result.
It is not about performance and they are not the same. It helps us in reducing unnecessary if else statements.
Consider this: there is a variable foobarbaz whose value can be anything among foo/ bar/ baz/ foobar/ barbaz. You need to execute a statement if the value is not foo. So instead of writing like this:
if(foobarbaz === "bar" || foobarbaz === "baz" || foobarbaz === "foobar" || foobarbaz === "barbaz") {
//some statement
}
else if(foobarbaz === "foo") {
//do nothing
}
You can write something like this:
if(foobarbaz !== "foo") {
//some statement
}
You can see we were able to eliminate the unnecessary else statement.
In php == compare only the values are equal. For and example
$ready = 'true';
if($ready == true) {
echo "true";
}
else{
echo "false";
}
It print true.But if it is compare with === it not only check the values but also it check the datatype. So it compares with === it print the false.
Talking about !== it's work as the same. So it's not a problem to output if you use
if($ready === true)
or
if($ready !== false)
Can't compare these two because both are same.

Confused with use of strpos and !==

Confused!
I am trying to extract our localsites' names which are embedded in our WordPress website's structure, ie https://www.website.co.uk/site99/folderX/page. In the URL the localsite name is all lower case without any gaps, whereas the 'display name' of the localsite has a Starting capital and a gap between words. What am I doing wrong here?
if(strpos($_SERVER['REQUEST_URI'], '/site01/') !== false) { $categoryIdOrSlug = 'Site 01';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site02/') !== false) { $categoryIdOrSlug = 'Site 02';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site03/') !== false) { $categoryIdOrSlug = 'Site 03';}
endif;
so what I am looking for is where /site99/ is in position 0 of the slug.
If you are in https://www.website.co.uk/site99/folderX/page
Then : $_SERVER['REQUEST_URI'] will be /site99/folderX/page
if (strpos($_SERVER['REQUEST_URI'], '/site98/') !== false) { $categoryIdOrSlug = 'Site 98';} // strpos($_SERVER['REQUEST_URI'], '/site98/') will be false
elseif (strpos($_SERVER['REQUEST_URI'], '/site99/') !== false) { $categoryIdOrSlug = 'Site 99';} // strpos($_SERVER['REQUEST_URI'], '/site98/') will be 0 (which is success run & is true)
See different outputs:
echo strpos($_SERVER['REQUEST_URI'], '/site99/'); // OUTPUT: 0
Here, strpos() return the index/position at which the 2nd param(/site99/) is present in first param($_SERVER['REQUEST_URI']).
The strpos() function finds the position of the first occurrence of a string inside another string. Related functions: strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)
var_dump(strpos($_SERVER['REQUEST_URI'], '/site98/'));
Output will be bool(false). Why its false because the string was not found in param one. If its found, then the out will be a int of position like int(25).
var_dump(strpos($_SERVER['REQUEST_URI'], '/site99/'));
Output will be int(0) because strpos() has successfully found /site99/ in $_SERVER['REQUEST_URI'].
And, normally === or !== are used for Boolean value(TRUE/FALSE) comparisons.
No need to get confused with strpos() and !== both are entirely different, one returns a position index value(if found) or FALSE, if not found required string. Whereas, !== compares left & right side values of operator & says TRUE or FALSE.
Reply to your comment:
Yes, you are getting correct answer. As you said to making ensure we are using if() check.
You see we are getting int(0) while var_dump(strpos($_SERVER['REQUEST_URI'], '/site99/'));. If we have a index value(even its 0) its treated as a success run(true). That is, the string you are searching is found in index 0 or at a particular position of $_SERVER['REQUEST_URI']. if() makes sure that the check is correct, int(0) !== false means int(0) is a success run(which is also said as true). So if(int(0) !== false) can be said also as if(true !== false) which is true & so $categoryIdOrSlug = 'Site 99'; will run.
if() can also be written as:
if (strpos($_SERVER['REQUEST_URI'], '/site98/')) { $categoryIdOrSlug = 'Site 98';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site99/')) { $categoryIdOrSlug = 'Site 99';}
echo $categoryIdOrSlug; // output: Site 99
You cant check by === 0 because we cant say the position at which strpos() founds the searching string, it may vary.

Unable to get the position of a character within my string using strpos

Good day,
I have the following string :
[Star]ALERT[Star]Domoos detects blabla[blabli]
For strange reasons, the code below does not detect the star at the very first character. I read in the php documentation that the first character has an index of 0. However, if I am looking for the '[', the function works very well.
What I am trying to achieve is to ensure that the first character of my string is really a * (star). Strangely, if I enter $pos1 = strpos($inputString, '*', 1), the star shown at position '6' would be returned.
I don't quite understand why my code does not work as expected (i.e. does not enter into the 'true' condition)
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
if ($pos1 == True)
{
echo 'position' . $pos1;
}
Do you have any suggestion that would help me to overcome this issue?
Thanks a lot for your appreciated support.
change condition to
if ($pos1 != False)
{
echo 'position' . $pos1;
}
as strpos will return position at (integer) or False
If you look at the manual:
Find the numeric position of the first occurrence of needle in the
haystack string.
In your test case, the numeric position is 0 and 0 != true.
Also see the warning in the manual:
Warning This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
So the condition you really want is:
if ($pos1 !== false)
You don't need strpos. As string is an array of characters so you can do like this
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$compare_char= $inputString[0];
if($compare_char=="*"){
//do something.
}
As i suppose it is fast too rather than on searching through strpos
Actually issue is that when you are looking at 0 position the value which you get is 0 and when you are checking that in if condition with True, it will always fail because 0 will be evaluated as False. To resolve this you can use
if($pos1 !== False)
The function strpos returns false if there is no existence of what you search. So make a check like the following:
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
return $pos1 !== false ? 'position ' . $pos1 : '..';
$pos1 returns 0 and this is treat as False so we cant take it as True so we can use here isset function.
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*',0);
if (isset($pos1))
{
echo 'position' . $pos1;
}

PHP strpos to match querystring text pattern

I need to execute a bit of script only if the $_GET['page'] parameter has the text "mytext-"
Querystring is: admin.php?page=mytext-option
This is returning 0:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
echo $match;
strpos returns the position of the string. Since it's 0, that means it was found at position 0, meaning, at the start of the string.
To make an easy way to understand if it's there, add the boolean === to an if statement like this:
<?php
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match === false ) {
echo 'Not found';
} else {
echo 'Found';
}
?>
This will let you know, if the string is present or not.
Or, if you just need to know, if it's there:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match !== false ) {
echo 'Found';
}
?>
Use substr() once you get the location of 'mytext-', like so:
$match = substr($myPage, strpos( $myPage, 'mytext-') + strlen( 'mytext-'));
Otherwise, strpos() will just return the numerical index of where 'mytext-' starts in the string.
You can also use str_replace() to accomplish this if your string only has 'mytext-' once:
$match = str_replace( 'mytext-', '', $myPage);
The function strpos() returns the position where the searched string starts which is 0. If the string is not found, the function will return false. See the strpos documentation which tells you as well:
WARNING This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
A solution to your question would be to use substr(), preg_match() or check if strpos() !== false.
The easiest solution should be this:
if (preg_match('/^mytext-/i', $_GET['page'])) {
// do something
}
You may also consider using more than just one GET parameter like
http://www.example.com/foo.php?page=mysite&option1=123&option2=456
You then use your parameters lik $_GET['page'], $_GET['option1'], $_GET['option2'], etc.
However, you should also be careful what you do with raw $_GETor $_POST data since users can directly input them and may inject harmful code to your website.
That is expected since the substring starts at index 0. Read the warning on php.net/strpos:
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
If you only need to check if $myPage contains 'mytext-', use stristr:
if(stristr($myPage, 'mytext-') !== false) {
// contains..
}
What's wrong about preg_match?
$myPage = $_GET['page'];
if (preg_match("/\bmytext-\b/i", $myPage)) {
//Do Something
}
Or do you need the "option" out of "mytext-option"?
If yes you can use this:
$myPage = $_GET['page'];
$querystrings = explode("-", $myPage);
if ($querystrings[0] == 'mytext')) {
//Do Something
echo $querystrings[1]; //outputs option
}
With this you can even use more "options" in your querystring like "mytext-option-whatever". That's the same as when you use
$_GET['page'], $_GET['option'], $_GET['whatever']
when you use
?page=mysite&option=x&whatever=y

verify, if the string starts with given substring

I have a string in $str variable.
How can I verify if it starts with some word?
Example:
$str = "http://somesite.com/somefolder/somefile.php";
When I wrote the following script returns yes
if(strpos($str, "http://") == '0') echo "yes";
BUT it returns yes even when I wrote
if(strpos($str, "other word here") == '0') echo "yes";
I think strpos returns zero if it can't find substring too (or a value that evaluates to zero).
So, what can I do if I want to verify if word is in the start of string? Maybe I must use === in this case?
You need to do:
if (strpos($str, "http://") === 0) echo "yes"
The === operator is a strict comparison that doesn't coerce types. If you use == then false, an empty string, null, 0, an empty array and a few other things will be equivalent.
See Type Juggling.
You should check with the identity operator (===), see the documentation.
Your test becomes:
if (strpos($str, 'http://') === 0) echo 'yes';
As #Samuel Gfeller pointed out: As of PHP8 you can use the str_starts_with() method. You can use it like this:
if (str_starts_with($str, 'http://')) echo 'yes';
PHP does have 2 functions to verify if a string starts with a given substring:
strncmp (case sensitive);
strncasecmp (case insensitive);
So if you want to test only http (and not https), you can use:
if (strncasecmp($str,'http://',7) == 0) echo "we have a winner"
check with
if(strpos($str, "http://") === 0) echo "yes";
as == will turn positive for both false & 0 check the documentation
Another option is:
if (preg_match("|^(https?:)?\/\/|i", $str)) {
echo "the url starts with http or https upper or lower case or just //.";
}
As shown here: http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/
strncmp($str, $word, strlen($word))===0
Is a bit more performant than strpos
Starting with PHP 8 (2020-11-24), you can use str_starts_with:
if (str_starts_with($str, 'http://')) {
echo 'yes';
}
PHP 8 has now a dedicated function str_starts_with for this.
if (str_starts_with($str, 'http://')) {
echo 'yes';
}
if(substr($str, 0, 7)=="http://") {
echo("Statrs with http://");
}
There's a big red warning in the documentation about this:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
strpos may return 0 or false. 0 is equal to false (0 == false). It is not identical to false however, which you can test with 0 === false. So the correct test is if (strpos(...) === 0).
Be sure to read up on the difference, it's important: http://php.net/manual/en/language.operators.comparison.php

Categories