Maintain PHP Session in web app on iPhone

The accepted answer for this question is wrong, this is easy to do.

The trick is to do this:

// Start or resume session
session_start(); 

// Extend cookie life time by an amount of your liking
$cookieLifetime = 365 * 24 * 60 * 60; // A year in seconds
setcookie(session_name(),session_id(),time()+$cookieLifetime);

That’s it! No local cache manifest required and you can work with sessions in your web app as you would with web pages in a regular desktop or mobile browser. I tested on iPhone 5 (iOS 6.1) and iPhone Simulator / iPad 2 (both iOS 6.0) and this worked even when shutting down and restarting the device / simulator during the session.

It works great: the resulting session cookie gets shared between multiple instances of the web app if a user adds your web app to the home screen several times, and unless Safari’s Private Browsing mode is switched on, the session cookie will even be available when surfing to your web page directly from Safari instead of using the web app. So no matter how the user approaches your app, the current session seems to always get restored when using this strategy.

To try it yourself, use above code and output session_id() in your web page (temporarily, as it’s a security risk) and see if it changes between closing and opening your web app from the home screen (try rebooting your device during the session as well). If the outputted session ID doesn’t change, it works: it is apparently being stored in some (shared) local cache by Safari.

Tested and confirmed to work under iOS 4.2.1, 5.1.1, 6.0 and 6.1.

Disclaimer: Apple’s documentation explicitly states the need for a local cache manifest in order to save data locally in a web app, but this solution works without that. Ie, this solution may rely on undocumented or buggy behavior by Mobile Safari. However, since it works on so many iOS versions, I am under the impression that this is intended behavior (at least on Apple’s part), just unclearly documented.

Leave a Comment