Yii2 share session between 2 apps

一个人想着一个人 提交于 2019-12-10 23:28:10

问题


Currently, my application have the following structure:

  • frontend
  • backend (user authenticated)
  • client (user authenticated)

What I'm trying to do is to pass a flash message from the client to the frontend.

In the client app I simple set the flash:

Yii::$app->session->setFlash('successMessage', 'My success message!');

And in the frontend:

Yii::$app->session->getFlash('successMessage');

But the above obviously is not working.

I've already tried to set equal session id in the config/main.php of both apps, but there seems to be no different:

'components' => [
    'session' => [
        'name' => '_mySharedSessionId',
        'savePath' => __DIR__ . '/../runtime',  
    ],
    ...
]

Any ideas where I'm wrong?

UPDATE The problem maybe came from that I have set 4 different vhosts for each app: local-frontend, local-backend, local-client. If I revert it to the default, all seems to work fine. So my question now is: Is there an universal way to share a session between the above vhosts so that when the site is uploaded for production it will work also there (probably the urls on production will be something like www.mysite.com, www.client.mysite.com, www.admin.mysite.com)?


回答1:


Add below code in your controller file

Yii::$app->session->setFlash('delete', "Member Deleted Successfully.......");

And add below code in your view or index file

<?php if (Yii::$app->session->hasFlash('delete')): ?>
   <div class="alert alert-danger alert-dismissable">
      <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
      <h4><i class="icon fa fa-check"></i>Deleted!</h4>
      <?= Yii::$app->session->getFlash('delete') ?>
   </div>
<?php endif; ?>



回答2:


The issue is in your php configuration and not specific to Yii2. You should explicitly set session.cookie_domain parameter in php.ini:

session.cookie_domain = ".example.com"

Alternatively, you can do that in php using ini_set (for example, in your web/index.php):

ini_set('session.cookie_domain', '.example.com' );

By default, that variable restricts cookies to current domain, but setting it to .example.com (notice the dot prefix) will allow to use the same cookie for example.com, www.example.com, foo.example.com, bar.example.com, but not example.org.

Specifically for your local installation, change vhosts to frontend.local, backend.local, and client.local, and set cookie_domain to .local.




回答3:


If you want to share the session from one application to another without hindering the domain configuration of the app, then you should try memcache!



来源:https://stackoverflow.com/questions/32570950/yii2-share-session-between-2-apps

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