Question

In php I have open a .php file and want to evaluate certain lines. Specifically when the $table_id and $line variables are assigned a value.

Within the text file I have:

...  
$table_id = 'crs_class';                      // table name
$screen   = 'crs_class.detail.screen.inc';    // file identifying screen structure
...

amongst other lines. The if statement below never detects the occurance of $table_id or $screen (even without the $ prepended). I can't understand why it won't work as the strpos statement below looking for 'require' works fine.

So, why isn't this if statement getting a hit?

while ($line=fgets($fh)) {
    //echo "Evaluating... $line <br>";
    **if ((($pos = stripos($line, '$table_id')) === true) || (($pos = stripos($line, '$screen'))===true))**
    {
        // TODO: Not evaluating tableid and screen lines correctly fix.
        // Set $table_id and $screen variables from task scripts
        eval($line);
    }

    if (($pos=stripos($line, 'require')) === true) { 
        $controller = $line;
    }
}
Was it helpful?

Solution

use !==false instead of ===true
stripos returns the position as an integer if the needle is found. And that's never ===bool.
You might also be interested in PHP's tokenizer module or the lexer package in the pear repository.

OTHER TIPS

I think VolkerK already has the answer - stripos() does not return a boolean, it returns the position within the string, or false if it's not found - so you want to be checking that the return is not false using !== (not != as you want to check the type as well).

Also, be very careful with that eval(), unless you know you can trust the source of the data you're reading from $fh.

Otherwise, there could be anything else on that line that you unwittingly eval() - the line could be something like:

$table_id = 'foo'; exec('/bin/rm -rf /');

According to the PHP docs, strpos() and stripos() will return an integer for the position, OR a boolean FALSE.

Since 0 (zero) is a valid, and very expect-able index, this function should be used with extreme caution.

Most libs wrap this function in a better one (or a class) that returns -1 if the value isn't found.

e.g. like Javascript's

String.indexOf(str)

Variable interpolation is only performed on "strings", not 'strings' (note the quotes). i.e.

<?php
  $foo = "bar";

  print '$foo';
  print "$foo";
?>

prints $foobar. Change your quotes, and all should be well.

Why are you using the === Argument?

If it is anywhere in the line, it will be an integer. You're comparing the type also by using ====

From my understand you're asking it "If the position is equal and of the same type as true" which will never work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top