Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close connection in PHP but keep executing script

Tags:

php

buffering

Anyone know how to close the connection (besides just flush()?), but keep executing some code afterwards.

I don't want the client to see the long process that may occur after the page is done.

like image 977
Kristopher Ives Avatar asked Nov 29 '22 19:11

Kristopher Ives


1 Answers

You might want to look at pcntl_fork() -- it allows you to fork your current script and run it in a separate thread.

I used it in a project where a user uploaded a file and then the script performed various operations on it, including communicating with a third-party server, which could take a long time. After the initial upload, the script forked and displayed the next page to the user, and the parent killed itself off. The child then continued executing, and was queried by the returned page for its status using AJAX. it made the application much more responsive, and the user got feedback as to the status while it was executing.

This link has more on how to use it:

  • Thorough look at PHP's pcntl_fork() (Apr 2007; by Frans-Jan van Steenbeek)

If you can't use pcntl_fork, you can always fall back to returning a page quickly that fires an AJAX request to execute more items from a queue.


mvds reminds the following (which can apply in a specific server configuration): Don't fork the entire apache webserver, but start a separate process instead. Let that process fork off a child which lives on. Look for proc_open to get full fd interaction between your php script and the process.

like image 101
Jhong Avatar answered Dec 14 '22 09:12

Jhong