Search code examples
phpstrpos

Checking strpos() == false fails to find match at start of string


I have a string that contains the paid modules of a user. If the module is not part of the string, an error page should be shown.

The variable $paidModules contains reminder newsfeed system finance

This is the PHP part where I check if the user paid for the module. If that is not the case, the noAccess.php page should be shown.

if($paidModules != null & $paidModules != "" ) {
    if (strpos($paidModules,'reminder') == false) {
        include('noAccess.php'); 
        return;
    }
}

The problem is now, even though the variable $paidModules contains reminder, the noAccess.php is shown. What am I doing wrong?


Solution

  • strpos() may return a boolean false. It also may return 0 as the position found.

    As such you need to use strict equality:

    if (strpos($paidModules,'reminder') === false) {
      // code...
    }
    

    In your case because reminder is found in the zero position. Using ==, PHP type-juggles 0 == false as true.