How to get the line numbers of PHP source code executed in more robust way [duplicate]

怎甘沉沦 提交于 2019-12-12 10:32:37

问题


I'm trying to get the line numbers of PHP source code implemented at that run time. I used __LINE__ function which return the line number that implemented based on the condition that I gave. I try to put most of the senario of PHP source. However, the function still missed some issue or not working smoothly for all PHP senario syntax. The following example shows what I'm trying to get, and the result I achieved:

(example.php)

<?php  ;      
$a = "Hello World! ";  
$b = "Welcome ";  
if(isset($a)) {
   echo true;   }
if(isset($b)) {
   echo true;   }
else {        
   echo false; 
}

?>

Then when I run my testing code as following:

(test.php)

$file = file_get_contents("example.php");
$lines = explode("\n", $file);
$start = ' $total = NULL;  ';
$append = '  $total = $total . __LINE__ . " - " ; ';
$append2 = '  echo $total; ';
$check_php = 0;

foreach ($lines as $key => &$value) {

if(strpos($value, "<?php") !== false){
    $check_php = 1;
    $value = $value.$start.$append;
}

if(strpos($value, "?>") !== false){
       $value = $append2.$value ;
          $check_php = 0;
}


if($check_php === 1)
{
    if($value == " " OR  empty($value) )
    {

    }
    else if(substr($value, -1) == ';' )
    {
        $value = $value.$append;
    }
    else if(strlen(preg_replace('/[^a-zA-Z]/', '', $value)) < 2)
    {

    }
    else if(substr( $value, 0, 4 ) === "else")
    {
        $value = $value.$append;
    }
    else
    {
        $value = $append.$value ;
    }

}


}
file_put_contents("example.php", implode("\n", $lines));

header("example.php");

Then the file (example.php) will change as following:

<?php  ;      
 $total = NULL;    $total = $total . __LINE__ . " - " ; 
  $total = $total . __LINE__ . " - " ; $a = "Hello World! ";  
  $total = $total . __LINE__ . " - " ; $b = "Welcome ";  
  $total = $total . __LINE__ . " - " ; if(isset($a)) {
  $total = $total . __LINE__ . " - " ;    echo true;   }
  $total = $total . __LINE__ . " - " ; if(isset($b)) {
  $total = $total . __LINE__ . " - " ;    echo true;   }
else {        
  $total = $total . __LINE__ . " - " ; 
  $total = $total . __LINE__ . " - " ;    echo false; 
}
  echo $total; ?>

Which will print the path that executed at this run:

(Result)

2 - 3 - 4 - 5 - 6 - 7 - 8 -

Can anyone help me to find more robust way to get the path of PHP source code based on most of PHP syntax senario. or if any tool can do it and get the line numbers of PHP source code that executed at that time.

Thanks in advance

来源:https://stackoverflow.com/questions/59128514/how-to-print-a-variable-in-single-quotations-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!