3

I want to write a script which calls some code but continues to run after calling it. E.g

function foo()
{
 $this->load_function_a();
 $this->load_function_b();
 echo 'A and B succesfully called';
}

I want function the output to be displayed immediately rather than wait for completion of processing of both the functions. Any idea how to achieve this in PHP?

SanketR
  • 1,182
  • 14
  • 35
  • Woo... I don't think that is posible... Maybe you can use Javascript and AJAX. – Goudgeld1 Feb 07 '15 at 13:23
  • possible duplicate of [How can I run a PHP script in the background after a form is submitted?](http://stackoverflow.com/questions/4626860/how-can-i-run-a-php-script-in-the-background-after-a-form-is-submitted) – halfer Feb 07 '15 at 13:23
  • Aside from the options presented there, consider a job queue as well - Gearman or Resque. – halfer Feb 07 '15 at 13:26

3 Answers3

0

What you are looking for, are asynchronous function calls. PHP supports multi-threading, although you need the PThreads extension installed on your server. I am not very familliar with multi-threaded programming in PHP (more the .NET guy in those cases :P), but this link might help you quite a bit:

PThreads

Ziga Petek
  • 3,953
  • 5
  • 33
  • 43
0

This generally isn't easily possible with PHP running in a web environment. There may be various "hacky" methods of accomplishing this, however they will be unreliable such as calling the function in a destructor, or using register_shutdown_function()

In reality the simple answer would be:

function foo()
{
 $this->load_function_a();
 echo 'A succesfully called';
 $this->load_function_b();
}

However I'm assuming this won't suite your needs in your real code. So to solve this problem properly, the real answer would be to use some kind of queue and a queue processor. For example:

  • Having function B queue it's functionality and then later processed by a cron job.
  • Using something such a RabbitMQ or Gearman to process function B's functionality asynchronously.

Hope this helps!

A.B. Carroll
  • 2,404
  • 2
  • 17
  • 19
0

This is somehow possible if you don't want to display the function's output later.

<?php
ignore_user_abort(true);
header("Content-Length: 0");
flush();
do_your_work_here();

Instead of using Content-Length: 0 you can also print your real content length and output something. The browser will then see that it read all contents (at least he assumes that) and your script will keep running.

kelunik
  • 6,750
  • 2
  • 41
  • 70
  • Note this is still subject to max execution time. – A.B. Carroll Feb 07 '15 at 13:44
  • @kelunik: yes, i don't care about the output, so do i need to call this before I call my function a? – SanketR Feb 07 '15 at 14:01
  • @SanketR: Right, that's what I was indicating with `do_your_work_here`. Please note that something like this can easily be used to create a lot of load for your webserver. – kelunik Feb 07 '15 at 14:17