Which script is writing output in PHP? - php

I'm working on a Laravel application and after some updates I keep getting a comma "," in every http response or console output so I'm crazy trying to find which script file is printing that character.
Is it possible to know which file is writing to the output http response or console?
UPDATE
I've put an echo call in Composer's ClassLoader vendor\composer\ClassLoader.php after an include function for the loaded classes is called, as follows:
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file; echo $file . "\n";
}
And now the comma appears between the following classes are loaded, is this helpful?
C:\Users\Bla\Bla\trunk\vendor/filp/whoops/src/Whoops/Handler/PrettyPageHandler.php
,C:\Users\Bla\Bla\trunk\vendor/laravel/framework/src/Illuminate/Foundation/AliasLoader.php
C:\Users\Bla\Bla\trunk\vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php
UPDATE 2
Found it! As #vladsch said, it was before an opening tag ,<?php in one of my config files, thanks

Since you have it in HTTP and console then this rules out the views.
The culprit is probably a comma inadvertently inserted before the opening <?php tag. Most likely one of the first ones that is at the top of every PHP file.
Do a search for ,<?php or for regex pattern /\s*,\s*<\?php/

Yes, you can, debugging with xdebug or other debbuger tool, step by step (step into) until you find the script.
See this stackover entry for guiadance.
I strongly recommend use a real debug tool as a good pro practice. But maybe for this particular purpouse its a little overwelming.

You can probably narrow it down with some basic debugging. Add a dd('hello') throughout your application.
I would start in the routes.php file. See if the comma appears before or after the hello. If it is before the hello, then the comma is in one of the bootstrapping files.
If the comma is after the hello, then it is most likely in one of your views etc. Keep moving the dd('hello') deeper into your application until it appears.

No you cannot, that's why you should use a version control system (i.e.: git), so you can easily rollback whenever the system breaks.
In your case you could try to search for comma inside every single files of your working directory (escluding vendor and other unimportant folders such as storage)
If you have a debugger you could try to step into to check every single call from the beggining

Related

Is eval() functionally the same as include in PHP, given the following example?

I am working within an existing PHP program that has an established way that it dynamically loads certain PHP files for rendering HTML, by doing something basically this:
try {
$includeFilePath = realpath($mySubPath);
include $includeFilePath;
} catch (Exception $e) {
//imagine code that handles error
}
Assume that both file to be included and the file containing the above method are read-only and it's not permissible to alter these actual files on disk. However the above method may be overridden by extending the class it is part of. Meanwhile the file that's being included cannot be overridden gracefully because it does not contain classes, just a mix of PHP and HTML instructions (old school "phtml").
Now what I want to do instead is:
try {
$includeFilePath = realpath($mySubPath);
$codeToModify = substr(file_get_contents($includeFilePath),5);
$codeToEval = $this->modifyCode($codeToModify);
eval($codeToExecute);
} catch (Exception $e) {
//imagine code that handles error
}
... where the modifyCode($str) method is defined elsewhere, and basically what it would do is (a) check the existing file against a pre-known hash checksum value to ensure it has not been modified, and (b) inject known safe code into it in order to add additional functionality to the application (it's "known safe" because we also would use a similar hash verification system on it and validate it).
Now my question is, assuming that security risks are not a concern here, is there any functional reason why eval would be problematic?
Note: no files we'd be including have closing html tags, only opening ones. I chose to use substr($str,5) to trim the opening tag as opposed to adding opening and closing tags as I've seen done elsewhere; that ought to work, right?
Explanation:
Since I anticipate a lot of you might wonder, "Why would you want to do that?", the reason is fairly complicated, but I'll try to explain it. The alternative to doing the above would be to include an entirely different file: one that already contains the custom code I want to use on top of the code from the base file. However the custom code I want to use is all additional code not present in the original base file, so we would end up with a fair amount of duplicated code instead of a more elegant solution where only the new code is "injected" into the base code prior to execution. Even still, using a new file that contains both the old and new code would technically work fine for now.
The problem is, though, in the future it's entirely possible that when we upgrade the base program, there will be changes to the original file (the one that's been effectively overridden by using my custom version of it). If that happens, our override would continue to rely on the previous version's code for that file, since the part of it that carried over from the original base system would no longer match up with the new version's normal default code for that file.
So, to address that problem, I want to go with the method of injecting the code using my custom modifyCode($str) method. That method can tell if there's been any updates to the original file (whether due to a hacker or due to system update) and it would be able to then warn the admin to check out why this code has changed, and issue an approval before executing the modified version of the code by updating the checksum with the hash of the new version of the file to be overridden. That way we can safely update the system and know it will fall back on the default behavior of the new version of the system rather than continue to run old code (which risks breaking the system) or adding mods intended for old versions of the code to new versions of the code that they haven't yet been tested on.
I hope that makes sense.
No. Call stack would be changed (error messages, magic constant __FILE__). Relative includes in evaled code could be broken. Two new variables $codeToModify, $codeToEval would appear in evaled code scope. Evaled code would not be cached. Parse error inside evaled code does not interrupt whole script. Eval could be disabled with Suhosin.

Any way to subvert class redeclaration issue? No namespaces

