JavaScript setrawcookie
Send a cookie with no url encoding of the value
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 | function setrawcookie (name, value, expires, path, domain, secure) { // Send a cookie with no url encoding of the value // // version: 1008.1718 // discuss at: http://phpjs.org/functions/setrawcookie // + original by: Brett Zamir (http://brett-zamir.me) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + derived from: setcookie // + input by: Michael // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: setcookie('author_name', 'Kevin van Zonneveld'); // * returns 1: true if (typeof expires === 'string' && (/^\d+$/).test(expires)) { expires = parseInt(expires, 10); } if (expires instanceof Date) { expires = expires.toGMTString(); } else if (typeof(expires) === 'number') { expires = (new Date(expires * 1e3)).toGMTString(); } var r = [name + '=' + value], s = {}, i = ''; s = {expires: expires, path: path, domain: domain}; for (i in s) { if (s.hasOwnProperty(i)) { // Exclude items on Object.prototype s[i] && r.push(i + '=' + s[i]); } } return secure && r.push('secure'), this.window.document.cookie = r.join(";"), true; } |
Examples
Running
1 | setcookie('author_name', 'Kevin van Zonneveld'); |
Should return
1 | true |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have setrawcookie goodness in JavaScript.
Two notes:
1. This function is not identical to the PHP one, as the PHP one takes unix timestamp as the expiry, whereas this function takes the number of seconds between now and expiry as the input field.
2. The expiry input field must not be quoted else the 'typeof' statement will view it as a string rather then a number, which will make the field invalid and the cookie will expire at end of session.


Brett Zamir
Jan 28th