var_dump has unreadable output - php

I have a method to dump a var_dump output to a file, as such:
function dumpToFile($object) {
$file = "c:/tmp/php.log";
ob_start();
var_dump($object);
$output = ob_get_clean();
$fh = fopen($file, "a+");
fwrite($fh, $output."\r\n");
}
Out of nowhere, the output of this is always starting with a tag like this and has some characters that are HTML encoded, like &quot
<pre class='xdebug-var-dump'> dump content... </pre>
I don't remember changing the PHP.ini file, any ideas ? I'm using php-cgi.exe under Windows.
var_dump itself outputs the garbled data, so it's not my method as far as I can see.

Seems like your xdebug has been enabled. See below post on how to disable:
https://stackoverflow.com/a/8754934

Related

PHP File Handling (Download Counter) Reading file data as a number, writing it as that plus 1

I'm trying to make a download counter in a website for a video game in PHP, but for some reason, instead of incrementing the contents of the downloadcount.txt file by 1, it takes the number, increments it, and appends it to the end of the file. How could I just make it replace the file contents instead of appending it?
Here's the source:
<?php
ob_start();
$newURL = 'versions/v1.0.0aplha/Dungeon1UP.zip';
//header('Location: '.$newURL);
//increment download counter
$file = fopen("downloadcount.txt", "w+") or die("Unable to open file!");
$content = fread($file,filesize("downloadcount.txt"));
echo $content;
$output = (int) $content + 1;
//$output = 'test';
fwrite($file, $output);
fclose($file);
ob_end_flush();
?>
The number in the file is supposed to increase by one every time, but instead, it gives me numbers like this: 101110121011101310111012101110149.2233720368548E+189.2233720368548E+189.2233720368548E+18
As correctly pointed out in one of the comments, for your specific case you can use fseek ( $file, 0 ) right before writing, such as:
fseek ( $file, 0 );
fwrite($file, $output);
Or even simpler you can rewind($file) before writing, this will ensure that the next write happens at byte 0 - ie the start of the file.
The reason why the file gets appended it is because you're opening the file in append and truncate mode, that is "w+". You have to open it in readwrite mode in case you do not want to reset the contents, just "r+" on your fopen, such as:
fopen("downloadcount.txt", "r+")
Just make sure the file exists before writing!
Please see fopen modes here:
https://www.php.net/manual/en/function.fopen.php
And working code here:
https://bpaste.net/show/iasj
It will be much simpler to use file_get_contents/file_put_contents:
// update with more precise path to file:
$content = file_get_contents(__DIR__ . "/downloadcount.txt");
echo $content;
$output = (int) $content + 1;
// by default `file_put_contents` overwrites file content
file_put_contents(__DIR__ . "/downloadcount.txt", $output);
That appending should just be a typecasting problem, but I would not encourage you to handle counts the file way. In order to count the number of downloads for a file, it's better to make a database update of a row using transactions to handle concurrency properly, as doing it the file way could compromise accuracy.
You can get the content, check if the file has data. If not initialise to 0 and then just replace the content.
$fileContent = file_get_contents("downloadcount.txt");
$content = (!empty($fileContent) ? $fileContent : 0);
$content++;
file_put_contents('downloadcount.txt', $content);
Check $str or directly content inside the file

Will md5(file_contents_as_string) equal md5_file(/path/to/file)?

If I do:
<?php echo md5(file_get_contents("/path/to/file")) ?>
...will this always produce the same hash as:
<?php echo md5_file("/path/to/file") ?>
Yes they return the same:
var_dump(md5(file_get_contents(__FILE__)));
var_dump(md5_file(__FILE__));
which returns this in my case:
string(32) "4d2aec3ae83694513cb9bde0617deeea"
string(32) "4d2aec3ae83694513cb9bde0617deeea"
Edit:
Take a look at the source code of both functions: https://github.com/php/php-src/blob/master/ext/standard/md5.c (Line 47 & 76). They both use the same functions to generate the hash except that the md5_file() function opens the file first.
2nd Edit:
Basically the md5_file() function generates the hash based on the file contents, not on the file meta data like the filename. This is the same way md5sum on Linux systems work.
See this example:
pr#testumgebung:~# echo foobar > foo.txt
pr#testumgebung:~# md5sum foo.txt
14758f1afd44c09b7992073ccf00b43d foo.txt
pr#testumgebung:~# mv foo.txt bar.txt
pr#testumgebung:~# md5sum bar.txt
14758f1afd44c09b7992073ccf00b43d bar.txt
md5_file command just hashs the content of a file with md5.
If you refer to the old md5_file PHP implementation (but the principle is still the same) source :
function php_compat_md5_file($filename, $raw_output = false)
{
// ...
// removed protections
if ($fsize = #filesize($filename)) {
$data = fread($fh, $fsize);
} else {
$data = '';
while (!feof($fh)) {
$data .= fread($fh, 8192);
}
}
fclose($fh);
// Return
$data = md5($data);
if ($raw_output === true) {
$data = pack('H*', $data);
}
return $data;
}
So if you hash with md5 any string or content, you will always get the same result as md5_file (for the same encoding and file content).
In that case, if you hash by md5 the content of a file with file_get_content() or if you use md5_file or even if you use md5 command with the same content as your file content, you will always get the same result.
By example, you could change the file name of a file, and for two different files, with the same content, they will produce the same md5 hash.
By example:
Considering two files containing "stackoverflow" (without the quotes) named 1.txt and 2.txt
md5_file("1.txt");
md5_file("2.txt");
would output
73868cb1848a216984dca1b6b0ee37bc
You will have the exact same result if you md5("stackoverflow") or if you md5(file_get_contents("1.txt")) or md5(file_get_contents("1.txt")).
based on the file contents, not on the file metadata like the BOM or filename
That's not correct about BOM.
BOM is a part of file content, you can see its three bytes in any non-unicode file editor.
Yes, I tried it for several times.
In my case, result for:
<?php echo md5(file_get_contents("1.php")) ?>
<br/>
<?php echo md5_file("1.php") ?>
Produce output as:
660d4e394937c10cd1c16a98f44457c2
660d4e394937c10cd1c16a98f44457c2
Which seems equivalent on both lines.

