PHP $_SESSION across subdomains
.htaccess on api.example.com
# CORS Headers (add this)
<ifModule mod_headers.c>
Header add Access-Control-Allow-Origin "http://example.com"
## Post the domain that will be doing the XHR requests
Header add Access-Control-Allow-Credentials: "true"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</ifModule>
<Limit GET POST PUT DELETE>
Allow from all
</Limit>
example.com
Post the following in the header of your main website
ini_set('session.cookie_domain', '.example.com' );
session_start();
XHR Request
Now we need to post the credentials from example.com to api.example.com I'm using AngularJS with this
$http({
method: 'GET',
url: '//api.example.com/auth/',
xhrFields: {
withCredentials: true
},
crossDomain: true
}).success....
Also change your config to allow sending with Credentials
.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
//rest of route code
SESSION between subdomains and ini_set
ini_set("display_errors","on")
on first line to see if there are any errors.
Of the first 4 lines, remove these 3 lines
ini_set("session.cookie_domain", "client.domain.com");
ini_set("session.cookie_domain", "mods.domain.com");
ini_set("session.cookie_domain", "domain.com");
and change the last line to
ini_set("session.cookie_domain", ".domain.com");
After login success and before login call session_regenerate_id()
to change your session id. As suggested by jeroen in php-sessions-across-sub-domains you can also add the below 2 lines prior to session_start
$some_name = session_name("some_name");
session_set_cookie_params(0, '/', '.domain.com');
please keep in mind that if you are going to add the 2 line above, you also need to add them in your login page.
and as a final note, check if there's anything output to browser prior to session_start
, if soyour setting for session will not be active and won't work
Starting a php $_SESSION on root domain (www) and sharing the session across subdomains
Try setting a name for the session
session_name("domain");
before setting the session cookie parameters.
session_name("domain");
session_set_cookie_params(0, '/', '.domain.com');
session_start();
Related Topics
How to Get File_Get_Contents() to Work With Https
Check If PHP Session Has Already Started
Why Would $_Files Be Empty When Uploading Files to PHP
What Is the Most Accurate Way to Retrieve a User'S Correct Ip Address in PHP
How to Get a Variable Name as a String in PHP
How to Set Up File Permissions For Laravel
Parse Xml With Namespace Using Simplexml
How to Get a Form Input Array into a PHP Array
How to Call a JavaScript Function from PHP
How to Read a Large File Line by Line
When Should I Use 'Self' Over '$This'