the accountant the accountant - 11 months ago 57
PHP Question

php - how to get the server response header and body

I want to get and log every request come to my PHP file and every response that my PHP file outputs.

as for the request , it is easy throw the super global variables e.g

, but I'm not sure how to get what my php file outputs to the client.
the only thing that I can do is to delay any
in my code and build one output string like
throw my php code and
it at the end of the script. like :

$response = "";
$response .= "<html> somehtml";
//somecode if($condition){ $response .= "some html"}else{$response .= "another html"}
//more code
$response .="</html>";
echo $response;
log($response); // custom function to store the response

but some times the php parser outputs warning and errors and other stuff than my response , beside I don't want to delay all the echos but I want to use echo throw my code for more convenience.

Is there a way to use echos throw my code and get my whole response including the response headers and every thing that my php server outputs?

Thank you.


You may use ob_start and its associated methods, which will hold all output in a buffer until you want to send it.

For example:


echo 'weeee';

$output = ob_get_contents(); // get the contents from the buffer
log($output); // your custom function

ob_end_flush(); // send the output to the browser and turn off buffering