My website had no security on cookies and some cookies were set by javascript. For security reasons, I had to add secure and httponly flags and so to adapt my javascript. The only way I found was to use ajax.
I wrote a php script called by javascript thru ajax to set cookies. As I know javascript is monotask and asynchronous tasks are scheduled after the synchronous ones. So I had to modify my code to wait for ajax return before calling next pages. For example (see javascript below), when action is 'RELOAD', if a form tag is found on page, it's submitted, if not, a simple reload is done.
javascript :
function setMultiCookie(prm, action) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
setMultiCookieRet(action);
}
};
xhr.open("POST", "setMultiCookies.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("prm="+encodeURIComponent(prm));
}
function setMultiCookieRet(action) {
switch(action) {
case 'RELOAD':
var form = document.getElementsByTagName('form');
if (form.length > 0)
form[0].submit();
else
location.reload(true);
break;
case 'NONE':
break;
default:
window.open(action,'_self');
}
}
php script setMultiCookies.php :
<?php
header("Content-Type: text/plain");
if ($_POST["prm"] == '')
exit;
$prm = explode('µ', $_POST["prm"]);
foreach ($prm as $parms) {
list($name, $value) = explode('§', $parms, 2);
if ($value == "-unSetCookie-")
setcookie($name, '', 1, "/", "", TRUE, TRUE);
else
setcookie($name, $value, 0, "/", "", TRUE, TRUE);
}
?>
Example of a call to set cookie var1 to val1 and var2 to val2, to unset val3 and to reload page after that :
<span onClick="setMultiCookie('var1§val1µvar2§val2µval3§-unSetCookie-', 'RELOAD');" class="button">
It works most of the time but in some cases, especially with form tags, it doesn't. I don't know what happens. I'm sure php script works. I've made some trace displays and I've tested that php setcookie return is set to true. But cookies are not set. I suppose something happens before set is done. I had that problem earlier when I loaded a page in javascript synchronous part.
I would be glad if you know what happens or if you know some way to investigate.