PHP setcookie() function

In this chapter you will learn:

  1. What is PHP setcookie() function
  2. Syntax for PHP setcookie() function
  3. Parameters for PHP setcookie() function
  4. Note for PHP setcookie() function
  5. Example - Set each fields for a cookie
  6. Example - Leave field unset for a cookie
  7. Example - setcookie() send and receive
  8. Example - delete a cookie by set the expiration date to the past
  9. Example - setcookie() and arrays

Description

PHP setcookie() can send the appropriate HTTP header to create the cookie on the browser.

Syntax

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Parameter

All the arguments except the name argument are optional.

You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot be skipped with an empty string, use a zero (0) instead.

  • name - The name of the cookie.
  • value - The value of the cookie.
  • expire - The time the cookie expires.
  • path - The path on the server in which the cookie will be available on.
  • domain - The domain that the cookie is available to.
  • secure - Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).
  • httponly - When TRUE the cookie will be made accessible only through the HTTP protocol.

Note

Make sure you call setcookie() before sending any output to the browser.

This is because setcookie() needs to send the Set-Cookie: HTTP header. If you output any content before calling setcookie(), PHP automatically sends the headers first, so by the time setcookie() is called it's too late to send the Set-Cookie: header.

Example 1

Here's an example that uses setcookie() to create a cookie storing the user's font size to 3:


setcookie( "fontSize", 3, time() + 60 * 60 * 24 * 365, "/", ".example.com", false, true );   

time() returns the current time in UNIX timestamp format. So the expiry time is 60 * 60 * 24 * 365 seconds after the current time, or one year into the future.

The cookie will remain until that time, even if the browser is closed and reopened, unless the user chooses to delete it manually.

It sets a path of "/" so the cookie will be returned to any URL within the Web site.

It sets a domain of ".example.com" so that the cookie is sent to any server within the domain example.com.

It sets No secure flag so that the cookie can be sent over standard HTTP connections.

It sets HttpOnly flag so that JavaScript can ' t read the cookie.

It's a good idea to precede the domain value with a dot (.), as in ".example.com", unless the domain is a hostname such as www.example.com.

Example 2

In the following example, setcookie() is used to store the number of page views.

The expires argument is zero, so the cookie will disappear when the user closes her browser.

The domain argument is an empty string, which means the browser will only send the cookie back to the exact Web server that created it:

setcookie( "pageViews", 7, 0, "/", "", false, true );

You can update an existing cookie by calling setcookie() with the cookie name and the new value. You need to supply the path and expires arguments when updating the cookie:

setcookie( "pageViews", 8, 0, "/", "", false, true );

Example 3


<?php//from  j a v  a2 s  .  co m
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/user/", "example.com", 1);
?>

To see the contents of our test cookie in a script, simply use one of the following examples:


<?php/* jav a2 s  .  co m*/
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

Example 4

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser.

Examples follow how to delete cookies sent in previous example:


<?php/*  j a  va 2  s. c  o m*/
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/user/", "example.com", 1);
?>

Example 5

You may set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:


<?php/*j a va2s  .c o  m*/
// set the cookies
setcookie("cookie[three]", "cookieA");
setcookie("cookie[two]", "cookieB");
setcookie("cookie[one]", "cookieC");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}
?>

Next chapter...

What you will learn in the next chapter:

  1. How to access cookie values
  2. Example - To display the pageViews cookie set
  3. Refresh to get the cookie data
Home » PHP Tutorial » PHP Cookie
PHP Cookies
PHP Cookie Components
PHP setcookie() function
PHP Access Cookies
PHP Remove Cookies