How to run a php function in background separate from the main thread?

exec, php

Solution

here is sample approach with fork:

$logFile = 'app-output.txt';
$command = 'nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);" &';
$command.= ' > "'.$logFile.'" 2>&1';

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent, do nothing
} else {
     // we are the child
    exec($command);
}

a little bit another approach can be:

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent, do nothing
} else {
     // we are the child
    $logFile = 'app-output.txt';
    ob_start();
    require '/export/wiki.php';
    update_wiki(1);

    file_put_contents($logFile, ob_get_contents());
}

Problem

So I have a main php thread in which I want to call a function such that it runs in the background and doesn`t keep the user waiting since this function takes a long time to execute. ``` $logFile = 'app-output.txt'; $command = 'nohup /export/php -r "require \'/export/wiki.php\';update_wiki(1);" &'; $command.= ' > "'.$logFile.'" 2>&1'; exec($command); ``` So I tried doing it using exec function but for some reason it doesn`t run in the background. WHere wiki.php is the file having an update_wiki function that takes a long time so I want to redirect the user back to the page he came from while this fucntion does its job as it is anyways indepedent and dumps the output somewhere else

Original source