To prevent the browser from timing out, and also allow you to close the page you can send the Content-Length header from the browser. This has the effect of completing the page load in the browser.

<?php
ob_start(); // place at top of script
echo str_pad('', 256); // IE needs some content
// ............... put any messages or HTML here ...............
$content_length = ob_get_length(); // length of content
header('Content-Length: ' . $content_length); // set the length of content
ob_flush(); // flush output to browser
flush();
// now you can do what you want as the browser has already loaded
// ............ run your script here ................
?>

As you can see, this is a bit hacky. If you run it in the command line, PHP automatically runs the script for ever and won't time out. You also don't need to send output for the browser, or trick the browser into completing the page load.