2

This works if 'test1' is in the url:

<? if(strpos($_SERVER['HTTP_HOST'], 'test1') !== FALSE) : ?>
  <p>Do something</p>
<? else : ?>
  <p>Do something else</p>
<? endif ?>

This doesn't work if 'test1' is in the url:

<? if(strpos($_SERVER['HTTP_HOST'], 'test1') OR strpos($_SERVER['HTTP_HOST'], 'test2') !== FALSE) : ?>
  <p>Do something</p>
<? else : ?>
  <p>Do something else</p>
<? endif ?>

Questions:

1. When I try to run the second option, php outputs "Do something else" every time - I know it's basic but why is this?

2. Why doesn't == TRUE work in this instance, only !==FALSE works.


Any help would be much appreciated - I've spent a scary amount of time researching this so sorry if it's because of a dumb mistake.

Cheers

2 Answers 2

2

You shouldn't test loosely with == TRUE because you might get a false positive, remember that 0 is falsy when its tested loose and getting 0 in strpos is valid since that actually is the position of where the needle exists relative to the beginning of your string.

Consider this snippet:

<?php $_SERVER['HTTP_HOST'] = 'test1.com'; ?>
<?php if(strpos($_SERVER['HTTP_HOST'], 'test1') == TRUE): ?>
  <p>Do something</p>
<?php else : ?>
  <p>Do something else</p>
<?php endif; ?>

This is an example of that false positive.

test1 is indeed inside the string (position 0), but since it returned 0 and your testing it with == TRUE it will go in the else block, leaving out a wrong answer.

So you should always test it !== false:

<?php $_SERVER['HTTP_HOST'] = 'test1.com'; ?>
<?php if(
    (strpos($_SERVER['HTTP_HOST'], 'test1') !== false) OR
    (strpos($_SERVER['HTTP_HOST'], 'test2') !== FALSE)) : ?>
  <p>Do something</p>
<?php else : ?>
  <p>Do something else</p>
<?php endif; ?>

Actually its in the manual covered. Read the red box note.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. May I please ask why you set HTTP_HOST to something first - is that just good programming practice? Cheers, Ben
@CMSCSS no, i just explicitly set HTTP_HOST some value for this particular example. glad this helped
0

try this

if(strpos($_SERVER['REQUEST_URI'], 'test1') OR strpos($_SERVER['REQUEST_URI'], 'test2') !== FALSE){ 
  echo"<p>Do something</p>";
} else {
  <p>Do something else</p>
}

1 Comment

don't open, and close php tags as it slows down page processing.

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.