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

DDD
Release: 2024-10-28 00:00:02
Original
155 people have browsed it

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>
Copy after login

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>
Copy after login

In PHP, access the cookie using $_COOKIE:

<code class="php"><?php 
  print_r($_COOKIE);
?></code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!