Skip to content
FullStackDost Logo
  • All Courses
  • Blogs
  • Login
  • Register
  • All Courses
  • Blogs
  • Login
  • Register
  • Home
  • All Courses
  • Full Stack Development
  • PHP Tutorial

PHP Tutorial

PHP Cookies

In PHP, cookies are small pieces of data sent by the server to the client’s browser, which are then stored on the client’s computer. Cookies are commonly used for session management, user tracking, and personalization. Here’s an overview of PHP cookies along with examples:

Setting Cookies:

You can set cookies using the setcookie() function. Cookies must be set before any HTML output.

Syntax:

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

Example:

setcookie("username", "John", time() + 3600, "/"); // Expires in 1 hour

Accessing Cookies:

Cookies are stored in the $_COOKIE superglobal array and can be accessed like any other associative array.

Example:

echo $_COOKIE["username"]; // Output: John

Deleting Cookies:

To delete a cookie, you can set its expiration time to a past value.

Example:

setcookie("username", "", time() - 3600, "/"); // Expire immediately

Cookie Parameters:

  • name: The name of the cookie.
  • value: The value of the cookie.
  • expire: The expiration time of the cookie (in seconds since the Unix Epoch). If not set, the cookie will expire when the browser is closed.
  • path: The path on the server for which the cookie is available. If set to ‘/’, the cookie will be available for the entire domain.
  • domain: The domain for which the cookie is available. Default is the current domain.
  • secure: Indicates if the cookie should only be transmitted over HTTPS.
  • httponly: Indicates if the cookie should only be accessible through HTTP.

Using Cookies for Persistent Login:

if (isset($_COOKIE["username"])) {
 $username = $_COOKIE["username"]; // Check if username exists in database and log in the user
} else {
 // Prompt user to log in
}

Note:

  • Cookies have size limitations (usually around 4KB).
  • Cookies are sent with every HTTP request to the server, which can impact performance.
  • Be cautious when storing sensitive information in cookies, as they are stored on the client’s machine and can be manipulated.

Cookies are a fundamental aspect of web development, allowing you to store and retrieve data on the client’s machine. They are commonly used for session management, user authentication, and personalization in PHP applications.

PHP GET & POST
Prev
PHP Forms
Next

Copyright © 2025 FullStackDost. All Rights Reserved.

Theme by ILOVEWP