Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWebsite Development and Maintenance

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Setting Secure Cookies

A cookie that was set with a secure flag protects the cookie's confidentiality. (A secure flag is a directive to divulge the cookie only through a secure internet connection.)

The browser encrypts secure cookies before sending them to the server. If the cookie is intercepted, it can't be read.

This article assumes you have a fundamental understanding of what browser cookies are. The WillMaster library does not have a basic "how cookies work" article. Doing an "HTTP cookie tutorial" search is likely to reveal some published elsewhere on the internet.

There is a Setting and Reading Cookies with JavaScript article in the library. And also a Setting and Viewing Cookies with PHP article, which may come in handy if you need to brush up on how to set cookies.

The Cookie Dump Tool article has a tool for viewing cookies in browsers without going through the browser's menu.

The reason for this article is because it is a very good idea to set cookies with the secure flag whenever it is practical to do so. When a website is unavailable with https://... secure connections, secure cookies are unlikely to be practical. Otherwise, it is sensible to set secure cookies.

I'll show you how to set secure cookies with JavaScript and with PHP.

In order to show how simple and easy it is to set the secure flag, I'll provide comparison code. One will describe how to sent the cookie without the secure flag and the other how to set the cookie with the secure flag.

Information Needed to Set a Cookie

To set a cookie, the cookie must have a name. The rest of these are optional:

  • A value for the cookie.

  • An expiration time. (No permanent cookie can be set. The original Netscape specs specified a maximum of 10 years.)

  • The server path where the cookie is to be available.

  • The domain name where the cookie is to be available.

  • The secure flag.

  • The HTTPonly flag (not an option when setting cookies with JavaScript).

To set a secure cookie, the secure flag must be set.

Cookies can not be set for another domain, only for the domain in the URL of the page.

First, let's set a cookie with JavaScript. Then, with PHP.

Setting a Cookie With JavaScript

To set the cookie, we'll first make a string that contains all the optional information we want to include with the cookie. We'll use the OptionalCookieValues variable for that.

For clarity, only the optional values are shown in this code (only the cookie name is required):

var OptionalCookieValues = new String(); // This line must be here.
// Every OptionalCookieValues line below is optional.

// To set a cookie value:
OptionalCookieValues += encodeURIComponent("Any Cookie Value");

// To set an expiration time (the number in the cookieDate parameter is the number of days for the cookie to last):
OptionalCookieValues += "; expires="+cookieDate(1.25);function cookieDate(days){var now=new Date();now.setTime(now.getTime()+parseInt(days*24*60*60*1000));return now.toGMTString();}

// To set the server path (for entire site, specify / as the value):
OptionalCookieValues += "; path=/subdirectory/";

// To set the domain name in the URL of the web page (a leading period will make the cookie available in subdomains):
OptionalCookieValues += "; domain=.example.com"; // Cookies can only be set for the domain in the URL of the page.

// The secure flag:
OptionalCookieValues += "; secure";

With the above, you end up with all the optional cookie values and flags in one variable.

To set a secure cookie, the secure flag OptionalCookieValues line must be present.

Note the 1.25 in the line to specify how long a cookie shall last. Change 1.25 to the number of days for your cookie. It may be a whole or decimal number.

Other notes in the above code are about using / to specify an entire-domain cookie. And about using a leading period to make the cookie available in subdomains. When .example.com (leading period) is specified, the cookie will be available on example.com, www.example.com, books.example.com, and any.other.example.com.

Now, let's set the cookie.

document.cookie = "CookieName=" + OptionalCookieValues;

Replace CookieName with a valid cookie name. (Valid cookie names begin with a letter and are composed of letters, numbers, and underscore characters.)

Here is the entire code for setting a cookie with JavaScript. (Remember, the optional lines do not have to be present.)

<script type="text/javascript">
var OptionalCookieValues = new String(); // This line must be here.
// Every OptionalCookieValues line below is optional.

// To set a cookie value:
OptionalCookieValues += encodeURIComponent("Any Cookie Value");

// To set an expiration time (the number in the cookieDate parameter is the number of days for the cookie to last):
OptionalCookieValues += "; expires="+cookieDate(1.25);function cookieDate(days){var now=new Date();now.setTime(now.getTime()+parseInt(days*24*60*60*1000));return now.toGMTString();}

