Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most simple way to start a new process/thread in PHP

Scenario:

  1. Shared hosting, so no ability to install new extensions + no CRON
  2. A submitted request needs to perform some heavy processes.
  3. I want the answer to the client to go as fast as possible, and the heavy lifting to continue immediately, but not stop the client.
  4. can be on a new thread (if it is possible) also no problem with starting a new process.

What is the best way to do this?

like image 411
Itay Moav -Malimovka Avatar asked Dec 17 '11 22:12

Itay Moav -Malimovka


2 Answers

On *nix:

exec('/path/to/executable > /dev/null 2>&1 &');

On Windows:

$WshShell = new COM('WScript.Shell'); 
$oExec = $WshShell->Run('C:\path\to\executable.exe', 0, false);

Both of these will spawn a new process that will run a-synchronously, completely disconnected from the parent. As long as your host allows you to do it.

like image 163
DaveRandom Avatar answered Sep 21 '22 06:09

DaveRandom


You can google by key: php continue processing after closing connection.

The following links that relate to your problem, are:

  • Continue processing after closing connection
  • http://php-fpm.org/wiki/Features#fastcgi_finish_request.28.29
  • http://www.php.net/manual/en/features.connection-handling.php

You can use belong command to continue executing without user aborting

ignore_user_abort(true);
set_time_limit(0);

You use fastcgi_finish_request to alert client to stop the response output. And your scripts will continue to be executed.

An example:

// redirecting...
ignore_user_abort(true);
set_time_limit(0);
header("Location: ".$redirectUrl, true);
header("Connection: close", true);
header("Content-Length: 0", true);
ob_end_flush();
flush();
fastcgi_finish_request(); // important when using php-fpm!

sleep (5); // User won't feel this sleep because he'll already be away

// do some work after user has been redirected
like image 39
Nguyen Van Vinh Avatar answered Sep 21 '22 06:09

Nguyen Van Vinh