How to Set a Cookie for Another Domain

How to set a cookie for another domain

You cannot set cookies for another domain. Allowing this would present an enormous security flaw.

You need to get b.com to set the cookie. If a.com redirect the user to b.com/setcookie.php?c=value

The setcookie script could contain the following to set the cookie and redirect to the correct page on b.com

<?php
setcookie('a', $_GET['c']);
header("Location: b.com/landingpage.php");
?>

Accessing cookie set by back-end on another domain

No.

If it was possible then Evil-Hacker.com could read the cookies from Your-Bank.com and gain access to your bank account.

Cookies are accessible, directly, only if the Domain parameter of the cookie matches a segment of the domain of the page trying to read them. (e.g. foo.example.com could read a cookie set for example.com). Top-level domains (like .com) are excluded from this.

An Ajax request, with the withCredentials flag set, could make a request to the domain the served the cookies (this would need permission via CORS with a pre-flight). A server-side script on that domain could then read the cookie and echo it back in the body of the response where JS could read it. Obviously this requires the domain the cookie belongs to to co-operate by providing such a webservice.

Creating a JavaScript cookie on a domain and reading it across sub domains

Just set the domain and path attributes on your cookie, like:

<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=.example.com;path=/";
</script>


Related Topics



Leave a reply



Submit