Home > Article > Web Front-end > Can I Set a Cookie for a Different Domain?
Navigating Cross-Domain Cookie Conundrum
Problem:
In the realm of website development, it may arise that you wish to set a cookie for a different domain than the one currently being accessed. For instance, you have a website at a.com and aim to set a cookie for b.com when a specific page, a.com/link, is loaded. Following that, you plan to redirect the user to b.com.
Is Cross-Domain Cookie Setting Possible?
The simple answer is: no, it is not possible to directly set cookies for other domains. This limitation stems from the fundamental security implications it could pose.
Workaround for Cross-Domain Cookie Setting
To overcome this hurdle, you must rely upon the assistance of b.com. To set the cookie for b.com, you must redirect the user to a specific URL on b.com that includes the instructions to set the cookie. For example:
a.com/link -> b.com/setcookie.php?c=value
The setcookie script at b.com/setcookie.php could perform the necessary cookie setting and then redirect the user to the desired page on b.com, as illustrated below:
<?php setcookie('a', $_GET['c']); header("Location: b.com/landingpage.php"); ?>
The above is the detailed content of Can I Set a Cookie for a Different Domain?. For more information, please follow other related articles on the PHP Chinese website!