Preventing session conflicts in PHP

自作多情 提交于 2021-01-28 03:16:22

问题


Recently I stumbled on an interesting bug where entries would show up in our local custom-made ticket system from users that didn't exist in the app. After some poking around I realised that both this and another PHP app running on the same server were using $_SESSION['user'] for authentication purposes. When someone used one system and then opened the other one he was "automatically" logged in as a user from the first app.

After the obligatory facepalm I changed the session variable name in one of the systems to stop this. However I need to make a permanent, zero-maintenance change to my session handling class to avoid this in future projects. I figure this could be done by using a unique value (for example the script path) to put an app's variables in a place in $_SESSION that wont be used by another app.

Is there a better way?

Edit: This is on linux. And both apps are on the same website.


回答1:


You can ensure that the Session cookies will be specific to the application by making sure that the domain and path of the cookies are set restrictively, e.g. for an application at http://www.example.com/apppath, you could do the following:

<?php

$currentParams = session_get_cookie_params();

session_set_cookie_params($currentParams['lifetime'], '/apppath/', 'www.example.com', $currentParams['secure'], $currentParams['httponly']);

session_start();

This will leave the other session settings intact.

The path is probably the important one, by default PHP will issue the cookie for the domain that the site was requested over (I think), so you could probably actually leave the domain parameter as the default.




回答2:


Set the cookie path so that each app only stores a session cookie valid for its own path.

You can do this with the session_set_cookie_params call.




回答3:


When it comes to shared hosting, it's better to store session id in the database rather then storing it on the server, there are lot of materials available on how to store sessions id in the database, more ever periodically changing the logged user session id can also improve securtiy and reduce conflicts.



来源:https://stackoverflow.com/questions/1027732/preventing-session-conflicts-in-php

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