Cookies with PHP PHP

Cookies are small strings of data created by a Web server but stored on the client. In addition to having names and values, cookies have an expiration time. Some are set to last for only a matter of minutes. Others persist for months. This allows sites to recognize you without requiring a password when you return.

Using cookies with PHP is almost as easy as using form fields. Any cookies passed from the browser to the server are converted automatically into variables. In addition, cookies are stored in the HTTP_COOKIE_VARS array.

If you wish to send a cookie, you use the setcookie function, described in Acookie is sent to the browser as a header. Just like other headers, you must set cookies before sending any content. When you do set a cookie, the browser may refuse to accept it. Many people turn off cookies. So, you cannot count on the cookie being present the next time a user requests a page.

Setting a cookie does not create a variable—not immediately. When setting a cookie, you are asking the browser to store information that it will return when it next requests a page. Subsequent page requests will cause the cookie to be created as a variable for your use. If you write a script that requires the cookie variable always be set, set it immediately after sending the cookie.

Cookies are a sensitive topic. Some people view them as intrusive. You are asking someone to store information on their computer, although each cookie is limited in size. My advice with cookies is to keep them minimal. In most cases it is practical to use a single cookie for your entire site. If you can identify that user with a unique ID, you can use that ID to look up information you know about them, such as preferences. Keep in mind that each page load causes the browser to send the cookie. Imagine an extreme case where you have created ten 1K cookies. That's 10K of data the browser must send with each page request.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics