Home  >  Article  >  Backend Development  >  How to Set and Read Cookies Across Pages with PHP and JavaScript?

How to Set and Read Cookies Across Pages with PHP and JavaScript?

DDD
DDDOriginal
2024-10-28 00:00:02156browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn