Is there a way in PHP to use persistent data as in Java EE? (sharing objects between PHP threads) without session nor cache/DB

回眸只為那壹抹淺笑 提交于 2019-11-28 01:10:02
// First page
session_id('same_session_id_for_all');
session_start();
$_SESSION['aConstantValueForEveryone'] = 'My Content';

// Second page
session_id('same_session_id_for_all');
session_start();
echo $_SESSION['aConstantValueForEveryone'];

This works out of the box in PHP. Using the same session id (instead of an random user-uniqe string) to initialize the session in for all visitors leads to a session which is the same for all users.


Is it really necessary to use session to achieve the goal or wouldn't it better to use constants?

There is no pure PHP way of sharing information across different threads in PHP! Except for an "external" file/database/servervariable/sessionfile solution.

You can declare a Variable in your .htaccess. For Example SetEnv APPLICATION_ENVIRONMENT production and access it in your application with the function getenv('APPLICATION_ENVIRONMENT')

Another solution is to wrap your variable in a "persistent data" class that will automatically restore its data content every time the php script is run. Your class needs to to the following:

  • store content of variable into file in __destructor
  • load content of variable from file in __constructor

I prefer storing the file in JSON format so the content can be easily examined for debugging, but that is optional.

Be aware that some webservers will change the current working directory in the destructor, so you need to work with an absolute path.

I think you can use $_SESSION['aConstantValueForEveryone'] that you can read it on every page on same domain.

Consider to refer to it's manual.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!