PHP Session ID Not Retain in iOS App

Currently my iOS app was retrieving data from the server which built using PHP + MYSQL through JSON, then in my PHP I tried to echo the session_id() . My app was using NSURLConnection sendAsynchronousRequest to communicate with PHP.

I tried request the same URL for 3 times, the returned session id will be in different value, I had included session_start() in my PHP as well.

But if I run the URL in browser, no matter how many times I run it the session id will always be the same.

Here is my iOS request code:

NSString *newURL = @"http://www.example.com/index.php?value=getData"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:newURL]];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
            if ([data length] >0 && error == nil){
                NSDictionary *myDict = [NSJSONSerialization
                                                JSONObjectWithData:data
                                                options:kNilOptions
                                                error:&error];
                NSLog(@"%@", myDict);
            }
        }];

Please help. Thanks.


I had a similar problem here (in a webview).

Try to increase the Lifetime of your Session Cookie in your PHP File.

// Start session
session_start(); 

// Extend cookie life time by an amount of your liking
$lifetimecookie = 30 * 24 * 60 * 60; // A month 
setcookie(session_name(),session_id(),time()+$lifetimecookie);

You have to understand how PHP is keeping the session on the server side. It is done by sending back cookie to the client (PHPSESSID). This cookie is then sent back to the server with every new request BY YOUR BROWSER.

But, you are NOT using a browser but connection object. You need to keep the returned session id on the client side and send it back to the server with every new request. This is done via headers. Response from the server will contain Set-Cookie and you need to send the session id cookie with a Cookie header.

链接地址: http://www.djcxy.com/p/41148.html

上一篇: Codeigniter API会话

下一篇: PHP会话ID不保留在iOS应用程序中