richardaum
richardaum

Reputation: 6777

Running an external php code asynchronously

I am building a WebService, using PHP:

Basically,

  1. User sends a request to the server, via HTTP Request. 'request.php', ie.
  2. Server starts php code asynchronously. 'update.php', ie.
  3. The connection with the user is finished.
  4. The code 'update.php' is still running, and will finish after some time.
  5. The code 'update.php' is finished.

The problem is with php running asynchronously some external code.

Is that possible? Is there another way to do it? With shell_exec?

Please, I need insights! An elegant way is preferable.

Thank you!

Upvotes: 0

Views: 133

Answers (4)

soapergem
soapergem

Reputation: 9989

You could have the user connect to update.php, generate some sort of unique ID to keep track of the process, and then call fsockopen() on itself with a special GET variable to signify that it's doing the heavy lifting rather than user interaction. Close that connection immediately, and then print out the appropriate response to the user.

Meanwhile, look for the special GET variable you specified, and when present call ignore_user_abort() and proceed with whatever operations you need in that branch of the if clause. So here's a rough skeleton of what your update.php file would look like:

<?php

if ( isset($_GET['asynch']) ) {

    ignore_user_abort();

    // check for $_GET['id'] and validate,
    // then execute long-running code here

} else {

    // generate $id here

    $host = $_SERVER['SERVER_NAME'];
    $url = "/update.php?asynch&id={$id}";

    if ( $handle = fsockopen($host, 80, $n, $s, 5) ) {
        $data = "GET {$url} HTTP/1.0\r\nHost: {$host}\r\n\r\n";
        fwrite($handle, $data);
        fclose($handle);
    }

    // return a response to the user
    echo 'Response goes here';

}

?>

Upvotes: 1

guy_fawkes
guy_fawkes

Reputation: 965

Look into worker processes with Redis resque or gearman

Upvotes: 0

Andrew
Andrew

Reputation: 1776

The best approach is using message queue like RabbitMQ or even simple MySQL table.

Each time you add new task in front controller it goes to queue. Then update.php run by cron job fetch it from queue, process, save results and mark task as finished.

Also it will help you distribute load over time preventing from DoS caused by your own script.

Upvotes: 2

Lo&#239;c
Lo&#239;c

Reputation: 11943

You could build a service with PHP. Or launch a PHP script using bash : system("php myScript.php param param2 &")

Upvotes: 1

Related Questions