This issue cost me several hours due to poor documentation of the setcookie() function in PHP. How do I delete a cookie in PHP?
The Context:
A Drupal site using a few jQuery modules, including autosave. Autosave was being used to persist the user-entered values in a medium-sized form, so that if they left the computer, closed the browser etc without completing the form, their original values would be there when they came back. However, the client was also worried about privacy, and therefore wanted the autosaved values to be deleted once the form was submitted, so that another user coming to the same computer wouldn't see the form populated with the previous information.
Autosave uses cookies to store the form data, and I didn't want them deleted immediately upon form submission, but only after some post-processing in one of my custom modules had taken place, so what I needed to do was delete those cookies in a PHP function after calling node_save().
The Problems
I quickly found out that I need to use the setcookie() function - however here is where the consensus ended. Various different sources indicated that cookies could be removed by:
- Simply calling setcookie("cookiename") without any parameters
- Calling setcookie("cookiename", "") - i.e. setting a blank value
- Calling setcookie("cookiename", "", TIME) where TIME is some time safely in the past, e.g. the day before.
On further inspection it seemed as if 3) was the way to go, and the only safe way of removing the cookie across browsers. The browser detects that the cookie's expiry date was in the past, and removes it. Great! Except...it didn't work for me.
Further inspection revealed that when the cookie has been created with a domain (as it usually will be for Drupal sites) you need to add the domain and the path to the setcookie() statement. E.g. setcookie("cookiename", "", time()-(60*60*24), "/", "mydomain.com"). This didn't work either! This is because my cookie domain, set in my settings.php file for Drupal, was "www.mydomain.com", not "mydomain.com". However, setcookie("cookiename", "", time()-(60*60*24), "/", "www.mydomain.com") also didn't work - because the PHP setcookie() function automatically adds a leading "." to the domain name! So my browser was searching for cookies on the ".www.mydomain.com" domain, which obviously didn't exist.
The Solution
Finally I stumbled across the bit of information I needed. If you include the Path variable "/", but EXCLUDE the domain variable altogether, then PHP will automatically look for the cookie on the domain from which the PHP statement is being called. So: setcookie("cookiename", "", time()-(60*60*24), "/") finally worked!