php
  1. php-cookie

PHP Cookie

Syntax

Cookies in PHP are set using the setcookie() function. The syntax for the function is as follows:

setcookie(name, value, expire, path, domain, secure, httponly);

Example

Here is an example of setting a cookie in PHP:

<?php
$value = "John Doe";
setcookie("username", $value, time() + 3600, "/");
?>

Output

When the above code is executed, a cookie named "username" with a value of "John Doe" will be set and will expire in one hour.

Explanation

Cookies are small text files that are stored on the user's computer. They can be used to remember information or preferences for a website. In PHP, cookies are set using the setcookie() function. The first parameter is the name of the cookie, the second is the value, and the third is the expiration time in seconds. The fourth parameter is the cookie path, which determines the URL path on the server in which the cookie will be available. The fifth parameter is the domain, which specifies the domain to which the cookie is available. The sixth parameter is the secure flag, which indicates that the cookie should only be transmitted over a secure HTTPS connection. The seventh parameter is the httponly flag, which prevents JavaScript from accessing the cookie.

Use

Cookies can be used to remember user preferences or login information, to track user activity, or to save shopping cart information.

Important Points

  • Cookies are small text files that are stored on the user's computer.
  • Cookies can be set using the setcookie() function in PHP.
  • The setcookie() function takes several parameters, including the expiration time, path, domain, secure flag, and httponly flag.
  • Cookies can be used to remember user preferences or login information, to track user activity, or to save shopping cart information.

Summary

Cookies are a useful feature in web development that can be used to remember information or preferences for a website. In PHP, cookies are set using the setcookie() function, which takes several parameters including the expiration time, path, domain, secure flag, and httponly flag.

Published on: