问题
I've just created a web app on my iPhone. I can open it and log in with no problem, but whenever I return to the app it has forgotten my previous session and I have to re-enter my username and password.
There have been a few other questions about this, but their answers haven't helped me to solve the problem because I'm not sure where to put the PHP that was provided.
This is the best answer that I've found: Maintain PHP Session in web app on iPhone
In the answer, Wilbo Baggins (https://stackoverflow.com/users/346440/wilbo-baggins) provides the following code:
// 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);
I entered that code between <?php
and ?>
tags in the website's header, but that hasn't solved the issue. I'm guessing that I'm putting it in the wrong place, so I'm looking for guidance that will explain where I should actually be putting it.
Thanks.
--
BUMP: Is there anyone out there who can help me solve this issue or, at the very least, knows how I can get in touch with Wilbo Baggins (https://stackoverflow.com/users/346440/wilbo-baggins)?
回答1:
In your login.php, add the following code when login information correct:
session_start();
//your code here
if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']),"apple")) //to prevent cookies for non-apple devices
{
$cookieLifetime = 365 * 24 * 60 * 60; // A year in seconds
setcookie("ses_id",session_id(),time()+$cookieLifetime);
}
Then, in every other *.php you want your session_id to be restored, add the following line BEFORE session_start():
if($_COOKIE['ses_id']){
session_id($_COOKIE['ses_id']);
}
session_start();
In your logout.php, add the following code:
session_start();
$cookieLifetime = 365 * 24 * 60 * 60; // A year in seconds
setcookie("ses_id","",time()-$cookieLifetime); //set lifetime to negative to autodelete cookie
session_destroy();
Hope this helps.
来源:https://stackoverflow.com/questions/16467664/maintaining-a-php-session-on-an-iphone-web-app