Here's some normal code:
<?php
echo "hey F4LLCON!";
?>
Executed, it behaves like we expect:
% php output.php
hey F4LLCON!
Now I'll modify it to add output buffering and save to the file and write to stdout (using regular echo
calls!):
<?php
ob_start();
echo "hey F4LLCON!";
$output_so_far = ob_get_contents();
ob_clean();
file_put_contents("/tmp/catched.txt", $output_so_far);
echo $output_so_far;
?>
After executing, the output in the file catched.txt
is equal to what we got earlier (and still get) on stdout:
hey F4LLCON!
Now I'll modify it again to show how generators from PHP 5.5 will provide you with an elegant solution that doesn't need to sacrifice performance (the previous solution requires you to save all the intermediate content in one giant output buffer):
<?php
$main = function() {
yield "hey F4LLCON!";
};
$f = fopen("/tmp/catched2.txt", "wb");
foreach ($main() as $chunk) { fwrite($f, $chunk); echo $chunk; }
fclose($f);
?>
We aren't storing everything in one giant buffer, and we can still output to file and stdout simultaneously.
If you don't understand generators, here's a solution where we pass a callback "print" function to main(), and that function is used every time we want to output (only one time here).
<?php
$main = function($print_func) {
$print_func("hey F4LLCON!");
};
$f = fopen("/tmp/catched3.txt", "wb");
$main(function($output) use ($f) {
fwrite($f, $output);
echo $output;
});
fclose($f);
?>