PHP processing after the request has completed
If you want to perform any time sensitive processing without the user waiting on you, you can use the following technique.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php ob_start(); // Perform usual tasks $response = ob_get_clean(); header("Connection: close"); header("Content-Length: " . strlen($response)); echo $response; flush(); // Perform time sensitive tasks // The users web browser is done loading // To test: sleep(15); ?> |
This is useful for situations where an “as-it happens” action must be performed, but you can’t afford to make the user wait.
For example, every time a user logs in to your website you want to tweet the action in twitter. This method will ensure an instantaneous update while removing the complexity of using a background task to manage these actions.
Beware if you use ob_gzhandler() as your callback function for ob_start(), there are encoding issues.
Personally I don’t really like this solution because of the risk of the users browser ignoring the headers and waiting anyway. I’d rather keep these types of operations separate from the usual page loads.
Tags: php
-
Harun
