Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a PHP script start another PHP script and exit?

How can a PHP script start another PHP script, and then exit, leaving the other script running?

Also, is there any way for the 2nd script to inform the PHP script when it reaches a particular line?

like image 217
Robin Rodricks Avatar asked Sep 19 '09 05:09

Robin Rodricks


2 Answers

Here's how to do it. You tell the browser to read in the first N characters of output and then close the connection, while your script keeps running until it's done.

<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort(); // optional
ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Will not work
flush();            // Unless both are called !

// At this point, the browser has closed connection to the web server

// Do processing here
include('other_script.php');

echo('Text user will never see');
?>
like image 130
Milan Babuškov Avatar answered Sep 29 '22 11:09

Milan Babuškov


You can effectively achieve this by forking and then calling include or require.

parent.php:

<?php

    $pid = pcntl_fork();
    if ($pid == -1) {
        die("couldn't fork");
    } else if ($pid) { // parent script
        echo "Parent waiting at " . date("H:i:s") . "\n";
        pcntl_wait($status);
        echo "Parent done at " . date("H:i:s") . "\n";
    } else {
        // child script
        echo "Sleeper started at " . date("H:i:s") . "\n";
        include('sleeper.php');
        echo "Sleeper done at " . date("H:i:s") . "\n";
    }

?>

sleeper.php:

<?php
sleep(3);
?>  

Output:

$ php parent.php
Sleeper started at 01:22:02
Parent waiting at 01:22:02
Sleeper done at 01:22:05
Parent done at 01:22:05

However, forking does not inherently allow any inter-process communication, so you'd have to find some other way to inform the parent that the child has reached the specific line, like you asked in the question.

like image 38
Mark Rushakoff Avatar answered Sep 29 '22 13:09

Mark Rushakoff