davosmith
davosmith

Reputation: 6327

Is it possible to determine which PHP file generated some output

Occasionally I have problems whereby a PHP file, somewhere on a large system is producing spurious output in certain situations.

This may be because someone has accidentally typed a space or other character before the <?php opening tag, or left an unwanted debugging echo in place or included some whitespace after the final closing ?> tag.

Is there any way to generate a log which shows all the PHP files that generated some output, alongside the output they generated?

If not, is there any other way that can be suggested for tracking down the problem I have described?

Edit: To clarify - the system I'm running is Moodle (not directly relevant, but as it was asked ...) and, on this occasion, the output was during the DB upgrade (but I've had similar problems with random characters being output at other times). There are a very large number of different PHP scripts being loaded into memory to generate the page, so manually spotting the one generating the unwanted output wasn't a very enticing prospect ...

Upvotes: 5

Views: 270

Answers (2)

VolkerK
VolkerK

Reputation: 96159

if your "only" concern is the text outside of php tags token_get_all() might help you. Everything(?) outside php tags is reported as T_INLINE_HTML (312), so it's easy to filter.
E.g.

<?php
for($t=0;$t<10; $t++) { ?>

<?php
}
?>

<?php
$at = token_get_all( file_get_contents(__FILE__) );
foreach($at as $t) {
    if ( is_array($t) && T_INLINE_HTML===$t[0]) {
        echo 'inline html @ line ', $t[2], "\r\n";
    }
}

prints (some blank lines and)

inline html @ line 3
inline html @ line 7

combine that with something like get_included_files() or RecursiveDirectoryIterator and you have a little makeshift tool for the task.

Upvotes: 1

Tabby
Tabby

Reputation: 388

There are a few ways of doing it but its a time consuming job unless you have written the code . Make sure you turn on error reporting this may also help.

1) Install Apachetop

This tool scans your webserver log files showing you which files are being called, it also has a few other interesting features

2)Use lsof

watch -n1 "lsof | grep '\.php'"

The above line of code will only list .php files which have been opened. If the file opens and closes fast it may not be able to list it

3)Use xdebug and xdebug profiler.

While your running the code; simultaneously check xdebug profiler and keep refreshing it. One of the feature the profiler has is that it draws a visual map of the files being called. You will have to then manually check those files for syntax errors or bad/wrong logic. If you know or if you have made the system it will be a bit ease for you to do it.

I hope this helps

Upvotes: 0

Related Questions