简体   繁体   中英

How to store session data into database in Codeigniter?

In this case I have 2 tables in database "users" and "posts". First table extends basic user data (id, firstname, lastname, username, mail, passwords etc...) Second one is about posts (id, title, text, author etc...)

So when user gonna create a post, he need to fill title field and text field, author field should be filled with username pulled directly from session and stored it to db.

There are different ways to do this but what I suggest - do not store any user data in the session. When the user first logs in - create a "token" which is a long random string with maybe a datetime at the end of it for reference. Update the users table with the token, and save the token to the session.

When the user goes to another page - you grab the token from the session - and use that to return the user record from the database. You then have all the user details for whatever you need. This will get you out of the habit of storing any user, etc details in the session. This is much better for security and it makes your system easier to deal with long term. Otherwise you are in the position of having to update the user database table AND the session anytime the user makes any changes.

Your better and probably safter option here is to store your SESSION data in the database itself.

Have a look at https://www.codeigniter.com/userguide3/libraries/sessions.html . You will need to create a table in your DB called ci_sessions (or it is renameable in the config file) and then you could if you so needed pull the user name from the session.

Sessions stored on disk are fine (AFAIK) if its a dedicated box etc and you are in complete control of the code. Its when you are on a shared box they can't be relied upon.

When you login, create an array of things that will go into the cookie and session DB; An example

if (password_verify($pass1, $stored))
    {
      $data = array(
        'name'         => $row->name,
        'is_logged_in' => TRUE
      );
      $this->session->set_userdata($data);

The name is part of the db record for the user. But is not part of the login. When you search for the user to log them in, name is one of the things you include in the query

Then, in your form input, simply set_value = $this->session->userdata('name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM