In this tutorial you will learn how to lớn store a small amount of information within the user"s browser itself using the PHP cookies.

Bạn đang xem: Html

What is a Cookie

A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user"s computer. They are typically used khổng lồ keeping traông xã of information such as username that the site can retrieve to personalize the page when user visit the trang web next time.

Tip: Each time the browser requests a page to the hệ thống, all the data in the cookie is automatically sent khổng lồ the VPS within the request.

Setting a Cookie in PHP

The setcookie() function is used to lớn phối a cookie in PHPhường. Make sure you Call the setcookie() function before any output generated by your script otherwise cookie will not set. The basic syntax of this function can be given with:

Parameter Description
name The name of the cookie.
value The value of the cookie. Do not store sensitive sầu information since this value is stored on the user"s computer.
expires The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The mặc định value is 0.
path Specify the path on the hệ thống for which the cookie will be available. If mix khổng lồ /, the cookie will be available within the entire domain.

Xem thêm: Php, Wait 5 Seconds Before Executing An Action, Php Sleep() Function

domain Specify the domain name for which the cookie is available lớn e.g
secure This field, if present, indicates that the cookie should be sent only if a secure HTTPS connection exists.

Tip: If the expiration time of the cookie is set khổng lồ 0, or omitted, the cookie will expire at the kết thúc of the session i.e. when the browser closes.

Here"s an example that uses setcookie() function to create a cookie named username và assign the value value John Carter to it. It also specify that the cookie will expire after 30 days (30 days * 24 hours * 60 min * 60 sec).

Note: All the arguments except the name are optional. You may also replace an argument with an empty string ("") in order khổng lồ skip that argument, however lớn skip the expire argument use a zero (0) instead, since it is an integer.

Warning: Don"t store sensitive sầu data in cookies since it could potentially be manipulated by the malicious user. To store the sensitive sầu data securely use sessions instead.

Accessing Cookies Values

The PHP. $_COOKIE superglobal variable is used to lớn retrieve a cookie value. It typically an associative array that contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. The individual cookie value can be accessed using standard array notation, for example to display the username cookie phối in the previous example, you could use the following code.