Home > tutorial > Execute Code After Browser Finishes Loading

Execute Code After Browser Finishes Loading

November 25th, 2009

How to execute a script after the browser stops loading

Recently I needed to execute a bit of code but the browser was timing out. I was actually using the php exec function to tar up some files. The browser kept showing a time out page. So in order to make the browser think it was done loading and then execute this bit of script, I put everything in the buffer with ob_start(). Then when I’m ready to stop the browser I get the size of the buffer. I then set the header content-length equal to this size and flush out the buffer. Now the browser will no longer show that its loading, since it has received all the content it is going to receive. So now you can execute any script.

Here is the code


<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort();  // optional
ob_start(); 

echo "some content";

$size = ob_get_length();
 header("Content-Length: $size");
 ob_end_flush();
 flush();
//Browser done loading

//put your script here

?>

kmussel tutorial

  1. December 21st, 2009 at 15:15 | #1

    Thats a good idea, you can also use the php function “register_shutdown_function” http://php.net/manual/en/function.register-shutdown-function.php that can do a similar effect. Though of course, this is done after everything else was shutdown, so classes like “ezdb” will be gone. not sure if reinst them will work.

  1. No trackbacks yet.
Comments are closed.