Close connection in PHP but keep executing script

后端 未结 5 1549
孤独总比滥情好
孤独总比滥情好 2021-01-14 00:10

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 proce

5条回答
  •  -上瘾入骨i
    2021-01-14 00:25

    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.

提交回复
热议问题