如果 PHP 脚本通过 exec 运行,它会保持其会话吗?
我想从另一个 PHP 脚本运行一个 PHP 脚本,以便父级在启动子脚本时成功返回。
父级将从我使用会话的浏览器启动。如果通过 exec 运行,子脚本是否能够使用相同的会话和会话变量?
感谢大家的帮助
场景
我正在通过 AJAX 解雇父母。完成此操作后,我希望父母运行孩子并回来。子脚本需要一段时间才能完成。父级将返回成功,表明它已运行子级。然后用户将被重定向到不同的页面。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就像其他人说的那样,这是行不通的。
但是,您可以执行
ignore_user_abort( true );
这将使您的脚本保持运行,即使用户关闭浏览器也是如此。
因此,ignore_user_abort,将大量子脚本包含在父脚本中,这样您就可以获得会话变量和所有内容,并且应该没问题。
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.
如果您想从 PHP 脚本运行 PHP 脚本,为什么不直接执行以下操作:
?
如果您需要在后台执行某些操作,请使用 AJAX 来触发请求。
编辑: AJAX 请求没有理由不能长时间运行,但您已经超出了 PHP 真正设计的范围。但无论如何,请触发 AJAX 请求。如果需要 20 分钟才能回来,那就没什么戏剧性的了。
或者,您可以每 15 秒触发一次 AJAX 请求(选择一个数字)来检查您已启动的状态。
对于真正长时间运行的任务,您可能必须采取“即发即忘”的方法。启动并立即返回。但它不会有会话信息。你需要存储它。
我建议采用某种持久性机制,例如作业表:
并且不是像 exec() 那样触发此类作业,而是使用 cron 作业来查找需要启动的作业并启动它们。这将比网络服务器触发的方法更脆弱。
您还将获得所需的状态报告,以便能够询问作业是否已完成。
If you want to run a PHP script from a PHP script why not just do:
?
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:
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