Search code examples
phpsearchstrpos

PHP 7.3 strpos() needles issue?


ERROR: strpos(): Non-string needles will be interpreted as strings in the future. Use an explicit chr() call to preserve the current behavior in

Having read a slew of online topics on this - none of them seem to touch on how I have code which makes me uncertain where I am wrong.

This code uses the get to search text files and returns an array of files with that search. Code worked up until the 7.3 update.

  $search_get = $_GET['q'];
  if ($search_get = NULL) {
  $search_get = 'encyclopedia';
  }

  foreach (glob("dir/*.txt") as $search) {
    $contents = file_get_contents($search);
    if (!strpos($contents, $search_get)) continue;
    $found[] = $search;
  }

How is $search_get not valid here?


Solution

  • @paul-t is right you are assigning the variable instead of comparing it to null, that's why you should use so-called Yoda conditions

    if (null === $search_get) {
        $search_get = 'encyclopedia';
    }
    

    Anyway this is a slightly simplified version of your code:

    $search_get = @$_GET['q'] ?: 'encyclopedia';
    
    foreach (glob("dir/*.txt") as $search) {
        $contents = file_get_contents($search);
        if (!empty($contents) && false !== strpos($contents, $search_get)) {
            $found[] = $search;
        }
    }
    

    BTW consider using stripos instead of strpos, because currently your checks on $contents variable are case-sensitive.