PHP close connection and continue execution background

1.5k Views Asked by At

I want to continue the execution of the script after closing the connection.

Here is what i tried ..

log_message('debug','Test started' );

//Show all errors   
error_reporting(E_ALL); 

//Configurations 
@ini_set("output_buffering", "Off");
//@ini_set('implicit_flush', 1);
@ini_set('zlib.output_compression', 0);

//User abort & maximum time
ignore_user_abort(true);
set_time_limit(0);

//check the level       
if (ob_get_level() == 0) {
    ob_start();
}

//Actual output
echo('hello world ...'); 

// get buffer length        
$size = ob_get_length(); 

// set content length
header("Content-Length:$size"); 

//close the connection 
header("Connection:close");  

// content encoding 
header("Content-Encoding: none"); 

//content type
header("Content-Type: text/html; charset=utf-8"); 

//Release buffer
ob_flush();
ob_end_flush();  
flush(); 

// Continue on background
// never gonna execute from here ...
sleep(20); 

//There is no aliens (class) exists , expecting error on log
$alien = new alienEncoder(); 

$alien->get_aliens( new alienDecoder() );

log_message('debug','End Test'); 

Everything works well execpt the CONTINUE part ( it stops after FLUSH), There is no error log on server.

The same code works in another host, but not here.

Please help.

SERVER : IIS 7.5 Shared, Using Codeigniter

Notes

  1. There is no alienEncoder() or something like that, so i am expecting some error log on server, but there is no error
  2. ResponceBufferLimit is set to zero
  3. using CGI/FastCgi
2

There are 2 best solutions below

4
On

PHP-FPM has a function especially for this purpose, fastcgi_finish_request()

Though I have no idea how to run it with IIS

6
On

Php is coupled with apache request system. It is started when the request is received When it finish, the request is closed.

Flush just send a partial responce to the client, but does not terminate this responce, so the browser will still hang, waiting for more content. It will consume bandwidth, apache and php ressources needlessy. Also I have to say it's a pretty bad pratice.

The best way to do computation intensive task without slowing the client is to use a defered task system. Personnaly I recommend resque (google it!). It enable you to add your action to a queue, then a worker will take all queued task and compute them.

For a cloud-hosted and almost free option that work, look at iron mq (from iron.io). They work the same way (you add a task to the queue, then the queue call a configurable url that will trigger the task computation)