Henrik
Henrik

Reputation: 1995

Forking a part of the php code

In my code I am sending a request to another page using curl_exec. I do not need the curl_exec result for the rest of the script and I do not want it to block until the curl_exec request is done and has received a response.

Any ideas if I can fork of a specific part of the script?

Or any other design ideas...?

Upvotes: 1

Views: 1326

Answers (4)

ldiqual
ldiqual

Reputation: 15365

PHP doesn't support forks and threads, but you can get rid of the response by setting a response timeout:

function curl_post_async($url, $params)
{
  foreach ($params as $key => &$val) {
    if (is_array($val)) $val = implode(',', $val);
      $post_params[] = $key.'='.urlencode($val);
  }
  $post_string = implode('&', $post_params);

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, 'curl');
  curl_setopt($ch, CURLOPT_TIMEOUT, 1);
  $result = curl_exec($ch);
  curl_close($ch);
}

Taken from: How to post an asynchronous HTTP request in PHP

As the CURL documentation, you can use CURLOPT_TIMEOUT_MS since PHP 5.2.3 and CURL 7.16.2.

Upvotes: 0

user1074324
user1074324

Reputation:

Take a look at curl-multi-exec, might be what you need:

Upvotes: 0

simshaun
simshaun

Reputation: 21466

Do you need the responses of the cURL requests?

First, the pcntl functions you would need to fork are generally a bad idea.

One method would be to place the cURL code in a separate script and exec() that script so it runs in the background.

$command = "php ..../wherever/your/kohana/cli/controller/is.php";
exec('php /path/to/curlscript.php > /dev/null &');

Outputting to /dev/null & allows the script to continue running in the background.

Alternatively, and probably a better solution, would be to implement a queue system such as Gearman or RabbitMQ.

Upvotes: 1

Evert
Evert

Reputation: 99523

Here's a few ideas:

  • Use curl_multi, and close curl at the very end of the request. You could even do this 'after shutdown'
  • Use worker scripts, with for example 'gearman'

Or:

  • You could open sockets manually, and handle stuff asynchronously using the libevent extension

Upvotes: 2

Related Questions