I have a PHP script that I need to execute from inside another PHP webpage. However for the second one to run properly the first needs to have fully completed. Essentially I need the first page to spawn a new process/thread for the second script which will wait 1 second before starting.
Doing an include causes blocking which prevents it from working and I can't get it to start using exec
Edit:
Should have clarified. These pages have no output and are not interfaced with through a web interface. All pages are called by POST requests from another server.
Edit 2:
Solution: make server requesting the page send a request directly to the second page 1 second after the first returns.
proc_open is the correct choice, as @ChristopherMorrissey pointed out. I want to elaborate a little here, as there are some caveats to using proc_open that aren't entirely obviously.
In the first code example @ http://php.net/manual/en/function.proc-open.php, it shows the overall usage and I will reference that.
The first caveat is with the pipes. The pipes are file streams in PHP that link to STDIN, STDOUT and STDERR of the child process. In the example, pipe index 0 represents a file stream from the parent PHP processes perspective. If the parent process writes to this stream, it will appear as STDIN input to the child process.
On POSIX compliant OSes, STDIN to a process needs to close before the process can terminate. Its very important to call fclose on the pipe from the parent, or your child process will be stuck. That is done with this line in the example:
fclose($pipes[0]);
The other caveat is on checking the exit code of the child process. Checking the exit code is the best way to determine if the child process has exited correctly, or if it erred out. At the very least, you will need to just know when the child process has completed. Checking this and the exit code are both done with http://www.php.net/manual/en/function.proc-get-status.php
If you want to ensure the process exits correctly, you will need to look at the exitcode
field returned in the array from proc_get_status. Keep in mind this exit code will only return a valid value once. All other times it will return -1. So, the one time it returns > -1, this is your actual exit code. So, the first time running
== false, check exitcode
.
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With