PHP Cookies
PHP Cookies
PHP Cookies
PHP cookies are small piece of data stored on the
user’s computer by the web browser while
browsing a website. They are commonly used to
remember information about the user.
What is a cookie?
A cookie is a small piece of data sent from a website and stored on the user’s computer by the user’s
web browser. It can store user preferences, login information, and other data.
Usage
Cookies are commonly used for session management, personalization, and tracking user behavior.
Duration
They can have an expiry time, after which they will be automatically removed from the user’s
computer.
Security
Cookies are restricted by the same origin policy for security reasons
How to create cookies with PHP
In PHP, cookies are created using the setcookie() function. This function sets a cookie to be sent
along with the rest of the HTTP headers.
setcookie()
This function accepts parameters like name, value, expiry time, path, domain, secure, and httponly.
Response Headers
When a cookie is set using setcookie(), it becomes a part of the HTTP headers returned by the web
server to the client.
Example
Setcookie(“user”, “Abebe”, time() + (86400 * 30), '/');
Managing cookie expiration and deletion
Cookie expiration can be managed by specifying an expiry time when creating the cookie. Cookies
can also be deleted by setting their expiry time to a past date.
Expiry Time
Deletion
Syntax
Create Cookie
Retrieve Cookie
Data Storage
Cookie data is stored on the user’s system and can be accessed for various functionalities.
Server-Side Access
The data stored in cookies can be accessed and utilized on the server side.
How do we use cookies in PHP?
It’s essential to follow best practices when working with cookies. This includes setting secure and
HTTP only cookies, validating and sanitizing cookie data, and being transparent about cookie
usage through a privacy policy.
Data Security
Ensure cookies carry only necessary information and are secure.
Privacy Policy