Heads up: I dont have the possibility to rename the classes or use name spaces for this.
Im looking for any crazy way to subvert class redeclaration issues in php. I actually only need 3 static variables from a web application, but the only way to get them requires including a file that declares a user class. However I already have a user class, so I get an error.
I tried to no avail to include the file in a class hoping it would isolate the included file - But no.
I tried reading an interface file I created that just echos the 3 values, but that actually just reads the php code and not the rendered values.
Is there anything like an opto-isolation system for code?
The only think I can think of is using ajax to do it, but it seems super sketchy. Is there a plain php version of this?
(Was a comment, but got too long.) Doesn't sound doable with your constraints. (You might need to show some code.) -- But if you are asking for a crazy way, and the option to rename the classes just applies to not editing the php script, then:
Load the include file into a variable, then transform it, and finally eval:
$source = file_get_contents("user.php");
$source = str_replace("class user", "class workaround_123", $source);
eval($source); // will give you a workaround_user instead of class conflict
Someone will probably comment on the advisability of eval... But it foremost depends on your code/situation if that's an applicable wacky workaround.
Alternatively you could invoke the user fetching code with a separate PHP process :
exec("QUERY_STRING=user=123 php-cgi user.php");
You could tokenize the whole file and go through it "by hand" to find the values you need.

How to use inclued? (inclued_get_data())

My first question is this. I thought the inclued tool would be useful to generate a file which contains information about how php-files are connected through include- and require-statements and it would especially be able to collect the necessary information just by parsing the code ... thing is I can't/don't want to execute the code to get the include-information. Though all example I found seem to require running the project.
Here http://php.net/manual/en/inclued.examples-implementation.php you'll find following example:
<?php
// File to store the inclued information
$fp = fopen('/tmp/wp.ser', 'w');
if ($fp) {
$clue = inclued_get_data();
if ($clue) {
fwrite($fp, serialize($clue));
}
fclose($fp);
}
?>
But what is that supposed to do? As far as I understand 'inclued_get_data()' it's just going to get information about which files are included in that file - none - then serializes the containing data-structure and writes it to '/tmp/wp.ser'. What am I missing here?
Then again if you enable the inclued-extension like this in php.ini:
extension=inclued.so
inclued.enabled=1
inclued.dumpdir=/tmp
the inclued-extension is invoked on a request of a site and it logs all inclusions that have been executed - right?
Anyway, it seems like none of those two options help me finding out about all inclusions of a whole project. Right? And if that is correct, then do you know a way to that without having to write a parser?
My understanding of inclued (after using it several times) is that you will need to have it execute on live code, as opposed to just parsing.
This is required for two reasons:
that's how it works (it's attaching to those functions in the Zend core to monitor them)
that's how it's able to resolve conditional includes (the information it provides is true for the run on which it was executed). Without this it wouldn't be able to understand files loaded by an autoloader, or any sort of conditional processing (such as loading a controller in the average framework).

Print the executed PHP code (Path of code taken)

I have a script with alot of nested includes and functions calling each other from lots of if conditions. Basically, its a coding nightmare.
Is there any way i can "PRINT" the PHP code executed ? I mean, print the actual flow of the code and the path taken by the script from start to end ?
PHP can't do this out of the box. You'd need to install the xDebug extension on your PHP development machine. Once installed, you could use the code coverage function to determine which lines have executed.
Lacking that, I'd create a simple debug function to include at the top of your code
public function myDebugString($string)
{
file_put_contents('/tmp/debug.log',"$string\n",FILE_APPEND);
return;
}
and then add calls to this throughout you code
myDebugString('Called at ' . __LINE__);
And then tail the log file created. Removing the debug statements is a simple find/replace operation for your editor once you're done.
Many frameworks have debugging objects that do way more than this built it, but if you're dealing with stand alone code something simple like this should be enough to get you by.
You can try debug_backtrace() or debug_print_backtrace().
Additionally, I recommend using Xdebug. It prints a very useful stack trace on exceptions (you can configure it to print out every method parameter and every local variable (xdebug.collect_params=4 and xdebug.show_local_vars=on configuration parameters).
Take a look at code coverage tools. This allows you to identify those functions and lines of code that are actually executed when a script runs

So Echo isn't echoing

So I've got all of this really neato PHP code and I've started doing some reuse with functions out of necessity. I'm debugging, trying to figure out why I can't delete comments on my website while I'm deleting folder (because who wants orphaned comments?)
So I have a call to deletefolder( $parent) inside a file called deletefolder.php. This a function that will recursively traverse my tree structure.
I've include another file inside deletefolder.php. The file is call helpers.php, and it contains the deletefolder function.
The deletefolder function calls deletecomments (kills all the comments per file) and delete file (which kills the file itself).
Now, all of it is just slathered with echo statements to help me figure out what's going on. When I call this combination of functions from other locations I don't seem to have a problem getting messages. But when I call them from the deletefolder.php page I don't get any. Does anybody know why this would be the case?
A few things you might want to verify.
Check the source of the output. You might be echoing straight in a middle of a HTML comment or a tag which is hiding the output.
Are you using output buffering (ob_start()) ? You might be clearing the buffer at some point in your code and forgot all about it.
Different files with the same name but not in the same directory. Do a die() in your function to make sure it actually reaches your code. You might be editing/including a copy of your file (happened to me quite a few times).
Well, I seriously doubt you've found a bug in the echo command, so the problem is with your program logic somewhere. Without seeing your code, it's impossible to say really. Perhaps there's some variable being set or unset unexpectedly, or you're not actually include()ing the files properly.

Categories