Storing Session data into MySQL database

store session data into mysql table

Hi Guys,

Today we will discuss on store PHP session data into MySQL database.

Its most critical part of the application when our application runs on the shared server and session data is hijacked or injected harmed by an attacker. So we need to be careful on this.

Everyone knows that my session data is stored by default into the /tmp folder and this is writable by all users.

For storing all my session data into the MySQL database, first, I will create the MySQL table.
Now suppose I have already created a database and named it as ‘system_data’ and I will create a MySQL table on this and we will insert all session data into that table.

Above SQL for creating a table into MySQL database.

For storing session data into MySQL table we need to change the default process of saving data.
We need to create 6 functions those handles the session process.

1. Open session data store
2. Close session data store
3. Read session data
4. Write session data
5. Destroy session data
6. Clean old session data

Below is the implementation of the all the mentioned functions.

After writing all these 6 functions, now I will use functions for the session.

so I will call session_set_save_handler() function and pass as arguments all above written 6 functions into this function and after that call the session_start() function.

Now it’s time to verify that session is working properly or not.I had created a session variable ‘abc’ and passed some data ‘session_data’ to it.

Now I will open created table for storing session data and check the data into the table so it will display data like this.

oie_gai2qm7wmfae

Storing session data into MySQL database is the good security practice.It’s also helpful when we will be using the multi-server architecture because we need to store session data in some common place.

Leave a Comment

Your email address will not be published. Required fields are marked *

Optimization WordPress Plugins & Solutions by W3 EDGE