Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store PHP Output To File?

Tags:

php

output

cron

I'm working on a cron php script which will run once a day. Because it runs this way, the output from the file can't be seen.

I could literally write all the messages I want into a variable, appending constantly information I want to be written to file, but this would be very tedious and I have a hunch not necessary.

Is there a PHP command to tell the write buffer to write to a log file somewhere? Is there a way to get access to what has been sent to the buffer already so that I can see the messages my script makes.

For example lets say the script says

PHP:

<?
  echo 'hello there';
  echo 'hello world';
?>

It should output to a file saying: 'hello therehello world';

Any ideas? Is this possible?

I'm already aware of

file_put_contents('log.txt', 'some data', FILE_APPEND);

This is dependent upon 'some data', when I don't know what 'some data' is unless I put it in a variable. I'm trying to catch the results of whatever PHP has outputted.

like image 247
Joseph Astrahan Avatar asked Dec 20 '22 16:12

Joseph Astrahan


2 Answers

You may want to redirect your output in crontab:

php /path/to/php/file.php >> log.txt

Or use PHP with, for example, file_put_contents():

file_put_contents('log.txt', 'some data', FILE_APPEND);

If you want to capture all PHP output, then use ob_ function, like:

ob_start();
/*
We're doing stuff..
stuff
...
and again
*/
$content = ob_get_contents();
ob_end_clean(); //here, output is cleaned. You may want to flush it with ob_end_flush()
file_put_contents('log.txt', $content, FILE_APPEND);
like image 55
Alma Do Avatar answered Dec 22 '22 06:12

Alma Do


you can use ob_start() to store script output into buffer. See php documentation ob_get_clean

  <?php

  ob_start();

  echo "Hello World";

  $out = ob_get_clean();
  $out = strtolower($out);

  var_dump($out);
  ?>
like image 31
Adam Fischer Avatar answered Dec 22 '22 05:12

Adam Fischer