views:

270

answers:

4

Is there a way to redirect output of an executing PHP script?

Of course this is trivial when launching the script via the command line. But how is this accomplished after the script is started?

Note: I need to capture the syntax errors and such as well.

A: 

PHP has file i/o functions to write to a file.

http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fwrite.php

Samuel
BUT this won't output compiler errors! Very important!
George Edison
"Compiler" errors?
macek
Like `Parse error: syntax error, unexpected $end in C:\XAMPP\htdocs\test.php(5) : eval()'d code on line 10`
George Edison
Those kind of errors. Maybe not _compiler_ errors technically.
George Edison
@George - if your script can't be parsed, then there's no way it can redirect any output itself, since it can't run. So I think you're out of luck.
zombat
Oh dear! Now my problem has been made worse - wait! What if the script does nothing more than call _another_ script with the code in it and _redirect its output_?!? Genius! I figured it out!
George Edison
A: 

You can use PHP's output control even in a command line script:

echo "123\n";
ob_start();
echo "456\n";
$s = ob_get_contents();
ob_end_clean();
echo "*$s";
Ignacio Vazquez-Abrams
Will this work for syntax errors? Will they get displayed? _[Better add that to the question...]_
George Edison
No. That wouldn't work for any sort of fatal error.
Frank Farmer
A: 

Syntax errors will output to STDERR, not STDOUT. Make sure you also redirect STDERR in your pipline...

./myscript | myfile.php &> out.txt
Agoln
But I don't think I can control the launching of the script...
George Edison
+1  A: 

If you want to capture parser errors, you need to:

  1. Make sure display_errors is On

  2. Set an error_prepend_string and an error_append_string

  3. Call ob_start from an auto_prepend file that runs before every PHP file you might be executing.

  4. Use set_error_handler as you normally would, and make your callback sift through the named output buffer, looking for your custom error_prepend_string and error_append_string. If you find it, then shunt your output wherever you want it. If you don't, then let it go wherever it would normally.

Most of this can be achieved through ini_set calls, but the auto_prepend file will need to be specified in your php.ini.

Azeem.Butt
Would it be possible to see a tiny example? :)
George Edison
The only example I have is 422 lines.
Azeem.Butt