Execution Lifetime of a PHP script

By: Andi, Stig and Derick  

When embedded in a web server, PHP scripts usually do their job quickly and exit. This paradigm does not fit when using CLI; your scripts may run forever, or at least until the next power failure. For example, if you write a daemon (UNIX lingo for a server process running in the background), the script will typically hang around forever, waiting for some kind of input to process, a timer signal, or something similar.

One of the practical consequences of this is that sloppy coding styles, which are relatively harmless in a short web-server request, have more of an impact in a long-running script. For example, when you open a file or database connection but don’t explicitly close it, PHP closes it for you at the end of therequest. But in a long-running script, “at the end of the request” is not until the script exits, which it does not even have to do.

This does not have to be a problem, because PHP also frees resources when they are no longer referenced. But keep this in mind when programming scripts that are supposed to run for some time. If you are finished with a file, close the file descriptor. If you’re finished with database operations, disconnect. If you don’t need that big array anymore, empty it.

Archived Comments

Most Viewed Articles (in PHP )

Polymorphism in PHP

Using class within a function in PHP

Installing PHP with nginx-server under windows


PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Function to force strict boolean values in PHP

Function to convert strings to strict booleans in PHP

Function to sort array by elements and count of element in PHP

Malware: global $ob_starting;

Function to return number of digits of an integer in PHP

Latest Articles (in PHP)

Comment on this tutorial