Donny
Donny

Reputation: 94

Session seems to expire always and can't restore the session value

I developed an app that needs users sign in. And the app keeps the session_id in the sandbox, so I just hope when session_id posted to the server, user_id can be get again by $_SESSION['id'].

Here's the code:

session_id($_POST["session_id"]);  
session_start();

$user_id = session_id($_POST["user_id"]); 

If users sign in, users can get the data they need in about 4 hours. But after several hours, users can not get any data.

I found it's because session_id($_POST["user_id"]) = nil.

I have set the session_gc_maxlifetime to 999999999. I restart the server.

However it doesn't work.

Upvotes: 0

Views: 66

Answers (2)

Ryan Vincent
Ryan Vincent

Reputation: 4513

You have a couple of issues...

1) misuse of 'sessions':

There should be no need to call the 'session_id' function. The default handling by PHP is sufficient for most websites.

You should be using session_start() as the first line in your script. This will then automatically make available the previous values that you set in the $_SESSION array.

So, if you wanted to save the $_POST['user_id'] in the session then you would do: $_SESSION['user_id'] = $_POST["user_id"];

2) session data is not for long term storage! the normal limit of 30 minutes is fine. The longer the lifetime then the more data is saved on the server as the sessions, which are normally files, cannot be deleted until they expire.

3) If you want to store the fact that a user is logged in then you should be using 'cookies' ($_COOKIE). These provide long term storage of information, days or weeks if you wish, that is stored on the client and will be sent to the server whenever the client connects to your server.

Sadly, i do not have any simple examples of setting cookies handy as i use my own 'class' to look after them and it is needlessly complex to help explain how to use them here.

However, here is a tutorial that seems to cover what you need: http://www.w3resource.com/php/cookies/cookies-in-php-with-examples.php

Upvotes: 1

Ol' Reliable
Ol' Reliable

Reputation: 570

You need to session_start(); before anything else so session_start(); should be the very first line of your code.

Upvotes: 0

Related Questions