PHP Creating and using cookies

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments

Cookies are small text files that are stored on the client’s computer by the browser. They are used to store data that can be accessed on subsequent visits to the website. In PHP, cookies can be set, read, and deleted using the setcookie(), $_COOKIE superglobal, and setcookie() functions.

The setcookie() function is used to set a cookie. The function takes at least two arguments: the name of the cookie and its value.

setcookie("username", "John", time() + (86400 * 30), "/");

The above code sets a cookie named “username” with the value “John” that expires in 30 days. The last argument “/” indicates that the cookie is available throughout the entire website.

You can also set other optional parameters like expire, path, domain, and secure and httponly.

To read the value of a cookie, you can use the $_COOKIE superglobal array.

$username = $_COOKIE['username'];

To delete a cookie, you can set its expiration time to a past date using the setcookie() function.

setcookie("username", "", time() - 3600);

It is important to note that cookies can only be accessed by the domain that set them, also when working with cookies you should consider the user’s privacy and follow the laws and regulations that apply to your country or region.

Cookies can also be used to store session data, which allows you to keep track of a user’s actions across multiple pages. PHP provides the session_start() function to start a new session, and the $_SESSION superglobal array to store and access session data.

These are just a few examples of how to use cookies in PHP, it’s recommended to consult the official PHP documentation for more information on working with cookies in PHP.

Leave a Reply