IP and domain create different session

2019-07-11 17:17发布

问题:

I've built a website with a user-login. Now, for some reason when I enter from the site's IP and from the site's domain a different session is created.

In the website I use a global parameter, named: ROOT where:

define("HOST", "localhost/final-project-management-system");
define("ROOT", "http://".HOST."/");

I give a lot of links related to ROOT in the website.

When I try connect to the IP, an initial session is created, but when I move to one of the pages with ROOT involved, a new session is created and the old session is deleted.

Does anyone have any idea why this happens ?

Thanks ..

回答1:

PHP sessions are based on the scope of cookies, and the behaviour you describe is exactly how this works.

The scope of a cookie is defined simply by a string value based on the hostname (or IP) that appears in the address bar of the browser. Just because an hostname resolves to a specific IP, does not mean they share cookies.

If you think about it then basing the cookie scope on the resolved IP address would potentially cause major problems with cookies leaking between sites when you consider shared hosting environments.

In order to have this work correctly, the user will have to access the site via either the DNS name or the IP address, not both. You can pass the session ID manually to work around this, but it doesn't come recommended (not by me, at any rate).



回答2:

If the URL in the browser contains the IP Address and the cookies were stored in the browser against the hostname or its parent domain then the cookies wont be sent as part of the request there by may result in new session creation.

The best practice is to have a rule at the server side that if the incoming request contains the host header as IP address simply redirect to a location in which the URL contains the host name/FQDN . Sites such as Google, Facebook will return a 302 redirect when a request is made for a website using ip address.



回答3:

you have try var_dump() on session?

var_dump($_SESSION);

you start the session_start() at top of php?