0

I am creating an API that receives a post request and then returns data. This data needs to be returned immediately but then I need to execute a long running curl operation after that.

<?php
if (!empty($_POST)) {
    $numbers = isset($_POST['numbers']) ? $_POST['numbers'] : 0;
    $numbers = $numbers*$secrethash;
    $result = array("error" => false,
        "numbers" => $numbers);
    echo json_encode($result);
    $curlfunction($numbers);
    exit;

Unfortunately, data is not returned until the curl function completes which causes my application to timeout. It is possible to execute the curl in the background so my data can be returned immediately?

NinjaCoder
  • 2,381
  • 3
  • 24
  • 46
Ray Li
  • 7,601
  • 6
  • 25
  • 41
  • 1
    have a look at [this question](https://stackoverflow.com/questions/3833013/continue-php-execution-after-sending-http-response) – Shankar Nov 12 '17 at 04:35
  • 1
    Possible duplicate of [Continue PHP execution after sending HTTP response](https://stackoverflow.com/questions/3833013/continue-php-execution-after-sending-http-response) – Robert Moskal Nov 12 '17 at 04:37
  • Adding the task to a queue and then processing via cron task was the first suggestion. Is there a better method? – Ray Li Nov 12 '17 at 04:39

2 Answers2

1

You could put the function in a separate file and execute it similar to this. This would cause a separate process to be created. Maybe write the result to a file and read it. Set up your php to take your variable as a parameter.

exec("/usr/bin/php /path/to/script.php > /dev/null &");

It might be worth a shot. :-)

Jeff Mattson
  • 394
  • 3
  • 9
0

There are several options for you.

  1. You can install CRON job after outputting json content via exec() function.
  2. Make AJAX request from your page after json data was returned.
Dmitriy Buteiko
  • 624
  • 1
  • 6
  • 14
  • AJAX is not possible because this is an API that returns data. I can create 2 APIs however and have the client call the second after receiving a response from the first! Edit: Not very good API design though :P – Ray Li Nov 12 '17 at 04:41
  • Ended up creating a second API containing the CURL and calling that after receiving a response from the first. Thanks for your suggestions! – Ray Li Nov 13 '17 at 20:50