Search code examples
phphttpresponsehttp-response-codes

Implementation for http_response_data in PHP?


As we know, there is the http_response_code function to get the response code from the server side by PHP, is there any implementation for similar function http_response_data to get the response data?

UPDATE: This http_response_data function will be called in the shutdown handler to track the whole website activity.

register_shutdown_function('shutdownHandler');

Solution

  • Generally, you put data into the response body by commands like echo or print. Using output buffering this data does not get immediately sent out to the client, but they get added to an output buffer. You can inspect and modify this buffer prior to it being sent back to the client via a number native PHP methods.

    So, you can:

    • Enable an output buffer
    • Write to the buffer
    • Get a copy of the entire buffer contents when finished writing to it
    • Flush the buffer
    • Smile, drink soda, and eat some pie

    From the register_shutdown_function() documentation:

    The shutdown callbacks are executed as the part of the request, so it's possible to send output from them and access output buffers.

    Here's the PHP documentation for manipulating the buffer: http://php.net/manual/en/book.outcontrol.php

    A good overview of using the buffering functions is here: https://benramsey.com/articles/output-buffering/