// To set the server path (for entire site, specify / as the value):
OptionalCookieValues += "; path=/subdirectory/";

// To set the domain name in the URL of the web page (a leading period will make the cookie available in subdomains):
OptionalCookieValues += "; domain=.example.com";

// The secure flag:
OptionalCookieValues += "; secure";

document.cookie = "CookieName=" + OptionalCookieValues;
</script>

To set a secure cookie, the secure flag OptionalCookieValues line must be present.

Put the JavaScript into your web page to set the cookie. (Note: Change the domain name to the actual domain name where the web page is being loaded from. Cookies can not be set for other domains.)

Setting a Cookie With PHP

To set the cookie, we'll first make an array that contains all the information we want to include with the cookie. The variables must be present, but they may be null or false.

$cookieInfo = array();
// Every $cookieInfo either must contain a value. For an optional no-value, use null or false. A comment by the value informs which to use in that case.

// To set a cookie value:
$cookieInfo['value'] = 'Any Cookie Value'; // May use null ("")

// To set an expiration time (the first number in the parentheses is the number of days for the cookie to last):
$cookieInfo['expires'] = intval( time() + (1.25*24*60*60*1000)); // May use false (no quotes)

// To set the server path (for entire site, specify / as the value):
$cookieInfo['path'] = '/subdirectory/'; // May use null ("")

// To set the domain name (a leading period will make the cookie available in subdomains):
$cookieInfo['domain'] = '.example.com'; // May use null ("")

// The secure flag:
$cookieInfo['secure'] = true; // May use false (no quotes)

// The HTTPonly flag:
$cookieInfo['http'] = false; // May use true (no quotes)

With the above, you end up with all the optional cookie values and flags in one array.

Note the 1.25 in the line to specify how long a cookie shall last. Change 1.25 to the number of days for your cookie. It may be a whole or decimal number.

Other notes in the above code are about using / to specify an entire-domain cookie. And about using a leading period to make the cookie available in subdomains. When .example.com (leading period) is specified, the cookie will be available on example.com, www.example.com, books.example.com, and any.other.example.com.

Now, let's set the cookie.

setcookie('CookieName',$cookieInfo['value'],$cookieInfo['expires'],$cookieInfo['path'],$cookieInfo['domain'],$cookieInfo['secure'],$cookieInfo['http']);

Replace CookieName with a valid cookie name. (Valid cookie names begin with a letter and are composed of letters, numbers, and underscore characters.)

Here is the entire code for setting a cookie with PHP.

<?php
$cookieInfo = array();
// Every $cookieInfo either must contain a value. For an optional no-value, use null or false (specified with a comment).

// To set a cookie value:
$cookieInfo['value'] = 'Any Cookie Value'; // May use null ("")

// To set an expiration time (the first number in the parentheses is the number of days for the cookie to last):
$cookieInfo['expires'] = intval( time() + (1.25*24*60*60*1000)); // May use false (no quotes)

// To set the server path (for entire site, specify / as the value):
$cookieInfo['path'] = '/subdirectory/'; // May use null ("")

// To set the domain name (a leading period will make the cookie available in subdomains):
$cookieInfo['domain'] = '.example.com'; // May use null ("")

// The secure flag:
$cookieInfo['secure'] = true; // May use false (no quotes)

// The HTTPonly flag:
$cookieInfo['http'] = false; // May use true (no quotes)

setcookie('CookieName',$cookieInfo['value'],$cookieInfo['expires'],$cookieInfo['path'],$cookieInfo['domain'],$cookieInfo['secure'],$cookieInfo['http']);
?>

Put the PHP code somewhere on your web page above any HTML code. If any HTML code or other web page content is sent to the browser from the server before the cookie is set, the cookie setting will fail. (Note: Change the domain name to the actual domain name where the web page is being loaded from. Cookies can not be set for other domains.)

It is fairly simple to add the secure flag to a cookie when it is set, once a person knows how to do it. And now you have the information for that.

This article first appeared with an issue of the Possibilities newsletter.

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC