Home > Article > Backend Development > How to Set and Read Cookies Across Pages with PHP and JavaScript?
Setting and Reading Cookies Across Pages with PHP and JavaScript
When attempting to set a cookie with JavaScript and access it from a different PHP page, it may be necessary to address domain and path settings.
In JavaScript, to set a cookie with a specific expiration date, domain, and path:
<code class="js">function createCookie(name, value, days) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); const expires = "; expires=" + date.toGMTString(); const domain = "; domain=.example.com"; const path = "; path=/"; document.cookie = name + "=" + value + expires + domain + path; }</code>
Ensure that the domain and path match the target page. For example, if the cookie is set on example.com/index.php and needs to be accessed on example.com/test.php, the settings should be:
<code class="js">createCookie('cookieee', 'stuff', 22);</code>
In PHP, access the cookie using $_COOKIE:
<code class="php"><?php print_r($_COOKIE); ?></code>
The above is the detailed content of How to Set and Read Cookies Across Pages with PHP and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!