When does a PHP script end?
In my opinion, the web application is running all the time; so I am confused by the documentation pages that talk about the "end" of the PHP script (like this one ). Links like this seem to refer to the end of every web request, but if the end of the script ends there, doesn't that mean the OS must set up a completely new process for every request? This seems unlikely because rotating a new process is expensive and very inefficient for the entire site.
a source to share
A distinction needs to be made here: PHP is not a web server. Therefore, the end of the PHP script is irrelevant to the actual end of the web server (or at least in most cases).
Web server software that is constantly running like IIS, Apache or Lighttpd can execute PHP scripts without terminating itself. These scripts eventually stop working. How web servers runtime settings for a script depend on the approaches taken. For example, Apache 2 can indeed spawn a child process for every web request, although it doesn't set up the entire web server again every time: there is a master process that manages the children about settings and execution options.
Hence the PHP script ends when the web request ends; that is, when the script reaches an instruction that causes it to stop (such as a fatal error, instruction, exit
or the like) or when it reaches the actual end of the script's source.
EDIT About the efficiency of creating a new process for new requests.
Servers currently do not create a separate process for PHP itself: they use the PHP library to embed the language and work with it. However, servers can actually start a process for every HTTP request they receive. Apache does this with a module mpm_prefork
.
While spawning a new process does cost a lot, it potentially beats the cost of the script itself, which can be tenths of a second, which is much more than just spawning a process.
In addition, servers typically have to serve multiple clients at once; therefore, it is unthinkable to simply process each request sequentially. They have to run at the same time, which leaves developers with two options: threads or processes. PHP is not thread safe on many platforms, it is often preferable to run it in a separate process.
a source to share