Reputation: 2008
I am trying to get session id using session_id(); But I get to know that It will be regenerated after every 5 minutes.
So i got a trick to set random number into a user defined session variable . like ,
$uniqueId = uniqid(rand(), TRUE);
$this->session->set_userdata("my_session_id", md5($uniqueId));
Now question is where should I place this code. If I place this code in my controller's constructor , It will be executed on each request. and will give me a different session id for each request.
How can I set this session variable only once ? and it will not change until session destroy() .
Upvotes: 4
Views: 18631
Reputation: 1737
It's better to regenerate Session ID to prevent Session hijacking. Disabling session Id regeneration is bad Idea. read When and why I should use session_regenerate_id()? for more information.
If you want to identify the user by session, It's not good Idea to use Session Id.
You can set user ID on the session and use that as Identification for login. for more security you can store a random string as a key on the database and also set it on the session. On checking you can compare user ID and that key on the session with the user id and the key on the database.
If you want to have the same thing for Guest clients, you can do what I mentioned on #3 and store $_SESSION['guest']=USER_IP
and create a guest table on the database which stores guest IP. and when isset($_SESSION['guest'])
happens, you can check guest table instead of users table.
If you want protect your session against XSS, you can store another user information such as IP in your database and check that at start of your code.
Upvotes: 3
Reputation: 174
use php's built in function:
$session_id = session_id();
now $session_id
is a unique session id.
Upvotes: 4
Reputation: 409
In the config.php set the below, then you don't have to generate your own session id
$config['sess_expiration'] = 0;//Session does not expire
$config['sess_time_to_update'] = 0;//Disable session ID regeneration
In your controller you'll need __construct()
public function __construct(&$params){
// DO NOT forget this
parent::__construct($params);
}
Then when you get the session you'd use
$this->session->userdata('id');
Upvotes: 0
Reputation: 6969
In your constructor
check first whether session already set or not
.If session is not set then set it
otherwise do nothing
.Like this..
$uniqueId = uniqid(rand(), TRUE);//generates random number
if(!$this->session->has_userdata('my_session_id'))//if session is not set then it sets (if your session has already value then this step will be skip out)
{
$this->session->set_userdata("my_session_id", md5($uniqueId));
}
Upvotes: 1