开发者

Will a PHP script maintain its session if it is run via exec?

开发者 https://www.devze.com 2022-12-15 20:19 出处:网络
I would like to run a PHP script from another PHP script so that the parent comes back with a success when it initiate开发者_JS百科s the child script.

I would like to run a PHP script from another PHP script so that the parent comes back with a success when it initiate开发者_JS百科s 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.


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.


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.


The answer is no

0

精彩评论

暂无评论...
验证码 换一张
取 消