I need to share session between:
domain.com,
sub1.domain.com
sub2.domain.com
BUT also they must work with other domain.
For example if i choose session.domain = ".domain.com" - sessions will not work with "another.com"
Thanks
You cannot share a session across different domains as they are locked in by the session cookie domain setting.
You **can** retrieve associated data based on a cookie value that you can store in something such as Redis (server side). All it needs is some common identifier (such as a user ID) that is readable by another domain client side (by JavaScript).
The trouble is passing the values over from one site to another, or even another subdomain. You would need a central hub to connect to which stores the values and is the originator of the cookie domain. You can pass certain details over from one domain to another by referencing the cookie value stored on the second domain and pass data back (over ajax for example) based on the value you store.
Origin (Hub) Domain: cookie.domain.com
Subdomain 1: subdomain1.domain.com
Subdomain 2: subdomain2.domain.com
Different Domain: www.differentdomain.com
Cookie Domain: cookie.domain.com
JavaScript Domain: cookie.domain.com
This way, the JavaScript can read the cookie stored from cookie.domain.com, then interact with the current client side session or even the server/domain that the current page originates from.
If you have a look at how Facebook / Twitter inject their scripts and cookies, they come from the same domain / subdomain (that's how I figured this out for a previous project).
I have a few domains all on the same server, with the same IP and the same databases - that can be accessed by all 5 of the domains.
I have recently remade my login system, so that on my main domain, the cookie works for not only the main domain but the sub domains as well. What this means is that if a user logs into one area, they are signed in everywhere. Which is great! I write a cookie with their hash (taken from the DB) and check for that when loading each page, and they are automatically securely signed in.
This is lovely, but the problem then comes when switching domains, as cookies seem to be locked down to domains. So my other domain (lets call it domain2.com) cannot read the cookie from domain1.com.
Are there any clever ways around this? I could write something to the database, such as IP, but that wouldnt be very secure as the company i work for everyone is on the same IP and therefore it wouldnt be specific.
Or I thought about maybe including a hidden iframe on the page, which actually links to a page on the main server, and pulls the information that way somehow.
I am not sure, but I am sure it can be done. Any ideas?
Browsers, for good reasons, do not allow cookies to be read from any other domain.
What you can do is have domain2.com redirect to a page on domain1.com which checks if the user is logged in and if they are it redirects back to domain2.com with the user's id which can then log them in.
You should not depending on original PHP session functions Collections.
Here is what I have done :
After login success , Server side should return a "session ID" to the browser and store by JavaScript or some how, mean while the "session ID" should be store in database as a successful signal and you do a login time next to the session ID if you needed.
Now you can share the session ID in any IP server you want and make your client connect to(some trick like you redirect to the new domain and post the SID) then establish a PHP session.
I have two Domain site (Exmp: A & B) and two database,
function site A is for a payment method, so if a custumer buy a product, it will be direct for login first and
The site B is as a frontpage (web interface) only.
My question is : how can I get or check the session value FROM Site A and show the session_name in my interface website when the user is open my web at the same time.
Thanks in advance
You're facing 2 problems:
The session-id is probably stored on a cookie, and the browser will not send a cookie originated from domain A to domain B (unless you're talking about the same domain).
Even if you're able to have the session-id on both domains, for the data to be persistent across 2 sites, you're gonna need a shared session storage configured.
Possible solutions:
Pass the session-id over the URL as query-string parameter (not recommended for many reasons and has to be configured accordingly in your php.ini).
As for the storage: the common approach is to use a database as your session storage provider (hence making is 'shared').
Also, you may reconsider the use of session altogether, if you're only doing basic redirection maybe you can pass the data over a regular GET or POST request.
I want to create a cookie from one domain once the user is registered in PHP. and make this cookie accessible to 4 other domains not subdomain. I know that cookies are not designed to be accessible for other domains. For example I have set a cookies variable $user_email from domain www.firstdomain.com and want to access it in other domains like www.seconddomain.com, www.thirddomain.com etc. May be this can be done using PHP or JavaScript. Any idea please.
Thank you!
When searching the cookie list for
valid cookies, a comparison of the
domain attributes of the cookie is
made with the Internet domain name of
the host from which the URL will be
fetched. If there is a tail match,
then the cookie will go through path
matching to see if it should be sent.
"Tail matching" means that domain
attribute is matched against the tail
of the fully qualified domain name of
the host. A domain attribute of
"acme.com" would match host names
"anvil.acme.com" as well as
"shipping.crate.acme.com". Only hosts
within the specified domain can set a
cookie for a domain and domains must
have at least two (2) or three (3)
periods in them to prevent domains of
the form: ".com", ".edu", and "va.us".
Any domain that fails within one of
the seven special top level domains
listed below only require two periods.
Any other domain requires at least
three. The seven special top level
domains are: "COM", "EDU", "NET",
"ORG", "GOV", "MIL", and "INT".
The default value of domain is the
host name of the server which
generated the cookie response.
read up here.
you can load an iframe from a host which then reloads itself with the encoded cookie value in the segment part (after the #).
you can then access the document.location attribute from the parent window (hits the only thing that is accessible). decode it and pass it to your server doing an ajax request.
This could look like so.
xss.php (located on cookies.example.com):
<?php
$data = array(
'uid' => $_COOKIE['uid'],
'loginhash' => $_COOKIE['loginhash']);
header('Location: xss.php#'.urlencode(json_encode($data)));
for this particular case it does not need to be the hashtag! its just convinient for other situations. this can also be done in javascript.
another website embeds xss.php:
<iframe id="cookies" src="http://cookies.example.com/xss.php"></iframe>
you need to somehow delay the following of do it in a loop that stops after 5 seconds or something.
if(document.getElementById('cookies').location != 'http://cookies.example.com/xss.php') {
// read location, extract hashtag, json decode using javscript, there you have your user. send it to server for validation or whatever.
}
this teqnique is called xss recieving. it is for example utilised by facebook for all their javascript connect libraries.
a probably better way would be some sort of token exchanging protocol like openid.
amazon uses this too.
you can set up an openid provider (there are librarys available that can do that out of the box) and set it to auotmatically redirect back without user interaction. i have often seen openid protocol used for some other purposes just like cross domain communication.
As you have already said, a cookie can only be set for a domain from that domain (including its subdomains). And if your domains do not share a common superdomain, you need set each cookie for each domain separately.
You can do this with a script that on each domain that sets the cookie for you. But make sure to authenticate requests to these scripts so that only you can set the cookies.
I had solved exactly same problem (actually also for 4 domains). The only solution I've came up with was, to include 3 hidden iframes on the 'Successful login page' and those iframes just load www.domain1.com/register_session.php, www.domain2.com/register_session.php, etc....
As a parameter for register_session.php I use 'sid' which contains session ID:
session_id($_GET['sid']);
session_start();
This is actually for keeping session alive on all those domains but the same would be for your case with cookies.
I ve done some scripts to handle multi domain cookie :
https://code.google.com/p/mudoco/
if you want to access cookie within different domains so this can be done with the help of javascript trick. As cookie can be accessed within same domain.
Create cookie on user’s browser using JavaScript on your first domain.
Set the name of the window to whatever value of cookie you want to carry to another domain by using window.name.
Step 2 should be performed on every page of the domain which has created the cookie. It could be easily by calling a JavaScript file on all pages.
When you move to another domain, and want to access the above mentioned cookie value, access it by using window.name as window has not changed.
Create new cookie on this domain and assign this value to it.
we are solving the problem with eshop (php, mysql). The client want to have the same eshop on two domains with shared shopping cart. In the shop customer can do the shopping without users account (can't be logged in). And there is the problem, how to make the shared shopping cart cross domain.
The data from cart is stored in sessions, which we stored in database too. But we can't solve the problem in carrying data over domains. Identifying unlogged user is not holeproof (research).
The example, how it should work
Customer goes to domainOne and add some things to the cart. Than he goes to domainTwo (by link, typing domain address, however) and add some other things to the cart. In the cart he has things from both domains (after refreshing page).
Do you have any idea, how to solve this problem?
What didn't work:
redirecting is not possible due to customer requirments
cookies are related to domain
set_cookie with the other domain didn't work
the simpliest way is to carry over only the sessionid (stored in cookies) but we don't know, how to wholeproof identify unlogged users.
is there any other place, where data can be stored on client side except cookies? (probably not)
we can't use sending sessionid by params in url (if user click to link to the other domain) or resolving the header referer, bcs we don't know, how user can achieve the other domain.
If you can't understand me, take me a question. If you think, that having eshop on two domains with shared (common) cart is bad idea, don't tell me, we know it.
Thanks for each answer.
You can use a third domain to identify your customers over all domains.
Use for example a PHP File on http://thirdDomain.com/session.php that is included on all pages on both shops.
Sample:
<script type="text/javascript" src="http://thirdDomain.com/session.php"></script>
After your customer switches domains, you can identify him as the same customer using the third domain.
You can assign the session id on both shops to the session id on the third domain to access the cart on both shops. You only need to inform the third domain about your shop sessions (i.e. add them as parameter).
Depending on how flexible you are with your code and templates, you can even use an output from the third domain to define the session id in your shops. This way you can use the same session id on all domains.
But normally a session id assignment should be the more secure way.
Using the javascript version you can also output scripts that may add a session id to all outgoing links and forms to the other domain in the current html page. This might be interesting if you can identify your customer as having cookies blocked.
You can also use the javascript to inform the parent document about an existing session.
This keeps getting asked.
Have a search for SSO.
You need to pass the session id in the URL (or vai a POST) across the domains, then:
1) check the session does not already exist on the target domain
2) rebind the session using the session id sent
e.g.
if ((!$_COOKIE[session_name()]) && $_GET['passed_id']) {
if (check_session_exists($_GET['passed_id'])) {
session_id($_GET['passed_id']);
}
}
session_start();
...
function check_session_exists($id)
{
$path=session_save_path() . $id;
if (file_exists($path) && (time()-filemtime($path)<session_cache_expire())) {
return true;
}
return false;
}
This also means you need to add '?passed_id=' . urlencode(session_id()) to any URL pointing to the other domain.
C.
The schema is quite simple and widely used. By google for it's numerous services for example. You have a whole picture by tracking down HTTP interchange between your browser and various google services to get the idea.
Suppose we have our client authorized for the 1st domain. By getting to the second, we have to:
start a session and store some token in it.
ask browser to request 1st domain somehow and send this token along.
1st domain will recognize our client and make a connection in the shared database between this token and user id.
By requesting second domain again, we will have it authorized for it's already started session.
The only question remains is how to request 1st domain. It can be a picture, or JS request or entire page redirect. Certain choice is up to you.
You can use Flash LSO's for this matter i think. Normally LSO's are stored in their domain specific sandboxes, but if two domain objects allow, they can communicate as stated in the "cross-movie communication" section in http://download.macromedia.com/pub/flash/whitepapers/security.pdf.
For general info about LSO's:
http://www.adobe.com/products/flashplayer/articles/lso/
SSO.
CartA has iframe that 1) checks if the user is "active" (has session) 2) creates anon session
CartB has iframe that do 1) or 2)
iframe loads from SSO domain (any domain you can have)
SSO solution: build yours or use others - like simplesamlphp or something...
And there should be no need to pass sessions/params with URIs...
You can store data in other places than cookies (e.g. Flash cookies, localStorage) but all use same origin policy, which is the standard security model of the web: data stored by a domain can only be accessed by that domain and its subdomains. The standard workaround is to embed an iframe from the foreign domain into the page. That iframe will have access to the cookies of the foreign domain, and its url will be controlled by the local domain, which allows for communication.
A simple solution based on that is to have a table of (domainA sessionid, domainB sessionid) pairs. When a new user arrives to domainA, (new sessionid, NULL) is added to the table; the page shown to him includes an invisible iframe with source = http://domainB/mergeSessions.php?sessionA=1234. mergeSessions.php will then receive sessionA as an URL parameter and sessionB as a cookie, and update the session link table accordingly.
You could attempt to identify your visitors by IP, browser type, browser version, OS, screen resolution, and whatever else you come up with. That you store in the shared database when someone accesses either site.
If, within a small time window, say < 5 min, requests from that IP with those parameters comes, you can reasonably assume that it's the same user. Again, make sure you use everything you can find find to identify that user and by no means base anything secure on this or you will be subject to hijacking.
What about something like this, not sure how good it would be though.
User goes to store1. If user does not have a session cookie, redirect to a special page on store2 asking for the session id and sending the url on store1 to return to. The special page looks at the session cookie and redirects back to the original url on store1 with the session id (like the answer by #symcbean). Then on store1, the session cookie gets set(or created new) and no more redirecting happens. And then the same but oposite if the user is on store2 with no session cookie.
But if the user does not have cookies enabled, I can see an infinite loop happening. Not sure if it would be possible to detect and stop somehow.
But this way would be hacky at best.
1) Obviously, use the same session-store for both domains (files, database, memcached, the usual suspects.
2) If after session_start() the $_SESSION is empty, create an 'all domains' array in the session (do this on every domain, regardless which one it is, ).
$_SESSION['all_domains'] = array(
'domain1.com' => true, //<= current domain the customer is on,
'domain2.com' => false, //other domain, no cookie for it yet.
'domain2.com' => false); //repeat for all domains needed
3) Create a session-setter script on all domains (let's call it 'sesset.php':
<?php
if(isset($_GET['sessid']){
session_id($_GET['sessid']);
session_start();
//also, check here for the domains:
if(!isset($_SESSION['all_domains'])){
//set the array as before, flag this domain as true.
} else {
$_SESSION['all_domains'][$_SERVER['HTTP_HOST']] = true;
//you might want to set a custom domainname instead of HTTP_HOST, so you won't get doubles from domain with & without www. and so on.
}
}
?>
4) On every conceivable php HTML page, put this somewhere near the end of the body:
<?php
foreach($_SESSION['all_domains'] as $domain => $domainset){
if(!$domainset){
echo '<img src="http://'.$domain.'/sesset.php?sessid='.session_id().' width="1" height="1"/>';
}
}
?>
Not fullproof, but will get almost all users. Ofcourse, one could do it with a redirect cascade instead of 'hidden images', but searchbots (google et al.) very much get confused about it, especially if they don't remember the cookie and are stuck being redirected again & again.
easyXDM is a framework that allows the user to easily work around the Same Origin Policy.
Its built-in RPC feature is very easy to use, and you should be up in running in no-time.
For your case, select one of the domains to be the 'checkout'-domain (A) - this is the domain that will keep the session stored. On the same domain you create a small file with an easyXDM endpoint that is responsible for storing/retrieving the data sent from the other domain (B).
Now, in domain B, you include easyXDM and when storing/retrieving data from the cart, you access the RPC methods instead.
Option 1 Use Iframes:
Site 1 has an Iframe of site 2
Site 2 has an Iframe of site 1
When a user selects an item from site one, set the iframe value to a dynamic string ie domain2.com/iframe.php?itemid=someitem.
Have domain2 grab the $_GET information with PHP from the iframe and update the user's cookie.
Do the same in the other direction.
Option 2: Javascript includes
You can do something similar with cross-site included JS files generated by PHP to "pull" the contents of the user's cookie to the other site.
Option 3: Curl
Just post the data from one domain to the other, so both have a copy. This is the least secure method since there is no guarantee that the IP address or other identifying data can't be duplicated. Though, you can have some "question" or pass phrase to ensure it is the same person. Possibly by setting an email address?
Option 4: Third-party cookies
I think this one was already mentioned, but you can set the cookies from a third domain, so both sites functionally exactly the same rather than "toggling" back and forth between the two.