How to find undefined variables in PHP script

Suppose we have the following function in PHP:

public function testSomething()
{
    $name = perform_sql_query("SELECT name FROM table WHERE id = $entity_id;");
    assert($name == "some_name");
} 

The request is syntactically correct, but since $ entity_id is undefined, the request will always look for "id = 0", which is semantically incorrect.

I would like these functions to be executed automatically when they tried to use the undefined variable. Is there such a mechanism in PHP? Or maybe there is some tool that can be used to analyze the PHP source code to find such cases?

UPDATE These undefined variables can occur anywhere in the project, so checking the function arguments in each function is the right solution.

UPDATE2 Help Setup Assistant. Now at any time an uninitialized variable is used - an exception is thrown.

+3
source share
6 answers

One of the issues to consider is that for a live site, users may not see errors and warnings. Some web hosts provide error.log, which logs a php error. Here's a custom error handler for live sites:

function log_error($no,$msg,$file,$line)
{

    $errorMessage = "Error no $no: $msg in $file at line number $line";

    file_put_contents("errors_paypal.txt",$errorMessage."\n\n",FILE_APPEND);    
}

set_error_handler('log_error');

The great thing is that you can format it and dump various information that you want.

+2
source

PHP script . , , error_reporting() php.ini -directive . PHP -, ( , , ):

# In your PHP :
error_reporting(E_ALL | E_STRICT);

# Or in your php.ini:
error_reporting = E_ALL | E_STRICT
+6

, .

, SQL ( id= not id=0), __product_sql_query .

+2

, . isset(), - :

public function testSomething()
{    
    if(!empty($entity_id)){
            $name = perform_sql_query("SELECT name FROM table WHERE id = $entity_id;");    
            assert($name == "some_name");
            return true;
    }
    return false;
}

, :

error_reporting(E_ALL | E_STRICT);
+2
  • E_ALL php-, :

    error_reporting (E_ALL);

error_reporting php.ini .htaccess. , undefined.

  • php error_log .

Finally, for the above code, include all common sense error handling in the "perform_sql_query" function. Your perform_sql_query function is probably a wrapper over the mysql_query function, so check for errors generated by mysql_query functions (and similar ones).

+1
source

Use isset () before accessing variables.

-1
source

Source: https://habr.com/ru/post/1713220/


All Articles