0

I am creating a php scripts that runs on background. When the script completes, I want it to change a flag in session started from Web Interface. I tried passing the session id to the script and starting the same session with id but it keeps on loop.

I tried passing the session id to the script and starting the same session with id it doesn't work.

WebInterface.php

$_SESSION["flag"] = false;
shell_exec("php BackgroundScript.php ".session_id()." &");

BackgroundScript.php

$id = $argv[1];
session_id($id);
session_start();
//do things
$_SESSION["flag"] = true;

when I try initializing the session, the code doesnot seem to complete.

xerex09
  • 166
  • 14
  • A session id is normally stored in a browser cookie. You then switch to a complete different environment, the command line, which doesn't support cookies. You try to solve that by supplying the session id. When you call `session_start()`, the background the script tries to regenerate the cookie. See the note for [session_id()](https://www.php.net/manual/en/function.session-id.php). But cookies aren't supported. I don't know if that could work. Anyway, my point is that switching from a session _with cookie_ to one _without_ is probably a bad idea. Why not try it completely without cookies? – KIKO Software Aug 05 '19 at 07:39
  • There are also other ways, apart from the session, to communicate between PHP scripts. The obvious one is a database, but you could also use the file system directly. – KIKO Software Aug 05 '19 at 07:43
  • @KIKOSoftware I am currently getting the data from session file and writing back to it and it is working as expected. Since the function I am trying to achieve depends upon the session flag, I am looking for a alternative ways to modify the session values.. Thanks for your comments. – xerex09 Aug 08 '19 at 07:11

1 Answers1

0

What you could try is to pretent a session cookie exists, like this:

WebInterface.php

$_SESSION["flag"] = false;
shell_exec("php BackgroundScript.php ".session_id()." &");

BackgroundScript.php

$id = $argv[1];
$_COOKIE["PHPSESSID"] = $id;
session_start();
//do things
$_SESSION["flag"] = true;

This can work under some circumstances, but also might not.

See: https://stackoverflow.com/a/7578766/3986005

I think a better solution would be to communicate through a database or file.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33