know you're making progress by flushing the output. I've written scripts that print a single
period and then flush the buffer each time through a long loop.
There are two ways a script may halt unexpectedly: when the script runs too long, and
when the user clicks the stop button. By default, scripts are limited to a number of
seconds specified in php.ini. This is usually 30 seconds, but you can change it. Look for
the max_execution_time directive. But 30 seconds is a good setting. In case you write a
script that could run forever, you want PHP to stop it. Otherwise a few errant scripts
could slow your server to a crawl. For the same reason, you usually want to allow users
to be able to abort a page request.
There are times when you do want a script to run to completion, and you can instruct
PHP to ignore time limits and user aborts. The set_time_limit function resets PHP's
timer. See Chapter 11 for a complete description and example. I've written some scripts
that run on their own once a night, perhaps doing a lot of work. These scripts I allow to
run for an hour or more. Likewise, ignore_user_abort tells PHP to continue even when
the user has clicked the stop button.
Instead of just letting a script run, you may wish it to halt, but deal with the reason it
halted with special code. To do this, you must first tell PHP to execute a special function
whenever a script ends. This is done with register_shutdown_function. This function
will execute regardless of why a script ended. It even executes when the script ends
normally. You can test for the reason with two functions: connection_aborted and
connection_timeout. These are described in Chapter 8.
Writing to the Browser
Three functions in PHP will send text to the browser: echo, print, and printf. Each
does the same thing: They take values and print them to the browser. The printf
function allows you to specify the format of the output rather than sending values as-is.
I've used print so far in my examples, mostly out of personal preference. I don't usually
need the formatting that printf provides. Many older PHP examples you will find on the
Web use echo because it existed in PHP2. I avoid it, because it behaves more like an
operator than a function. All three functions are discussed in Chapter 8.
It is important to remember everything you write is in the context of a Web browser.
Unless you take measures to make it otherwise, your output will be treated as HTML
text. If you send text that is HTML code, it will be decoded by the browser into its
intended form. I've been sending
via print throughout the book so far, but Listing
7.1 is a more dramatic example of this concept.
Listing 7.1 Sending HTML with print
<?
print("You're using ");
print($HTTP_USER_AGENT);
print(" to see this page.
\n");