Maintain PHP Session in web app on iPhone

I have a jquery mobile web app. On my iPhone when I am on the web app I have a login and session variables. If I leave the app to go to another location on the phone and then return to the web app, I have to log in again. It seems like the session is not maintained. Further if I have an external link and it opens safari for that link, that same session is not transfered to the safari window. Is there a way to maintain the session?


Solution 1:

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.

Solution 2:

I'm guessing you're referring to the Apple "fullscreen capable" meta tag "web apps". They exist in a sandbox, so no, session data won't be maintained.

Solution 3:

If you don't want to open safari when clicking on a link just use this git.

https://gist.github.com/kylebarrow/1042026

Basically just copy the file stay_standalone.js to your project and in your views include this line:

<script src="stay_standalone.js" type="text/javascript"></script>