Monday, January 17, 2011

iPhone Cookie Hell

I was having a hell of a time getting a mobile website to logout iPhone users. The website uses cookies to keep track of logged in users, and the cookies would simply not delete on an iPhone. Worked fine on Android, Chrome, Safari (on the desktop), etc. The app used the textbook method for deleting cookies in PHP, setting the expiration to a time in the past:

setcookie($usercookie, '', time()-3600);

And then redirected the user to a page with a check for a logged in user which started with;

if(!isset($_COOKIE[$usercookie])) { ... }

Which always said the cookie WAS set. Hey, I just deleted it!

After much pulling of hair, I realized that Mobile Safari won't delete cookies until the user returns from the browser to the home screen. You can ask it to delete the cookie, but those requests just seem to queue up until that return to the home screen. But, it will update their values immediately. So now my logout php looks like:

setcookie($usercookie, ''); // null the cookie value, without specifying a time, for the iPhone
setcookie($usercookie, '', time()-3600, '/'); // delete the cookie, for all other browsers

And the auth check looks like:

if(!isset($_COOKIE[$usercookie]) || empty($_COOKIE[$usercookie])) { ... }

Voila.

No comments:

Labels

Blog Archive

Contributors