tags:

views:

43

answers:

3

Hello all,

I would like to run a PHP script from another PHP script so that the parent comes back with a success when it initiates the child script.

The parent will be initiated from the browser where I am using sessions. Will the child script be able to make use of the same session and session variables if run via exec?

Thanks all for any help

Scenario

I am firing off the parent via AJAX. After I do this, I want parent to run the child and come back. The child script will take a while to complete. The parent will return a success to indicate it has run the child. The user will then be redirected to a different page.

+2  A: 

If you want to run a PHP script from a PHP script why not just do:

require 'child.php';

?

If you need to do something in the background, use AJAX to fire off the request.

Edit: there is no reason an AJAX request couldn't be long-running but you're getting outside the realm of things that PHP was really designed for. But anyway, fire off an AJAX request. If it takes 20 minutes to come back, that's no drama.

Alternatively you can fire off an AJAX request every 15 seconds (pick a number) to check on the status of what you've started.

For truly long-running tasks you're probably going to have to take a "fire and forget" approach. Start it off and return immediately. But it won't have the session information. You'll need to store that.

I'd suggest having some kind of persistence mechanism like a Jobs table:

  • Job: id, started_by, status (not started, running, complete), started_when, completed_when.

and rather than firing off such jobs as an exec() have a cron job that looks for jobs that need to be started and start them. This will be less fragile than a Webserver triggered approach.

You'll also have the status reporting you need to be able to ask if a job is finished yet.

cletus
I have edited my question.
Abs
My goal is to start a process and moving on. The alternative will not work as I need to run this in the background as users should be able to close their browsers. The process I am running can take several hours (5,6,7 hours). A big DB job is going with PHP firing off sql scripts.
Abs
A: 

The answer is no

Andrea Zilio
+2  A: 

Like the others said, it will not work.

But, you can do ignore_user_abort( true );

This will keep you script running even if the user closes their browser.

So, ignore_user_abort, include the massive child script within the parent so you get the session vars and everything, and you should be fine.

Horia Dragomir
Thanks for the reference to that function, it really helped!
Abs