Using print_r in ob_start

As mentioned in the manual it's not working. i tried var_dump it too suffers from the same problem.
ob_start()
$debugdata=print_r ($var,true)
This prints the result on screen than storing to a variable
The second parameter of print_r is $return which allows the output to be returned as a string rather than outputting it:
$debugData = print_r($var, true);
There is no need to use output buffering for this, and in fact it cannot be used. You will need to end the output buffering before this and then restart the buffering after your print_r call:
ob_start();
// stuff
$output = ob_end_clean();
$debugData = print_r($var, true);
ob_start();
// more stuff
$output .= ob_end_clean();
EDIT: Another option is to nest output buffers and have an inner buffer do the print_r work:
ob_start(); // your original start
// stuff
ob_start();
print_r($var);
$debugData = ob_get_clean();
// more stuff
$output = ob_get_clean(); // your original end
ob_start() starts outbut buffering. But you also need to end and retrieve the contents of the buffer as well.
Here are the functions you could use:
ob_get_clean() - puts the contents of the output buffer in a variable, ends and cleans the buffer.
ob_start();
print_r($foo);
$output = ob_get_clean();
ob_get_contents() - fetches the contents of the output buffer without closing or cleaning it.
ob_end_clean() - closes and cleans the buffer.
ob_start();
print_r($foo);
$output = ob_get_contents();
ob_end_clean();
There are a few other possibilities. Please make yourself familiar with the output buffering functions.
Also, a remark. You don't just assign the output of print_r to a variable. You just print stuff as if you were printing it on the screen. With output buffering on, all output will be buffered instead of being sent to stdout immediately. So, first you print_r, then retrieve the contents of the buffer.
[EDIT]
In the light of the conversation going on in the comments, I recommend having a look at the notes section of the print_r() manual. As #RomiHalasz and #cbuckley observe, due to print_r's internal output buffering, it cannot be used in conjunction with ob_start()
while the second parametre, return, is used, as the two will collide.
You have to EITHER use output buffering and plain print_r (with only the first parametre), or end the output buffering before you use print_r with the second parametre.
Either this:
ob_start();
print_r($foo);
$output = ob_get_clean();
or this:
ob_start();
// blah
$output = ob_get_clean();
$output .= print_r($foo,true);
ob_start();
// blah
$output .= ob_get_clean();

Writing some data to a specific area within a file in PHP

I'm experimenting with fopen for the first time and was wondering if it was possible to search for a particular section within a file before adding or replacing that content with data?
Ideally, I'd like to:
Use fopen to get the file
Search for a comment called <!-- test -->
Replace that comment with new data.
This possible? (for the record - Appending data to the end of the file or adding new data to a specific line number would not work for what I'm working on as the file is constantly changing).
Thanks!
<?php
// make sure radio is set
if( isset($_POST['enableSocialIcons']) )
{
// Open file for read and string modification
$file = "/test";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
$new_contents = str_replace("hello world", "hello", $contents);
fclose($fh);
// Open file to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_contents);
fclose($fh);
}
?>
From: http://www.php.net/manual/en/function.fopen.php#81325
EDIT: To see what exactly is getting sent by your form do this at the top of the PHP file you're posting to:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;
?>
If you read the entire file in then use something str_replace to make the change, you should be able to get what you want.

Read Data From Text File PHP

I'm just wondering how I can read a text file in php, I'd like to have it display the last 200 entries (their each on a new line) from the text file.
Like
John White
Jane Does
John Does
Someones Name
and so on
Thanks!
Use fopen and fgets, or possibly just file.
There are several methods for reading text from files in PHP.
You could use fgets, fread, etc. Load the file into a dynamic array, then just output the last 200 elements of that array.
file will get the contents of a file and put it into an array. After that, it's like JYelton said, output the last 200 elements.
This outputs last 200 rows. Last row first:
$lines = file("filename.txt");
$top200 = array_slice(array_reverse($lines),0,200);
foreach($top200 as $line)
{
echo $line . "<br />";
}
<?php
$myfile = fopen("file_name.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
You may use this

Categories