0

I have a little question:

public function backend()
{
    $form = $_POST;

    // execute this code in another thread (don't wait to finish)
    SearchOnGoogle($form);

    // redirect instantly (and function "SearchOnGoogle" works in background);
    return redirect('/');
}

How can I do this thing? I tried a lot of things, and the function redirect is executed when SearchOnGoogle finishies execution.

georege
  • 3
  • 3

1 Answers1

0

If you want to do this within PHP then you can use curl_multi-exec(). This does does not execute "in the background" - but most of the time a client is retrieving content over HTTP, it is simply waiting for data to pass across the network. The curl_multi_select() function deals with checking the task(s) to see if if the local machine needs to do anything or if any data has arrived from the remote system.

The documentation for curl_multi_exec() in the PHP manual is (IMHO) not on a par with the writeups for other functions. There is a deeper dive here, briefly....

$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

$requests=array($ch1, $ch2);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active=count($requests);
$started=microtime(true);

for ($x=0; $x<=4 && $active; $x++) {
        curl_multi_exec($mh, $active);
        // we wait for a bit to allow stuff TCP handshakes to complete and so forth...      
        curl_mutli_select($mh, 0.02) 
}

do_something_useful();

do {
        // wait for everything to finish...
        curl_multi_exec($mh, $active);
        if ($active) {
            curl_mutli_select($mh, 0.05);
            use_some_spare_cpu_cuycles_here();
        }
        // until all the results are in or a timeout occurs
} while ($active > 0 && (MAX_RUNTIME<microtime(true)=$started); 
symcbean
  • 47,736
  • 6
  • 59
  • 94