Suddenly, an application isn't any longer able to output ZIP files. An inspection revealed the cause: The first character of the ZIP is a blank, which breaks the ZIP format spec.
To track down this problem, I enabled CStatementTracer, which prints each line of executed code to a log file. Didn't help. [Remark: declare(ticks=1); doesn't seem to trap each line of executed code]
I then set an output handler like so:
function callback( $buffer ) {
$deb = print_r( debug_backtrace(), TRUE );
file_put_contents( './statementTrager.log', $deb );
return $buffer;
}
ob_start("callback", 1 );
Unfortunately, this handler isn't called at all.
Q: Does a generic / canonical solution exists, which identifies the file / line of PHP-code, which emits the first character.
A solution, that finds the loc whatever other code gets executed.
Remarks:
Not even a single PHP file is closed using ?>
Meanwhile I found the suspicious like of code: A blank in front of a starting
Still, I'd like to get hints regarding a programmatic solution. Preferrably a solution written in pure PHP.
https://linux.die.net/man/1/strace is probably the most reliable tool to find out where the output comes from. Assuming you are on Linux. There must be similar tools for other platforms.
Although it will not give you the line of the php code, you can analyse the context of system calls made before and after the offensive character was sent. Usually it is enough to identify where the problem originates.
It is quite time consuming process though. Should be used as the last resort.
Related
I found this simple function that simply clears the contents of a file:
function createEmptyFile($filename)
{
//
$fp = fopen($filename, 'w');
//
fclose($fp);
}
For example, resets the log, or something else.
But I have a question whether this function is really 100% safe, that is, its behavior is uniquely determined, and the result will be as expected.
I have a strange feeling that there is a possibility that the file: may not be cleaned, or may be damaged, or filled with random data in some case.
I understand that perhaps this is all prejudice, but I would like to know exactly how right it is. In particular, I am confused by the absence of any command between opening and closing the handle.
For example, I assume that if the PHP interpreter will perform optimization, then due to the lack of a command, between opening and closing the handle, it may skip this block, or something like that.
Sorry if I create a panic in vain.
I am confused by the absence of any command between opening and closing the handle.
Let me put something to the front:
The left '{' and the right '}' bracket are flow-controls and need commands in between. fopen() and fclose() are not. Though these are only 2 commands they inherit many more.
That said lets look into the tasks of them: fopen() does ...
(a) look for the specific file,
(b) if the file is not existing it creates the file
(c) opens the file for writing only,
(d) redirects the file-pointer to the beginning of the file,
(e) if the file is longer then zero it will truncate it to zero length.
In particular, I am confused by the absence of any command between opening and closing the handle.
You see there are many "commands" in between. So don't worry.
I have a strange feeling that there is a possibility that the file: may not be cleaned
To be exact, the file is not cleared, it is truncated to zero length. The earlier data of this file is still in the memory of your data-storage. But this is subject to your operation-system. There exist programs to delete these data-blocks entirely.
[...], or may be damaged
I don't understand the question. You are going to delete a file - what more damage do you expect?
[...], or filled with random data in some case.
That is C-style for creating variables by setting up a pointer to free memory but not clearing the data earlier was in it and giving this duty to you. But here it is just a truncate and not a redirecting of the file pointer. This fear could be ignored.
But I have a question whether this function is really 100% safe, that is, its behavior is uniquely determined, and the result will be as expected.
Yes, normally the behavior is uniquely determined. But you have to expect some side-effects:
if the file does not exist it will be created. You need to have write-access to the directory. (else it will come back with false)
if you have no write-access to the file it will come back with false.
if your php-environment uses "safe mode" the possible difference of owner and user leads to a fail of fopen(). You need to be sure that the file is worked only by you.
It can happen that you just write fopen() and don't check the return-parameter. That may cause a problem and lead to: not 100% safe if you don't react correctly.
So - yes fopen() and fclose() are sufficient, correct and inform you if the work is not done properly.
I have been using PHP Desktop which works great however if i want to share a project i did not want users to see everything in the code.
I tried the suggested code protectors but nothing seems to work for the current version. I found a simple PHP obfuscator code but it gives an error. it also generates some output but fails to echo a result.
The error:
Warning: php_strip_whitespace(): failed to open stream: No error in C:\xampp\htdocs\PHP Obfuscator\Obfus.php on line 11
The code:
<?php
//$infile = file_get_contents("Input.php");
$infile = '<?php echo "Hello World 123"; ?>';
$outfile = "Output.php";
echo "Processing $infile to $outfile\n";
$data="ob_end_clean();?>";
$data.=php_strip_whitespace($infile); // Remove whitespace
$data.=gzcompress($data,9); // Compress data
$data=base64_encode($data); // Encode in base64
// Generate output text
$out='<?ob_start();$a=\''.$data.'\';eval(gzuncompress(base64_decode($a)));$v=ob_get_contents();ob_end_clean();?>';
// Write output text
//file_put_contents($outfile,$out);
echo $out;
?>
Does anyone know how to fix this code to make reading the PHP harder for regular users that would download the exe?
It would be to prevent non coders only as it would be packed in a exe, i know it's not a secure method to hide code sources.
Also does anyone have blenc etc working with the current version? I had no luck even after following the tutorial.
The argument for php_strip_whitespace() has to be a file name, not a raw string. Write the data to a temporary file, then clean it, then delete the temporary file when you're done.
In any case, you're going about this all wrong. Security through obfuscation isn't really security at all. Any competent programmer will recognize the base64 encoding, and it's trivial to decompress the compressed data. Then, a decent IDE could restore the missing whitespace with a couple of keystrokes. Besides, your code, with its eval(gzuncompress(base64_decode($a))), literally tells the user what you did to obfuscate the code in the first place.
If you don't want users to access the source, don't distribute the source, period. Use an API or a compiler, not an obfuscator.
This question already has answers here:
making print_r use PHP_EOL
(5 answers)
Closed 6 years ago.
I've been coding in PHP for a long time (15+ years now), and I usually do so on a Windows OS, though most of the time it's for execution on Linux servers. Over the years I've run up against an annoyance that, while not important, has proved to be a bit irritating, and I've gotten to the point where I want to see if I can address it somehow. Here's the problem:
When coding, I often find it useful to output the contents of an array to a text file so that I can view it's contents. For example:
$fileArray = file('path/to/file');
$faString = print_r($fileArray, true);
$save = file_put_contents('fileArray.txt', $faString);
Now when I open the file fileArray.txt in Notepad, the contents of the file are all displayed on a single line, rather than the nice, pretty structure seen if the file were opened in Wordpad. This is because, regardless of OS, PHP's print_r function uses \n for newlines, rather than \r\n. I can certainly perform such replacement myself by simply adding just one line of code to make the necessary replacements, ans therein lies the problem. That one, single line of extra code translates back through my years into literally hundreds of extra steps that should not be necessary. I'm a lazy coder, and this has become unacceptable.
Currently, on my dev machine, I've got a different sort of work-around in place (shown below), but this has it's own set of problems, so I'd like to find a way to "coerce" PHP into putting in the "proper" newline characters without all that extra code. I doubt that this is likely to be possible, but I'll never find out if I never ask, so...
Anyway, my current work-around goes like this. I have, in my PHP include path, a file (print_w.php) which includes the following code:
<?php
function print_w($in, $saveToString = false) {
$out = print_r($in, true);
$out = str_replace("\n", "\r\n", $out);
switch ($saveToString) {
case true: return $out;
default: echo $out;
}
}
?>
I also have auto_prepend_file set to this same file in php.ini, so that it automatically includes it every time PHP executes a script on my dev machine. I then use the function print_w instead of print_r while testing my scripts. This works well, so long as when I upload a script to a remote server I make sure that all references to the function print_w are removed or commented out. If I miss one, I (of course) get a fatal error, which can prove more frustrating than the original problem, but I make it a point to carefully proofread my code prior to uploading, so it's not often an issue.
So after all that rambling, my question is, Is there a way to change the behavior of print_r (or similar PHP functions) to use Windows newlines, rather than Linux newlines on a Windows machine?
Thanks for your time.
Ok, after further research, I've found a better work-around that suite my needs, and eliminates the need to call a custom function instead of print_r. This new work-around goes like this:
I still have to have an included file (I've kept the same name so as not to have to mess with php.ini), and php.ini still has the auto_prepend_file setting in place, but the code in print_w.php is changes a bit:
<?php
rename_function('print_r', 'print_rw');
function print_r($in, $saveToString = false) {
$out = print_rw($in, true);
$out = str_replace("\n", "\r\n", $out);
switch ($saveToString) {
case true: return $out;
default: echo $out;
}
}
?>
This effectively alters the behavior of the print_r function on my local machine, without my having to call custom functions, and having to make sure that all references to that custom function are neutralized. By using PHP's rename_function I was able to effectively rewrite how print_r behaves, making it possible to address my problem.
One of my users is experiencing odd behavior that doesn't seem to follow the PHP exec() specs.
I'm invoking like so:
exec($cmd, $out, $ret);
I would expect this not to generate any output, but the user is seeing an error stack trace from $cmd printed when it errors out. Nothing in my code outputs anything, so it has to be coming out of exec(), but how? Am I misinterpreting the documentation?
I expect I could trap this inside of an output buffer then dispose of it, but I would rather prevent it... And whatever I do, I want to understand why this is happening first.
NOTE: I'm working on getting more specifics on PHP version and other d etails from the users, but do not have that information at this time. All I can say is that it is >= 5.2.4.
What you experience is the normal unix behaviour:
An executed command always has two output pipes: standard out and error out. The documentation states that all output is given back. That does not include stuff written to the error output. That is using a separate pipe py purpose to separate error and normal output. If you want to capture that too you have to change the command you execute, typically you map the error output to the standard output by appending a 2>&1.
I'm trying to debug a plugin-bloated Wordpress installation; so I've added a very simple homebrew logger that records all the callbacks, which are basically listed in a single, ultimately 250+ row multidimensional array in Wordpress (I can't use print_r() because I need to catch them right before they are called).
My logger line is $logger->log("\t" . $callback . "\n");
The logger produces a dandy text file in normal situations, but at two points during this particular task it is adding something which causes my log file to no longer be encoded properly. Gedit (I'm on Ubuntu) won't open the file, claiming to not understand the encoding. In vim, the culprit corrupt callback (which I could not find in the debugger, looking at the array) is about in the middle and printed as ^#lambda_546 and at the end of file there's this cute guy ^M. The ^M and ^# are blue in my vim, which has no color theme set for .txt files. I don't know what it means.
I tried adding an is_string($callback) condition, but I get the same results.
Any ideas?
^# is a NUL character (\0) and ^M is a CR (\r). No idea why they're being generated though. You'd have to muck through the source and database to find out. geany should be able to open the file easily enough though.
Seems these cute guys are a result of your callback formatting for windows.
Mystery over. One of the callbacks was an anonymous function. Investigating the PHP create_function documentation, I saw that a commenter had noted that the created function has a name like so: chr(0) . lambda_n. Thanks PHP.
As for the \r. Well, that is more embarrassing. My logger reused some older code that I previously written which did end lines in \r\n.