Joel
Joel

Reputation: 59

PHP - Instead of doing ECHO's to debug variable values, how to send the value to a file?

I need to debug an Application, but the ECHO $variable it is not working.

How can I send the value of the variable to a log file?

Give me some clues.

Best Regards,

Upvotes: 4

Views: 11072

Answers (5)

Ken
Ken

Reputation: 78852

trigger_error in combination with error_reporting allows you to easily log what you want on development servers, without worrying about the load on your production servers.

It adds more information than error_log:

trigger_error('foo');

results in

[Fri Apr 08 14:28:08 2011] [error] [client 192.168.0.13] PHP Notice:  foo in /data/sites/kai/public_html/foo.php on line 3

whereas error_log('foo'); results in

[Fri Apr 08 14:28:08 2011] [error] [client 192.168.0.13] foo

Upvotes: 5

Johann du Toit
Johann du Toit

Reputation: 2667

I'm with @Ali on this one. But you could always try FirePHP, it allows you to write logging information to their library and then see it much like you would normally with FireBug. Here is a small tutorial too - http://www.developertutorials.com/tutorials/php/debugging-php-with-firebug-and-firephp-365/ .

Upvotes: 1

Ali
Ali

Reputation: 3666

Personally, I think this approach is wrong. You will clutter your code with either echo statements or functions to write to a file. This has a huge maintainability cost as you have to add/remove these statements.

I recommend that you learn how to step into your code and debug using xdebug. It's the only solution that I usually recommend for people trying to see how values for a certain variable is changing during execution time.

With that said, and if you still prefer the writing to file method, then simply instead of doing an echo statement do something like the following:

$file = "log.txt";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $variableName);
fclose($fh);

Upvotes: 1

Michael J.V.
Michael J.V.

Reputation: 5609

file_put_contents('/path_to_file/file.txt', print_r($variable, true));

OR

file_put_contents('/path_to_file/file.txt', var_export($variable, true));

Upvotes: 4

S L
S L

Reputation: 14318

 error_log('some variable');

But the value of variable will be the same in log file. You must have some error above it.

Upvotes: 1

Related Questions