1

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.

3
  • redirect output where? to a file? Commented Apr 17, 2010 at 3:36
  • 1
    Possibly. Anywhere would be nice :) Commented Apr 17, 2010 at 3:37
  • See... I have a script that has data piped in and the output is discarded. I want to capture it somehow. Commented Apr 17, 2010 at 3:37

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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";

1 Comment

Will this work for syntax errors? Will they get displayed? [Better add that to the question...]
1

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

./myscript | myfile.php &> out.txt

Comments

-2

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

4 Comments

Like Parse error: syntax error, unexpected $end in C:\XAMPP\htdocs\test.php(5) : eval()'d code on line 10
Those kind of errors. Maybe not compiler errors technically.
@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.
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.