Edward R
Edward R

Reputation: 3

PHP session_set_save_handler: read() before write()

I'm trying to save all my session data in the Database and have this class that should handle all that and have used session_set_save_handler to set that up. Now, I don't know if it's because I don't fully understand the whole idea behind that function but the problem I'm running into is that the read() function of my Session handler class is called BEFORE the write() function is. And the reason why that is not good is because read() is trying to look for information in the database that has yet to be written into the database and of course it gets empty results.

So I decided to read the documentation behind session_set_save_handler and it looks like the only time write() is called is when the session is terminated or when PHP is closed. From my perspective this seems pretty useless... why would anyone write() or store this information at the END before they could ever get a chance to retrieve it?

What I'm trying to do is when someone creates a use session, this information is written into the database and whenever I want to check for authentication or lookup user values I want to retrieve said information.

Am I going about this all wrong?? I appreciate any clarification. If anyone needs any code to demonstrate what I'm trying to do I'll update this.

Upvotes: 0

Views: 442

Answers (1)

C3roe
C3roe

Reputation: 96383

From my perspective this seems pretty useless... why would anyone write() or store this information at the END before they could ever get a chance to retrieve it?

What do you mean before they got a chance to retrieve it?

To retrieve it, the read method is called – and it is called before, so that you already have the info. But somehow this is what you are complaining about …?


Am I right in assuming that you don’t have much understanding of how PHP’s session mechanism works at all?

You call session_start on top of every script. If PHP finds a session id in the parameters passed to the script, it looks for an existing session with that id, and if it finds one, it reads the data from it. From that point on, you can work with that data – PHP has put it into the super-global array $_SESSION for you. You can access it from there, and you can put new data into it or alter the existing data.

And then, when the script ends, or session_write_close is called, the data is written back.

So of course the read function is called before the write function.

Upvotes: 1

Related Questions