PHP: Cookies

A cookie is a message given to a Web browser by a Web server. The browser stores the message in a small text file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, the cookie is sent back to the server too.

There are a wide variety of things you can do with cookies. They are used to store information about user, visited pages, poll results and etc. The main purpose of cookies is to identify users and possibly prepare customized Web pages for them.

Normally cookies are used only to store small amounts of data. Websites can read the values from the cookies and use the information as desired. In addition to the information it stores, each cookie has a set of attributes that helps ensure the browser sends the correct cookie when a request to a server is made.

Even though cookies are not harmful some people do not permit cookies due to concerns about their privacy. In this case you have to use Sessions.

How to Create a Cookie?

PHP cookies can be set using the setcookie() function. The syntax is as follows:

setcookie(name[, value[, expire[, path[, domain[, security]]]]])
  • [name] The cookie name. The name of each cookie sent is stored in the superglobal array $_COOKIE.
  • [value] The  cookie value. It is associated with the cookie name.
  • [expire] The time after which the cookie should expire in seconds
  • [path] Specifies the exact path on the domain that can use the cookies. 
  • [domain] The domain that the cookie is available. If not domain is specified, the default value is the value of the domain in which cookie was created.
  • [security] Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies that the cookie is sent over a secure connection but it doesn’t mean that the cookie is secure. It’s just a text file like every other cookie. A value of 0 denotes a standard HTTP transmission.

In the example below, we will create a cookie named “myCookie” and assign the value “PHP Tutorial” to it. We also specify that the cookie should expire after one hour and that the cookie is available for all pages within a Tutorials directory.

<?php
setcookie("myCookie", "PHP Tutorial", time()+3600, "/tutorials");
?>

There’s one important item to mention about using cookies. Because of the way cookies work within HTTP, it’s important that you send all cookies before any output from your script. This requires that you place calls to this function before any output, including tags as well as any whitespace. If you don’t, PHP will give you a warning and your cookies will not be sent.  

How to Retrieve a Cookie Date?

Now the cookie is set and we need to retrieve the information. As mentioned above the name of each cookie sent by your server accessed with the superglobal array $_COOKIE. In the example below we retrieve the value of the cookie and print out its value on the screen.

<?php
echo "The cookie value is ".$_COOKIE['myCookie'];
?>

This would show up on the page as: “myCookie value is PHP Tutorial”.

How to Delete a Cookie?

By default, the cookies are set to be deleted when the browser is closed. We can override that default by setting a time for the cookie’s expiration but there may be occasions when you need to delete a cookie before the user closes his browser, and before its expiration time arrives. To do so, you should assure that the expiration date is in the past. The example below demonstrates how to do it (setting expiration time 1 minute ago):

<?php
setcookie("myCookie", "", time()-60);
?>
admin

admin

Leave a Reply

Your email address will not be published.

ASP: Cookies

A cookie is a message given to a Web browser by a Web server. The browser stores the message in a small text file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, the cookie is sent back to the server too.

There are a wide variety of things you can do with cookies. They are used to store information about user, visited pages, last visits and etc. The main purpose of cookies is to identify users and possibly prepare customized Web pages for them.

When you enter a Web site using cookies, you may be asked to fill out a form providing some information about you. This information is packaged into a cookie and sent to your Web browser. The next time you go to the same Web site, your browser will send the cookie to the Web server. The server can use this information, for example, to display a welcome page with your name on it.

How to Create a Cookie?

In order to create a Cookie, you need to use the Response.Cookies command. In the following example we will create a cookie named “lastname” and assign the value “someValue” to it:

<%
Response.Cookies("lastname") = "Peterson"
%>

The Response.Cookies command must appear before the <html> tag otherwise you need to place at the top of your page the following line:

<% response.buffer = true %>

It is also possible to assign properties to a cookie, like setting a date when the cookie should expire. The example below creates a cookie which will expire in 30 days from now. If you want the cookie to expire as soon as your visitor leaves, you should set the Expires property with the value 1.

<%
Response.Cookies("lastname") = "Peterson"
Response.Cookies("lastname").Expires = Now + 30
%>

The next important property is the Domain property. The cookie can only be read by the domain it originated from. It is set by default to the domain in which it was created, but you can alter it for your needs. Have a look at the example:

<%
Response.Cookies("lastname").Domain = "http://www.webcheatsheet.com"
%>

Another two important properties are the Path and Secure properties. The Path property specifies the exact path on the domain that can use the cookies.

If the Security property is set then the cookies will only be set if the browser is using secure sockets or https:// to connect but it doesn’t mean that the cookie is secure. It’s just a text file like every other cookie.

Have a look at the examples:

<%
Response.Cookies("lastname").Path = "/cookies/"

Response.Cookies("lastname").Secure = True
%>

How to Retrieve a Cookie Value?

Now the cookie is set and we need to retrieve the information. In order to retrieve the value of the cookie, you need to use the Request.Cookies command. In the example below we retrieve the value of the cookie named “lastname” and print out its value.

<%
someValue = Request.Cookies("lastname")
response.write("The cookie value is " & someValue)
%>

The output will be “The cookie value is Peterson”.

Using a Cookie Dictionary

In addition to storing simple values, a cookie in the Cookies collection can represent a cookie dictionary. A dictionary is a construct that is similar to an associative array in that each element of the array is identifiable by its name.

Basically, cookie dictionary is just a cookie that can hold several values. These values are called keys. This gives you the option of storing all your necessary info in one cookie. For example let’s assume you wanted to gather the users first and last name and store them in one cookie. In the example below, we will create a cookie named “user” that will contain such information.

<%
Response.Cookies("user")("firstname") = "Andrew"
Response.Cookies("user")("lastname") = "Cooper"
%>

When you need to reference the values in the cookie with keys, you have to use the key value. Have a look at the example:

<%
Response.Write(Request.Cookies("user") ("firstname"))
Response.Write(Request.Cookies("user") ("lastname"))
%>

Now let’s assume that we want to read all the cookies your server has sent to the user’s computer. In order to check if one cookie has keys or not, you must use the HasKeys property of that specific cookie. The following example shows how to do it.

<%
Response.Cookies("lastname") = "Peterson"
Response.Cookies("user")("firstname") = "Andrew"
Response.Cookies("user")("lastname") = "Cooper"
%>
<%
'The code below iterates through the Cookies collection.
'If a given cookie represents a cookie dictionary, then
'a second, internal for...each construct iterates through
'it retrieving the value of each cookieKey in the dictionary.


Dim cookie
Dim cookieKey

for each cookie in Request.Cookies
  if Request.Cookies(cookie).HasKeys Then

    'The cookie is a dictionary. Iterate through it.
%>
    The cookie dictionary <%=cookie%> has the
    following values:<br />
<%
    for each cookieKey in Request.Cookies(cookie)
%>
      &nbsp; &nbsp; cookieKey: <%= cookieKey %><br />
      &nbsp; &nbsp; Value:
      <%=Request.Cookies(cookie)(cookieKey)%><br />
<%
    next
  else
    'The cookie represents a single value.
%>
    The cookie <%=cookie%> has the following value:
    <%=Request.Cookies(cookie)%> <br />
<%
  end if
next
%>
admin

admin

Leave a Reply

Your email address will not be published.