mrpehlivan
mrpehlivan

Reputation: 49

How to execute a function after response send in PHP

I am trying to execute a callback function after response send in php. For example in JAVA i made that using Threads. But in php after response it finish the process of script.Besides I try to implement pthreads but its too much complicated.

In my code:

if(isset($_REQUEST['x']) && $_REQUEST['x'] == "x") {
    header('Content-type: application/json');
    $data = json_decode(file_get_contents('php://input'), TRUE);
    if (!empty($data)) {
        $request = new XRequest($data['params']);
        $customParams = unserialize(file_get_contents('customParams'));
        $customParams->callCallback($request); //Calling from another PHP class
        echo(json_encode(array('status' => 'OK')));
    }
}

The request come from different server. I want to start first php echo response when response send i want to call $customParams->callCallback($request);

How can I do that? Any ideas?

Upvotes: 0

Views: 2629

Answers (2)

mrpehlivan
mrpehlivan

Reputation: 49

In php i solved my problem using bottom code. But pay attention to fastcgi_finish_request . With out this my server can not stop the first response and start callback.

Thanks.

 ob_start();
// Send your response.
echo json_encode(array('status' => 'ok')) ;

// Get the size of the output.
$size = ob_get_length();

// Disable compression (in case content length is compressed).
header("Content-Encoding: none");
header($_SERVER["SERVER_PROTOCOL"] . " 202 Accepted");
header("Status: 202 Accepted");
// Set the content length of the response.
header("Content-Length: {$size}");

// Close the connection.
header("Connection: close");
ignore_user_abort(true);
set_time_limit(0);

// Flush all output.
ob_end_flush();
ob_flush();
flush();
session_write_close(); 
fastcgi_finish_request();
// Do processing here
sleep(5);
callBackAfterResponse();

Upvotes: 2

user473305
user473305

Reputation:

PHP's concurrency model is simple and based around the fact that multiple PHP scripts can be executed simultaneously by a Web server. So typically, the way you'd implement this is by

  • Placing the body of your callback function in its own, separate script; and

  • Invoking it from the parent script through an outgoing Web request (using cURL or similar).

That is, have the first PHP script request the second at a URL on (presumably) the same Web server, just as though a user had opened the two URLs sequentially in their Web browser. This way, the second script can continue to run after the first has completed its response and terminated.

More sophisticated approaches are possible, involving message queues or remote-procedure call mechanisms like XML-RPC and Apache Thrift, if the second PHP script is made to run separately and continuously in its own process. But I think this will be enough for what you're trying to do.

Upvotes: 0

Related Questions