PHP Cookies
PHP Cookies
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize
the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to
the server, cookie is embedded with request. Such way, cookie can be received at the server side.
They are typically used to keep track of information such as a username that the site can retrieve to
personalize the page when the user visits the website next time. A cookie can only be read from the
domain that it has been issued from. Cookies are usually set in an HTTP header but JavaScript can
also set a cookie directly on a browser.
Creating Cookies with setcookie()
Set Cookie 1
The setcookie() function is used to
create a new cookie on the client's
browser. It requires several 2 Store on Client
parameters, including the name, The cookie data is then stored as a
value, expiration time, path, domain, text file on the client's machine. On
and security settings. subsequent visits, the cookie is
included in the request header and
sent back to the server.
Access on Server 3
The server can then access the
cookie data through the $_COOKIE
superglobal variable, which contains
all the cookies present in the current
request.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:
Cookie Parameters
Name Value Expiration
The name of the cookie, The value to be stored in the The timestamp when the
used to identify it. cookie. cookie will expire and no
longer be accessible.
Cookie Parameters
Path Domain Security
It is used to specify the path It is used to specify the It is used to indicate that
on the server for which the domain for which the cookie the cookie should be sent
cookie will be available. is available. only if a secure HTTPS
connection exists.
Setting a Cookies:
In this example:
Set Expiration
However, this time set the expiration time to a value in the past, such as one day ago.
Cookie Removed
This will effectively delete the cookie from the client's browser.
Cookies in Action
HTTPS HttpOnly
Cookies should be set with the "secure" flag Cookies should be set with the "HttpOnly"
to ensure they are only transmitted over a flag to prevent them from being accessed
secure HTTPS connection. by client-side scripts, reducing the risk of
XSS attacks.