Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strpos function issue in PHP not finding the needle

Tags:

string

php

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;
    }
}
like image 928
Josh Smeaton Avatar asked Dec 07 '22 09:12

Josh Smeaton


2 Answers

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.

like image 70
VolkerK Avatar answered Dec 22 '22 23:12

VolkerK


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 /');
like image 25
David Precious Avatar answered Dec 22 '22 22:12

David Precious