Daniele
Daniele

Reputation: 129

PHP - strstr() returns false but the $haystack contains the $needle

This is a very strange error, i am trying to fix it without success. I am trying to check if a link contains a string:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $actual_link;

The output is:

http://xxx.xxx.xxx.xxx/plesk-site-preview/***********.com/xxx.xxx.xxx.xxx/

Then:

if(strstr($actual_link,"plesk-site-preview")  ){
echo"<meta name='robots' content='noindex'>";
}

The problem is that strstr return false despite the substring plesk-site-preview is contained in http://xxx.xxx.xxx.xxx/plesk-site-preview/***********.com/xxx.xxx.xxx.xxx/.

How can i fix this error?

EDIT:

I have inserted before if(strstr($actual_link,"plesk-site-preview") ){ the following line for testing purpose:

$actual_link='http://xxx.xxx.xxx.xxx/plesk-site-preview/***********.com/xxx.xxx.xxx.xxx/';

Now the code is working! It seems that the string assigned at the variable $actual_link is lost before the IF statement.

Upvotes: 0

Views: 817

Answers (2)

Mawg
Mawg

Reputation: 40140

The documentaion says

string strstr ( string $haystack , mixed $needle [, bool $before_needle = FALSE ] )

Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

Returns the portion of string, or FALSE if needle is not found.

And you code

if(strstr($actual_link,"plesk-site-preview")) 

Perhaps it ought to be

if(strstr($actual_link,"plesk-site-preview") != "") 

as it returns a string, not a boolean if successful.

Hmm, actually it would be better to

 if(strstr($actual_link,"plesk-site-preview") !== FALSE)

Upvotes: 1

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

If you need check string presence of a substring in a string then you can use strpos, for example:

if(strpos($actual_link, "plesk-site-preview")){
    echo"<meta name='robots' content='noindex'>";
}

This way is better, because strpos is faster than strstr

Upvotes: 0

Related Questions