phptrace

How print every line of a php script as its being executed?


How to print every line of a php script as it's being executed?

For example in Python you can do

$ cat test.py 
import time
print('hello')
time.sleep(3)
print('goodbye')

$ python -m trace -t test.py 
 --- modulename: test, funcname: <module>
test.py(1): import time
test.py(2): print('hello')
hello
test.py(3): time.sleep(3)
test.py(4): print('goodbye')
goodbye

Is there a PHP equivalent?


Solution

  • PHP doesn't have trace, you can get around that with "ticks".
    This is an example of what you can do:

    <?php
    
    // You need to add this code
    declare(ticks=1);
    register_tick_function(function() {
        $backTrack  = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
        $line = trim(file($backTrack['file'])[$backTrack['line'] - 1] ?? '');
        echo "$line\n";
    });
    
    
    // Your code goes here
    echo "hello\n";
    sleep(3);
    echo "goodbye\n";
    

    It will print out this:

    hello
    echo "hello\n";
    sleep(3);
    goodbye
    echo "goodbye\n";
    

    You can read more about ticks here: