How to execute a PHP function in the background?

5

I'm using the cPanel API to add dynamically parked domains. So far so good, I send the required data via jQuery.post() only this process takes a while to complete, about 1 minute.

Are there any alternatives for the process to continue running in the background and the user to continue browsing the system? Currently the user can not navigate until the process is finished.

    
asked by anonymous 12.08.2014 / 06:06

4 answers

4

In the PHP script itself, add the following lines at the beginning:

set_time_limit( 7200 ); // Limite de tempo de execução: 2h. Deixe 0 (zero) para sem limite
ignore_user_abort( true ); // Não encerra o processamento em caso de perda de conexão

Below these lines, program normally.

I hope I have helped!

    
15.08.2014 / 22:17
2

I believe it's possible to run in the background using cURL as in the example below:

background-script.php

if ($_GET['iniciarbackground'] == 'true') { // chamada iniciada pelo ajax
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);

    // repassar ao cURL, tudo que recebeu como POST:
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);

    curl_exec($ch);
    curl_close($ch);
} else { // chamada iniciada pelo cURL
// tarefas a executar no background

}

jquery:

$.post( "background-script.php?iniciarbackground=true", { name: "John", time: "2pm" } );

Source: link

    
12.08.2014 / 14:30
0

I think the best alternative for you is to create a daemon in php, so you would have to have another server (worker) that can be cheap because you can manage a queue in a cadenced form. To do this I recommend using Gearman is excellent, the PHP documentation is here

    
12.08.2014 / 14:33
0

There must be something wrong, if I'm not mistaken, jQuery by default does ajax requests without "LOCK" the navigation, async.

In any case, make sure that requests are being made as- signually.

For users with host windows (taking advantage of the question) there is a function:

win32_create_service of PHP that allows you to run a script as a service, with options to stop, pause, etc ...

    
13.08.2014 / 14:33