I'm building a Session class, and was wondering how to deal with expired sessions in the database. I was thinking about throwing a random number, for example between 1 and 1000, and if it is 1, then I delete all the expired sessions.
开发者_开发百科I guess this will be faster than reading a file or another table in the DB, to check if I have to delete the expired sessions. But I'm not sure if this will work fine when I have a lot of visits. I could increase the range of the random number, but I don't feel good depending on randomness, so I'm not sure this is the way to go.
A cron would be better indeed, but I wanted it to be auto-sufficient.
Don't use random. It's best to use a cron job.
If you do it in a regular request, using random or any stored value, you got the overhead of clearing the sessions in that request. Your visitor might experience a sudden delay because of this.
If you still need to go this way, still don't use random. Write the last clean-up time into your database and read it to check if it is time for your next clean-up. Each request will probably need some database interaction after all, so this single query to retrieve a date value from a table that needs to have only one row and one column won't make any difference. If not all requests need the database, you could limit this check to only those requests which do.
But as I said: rather don't and just use a cron job.
I had similiar problem, for which I didn't want to/couldn't use cron jobs. My solution was to create a new PHP page which does the session cleaning.
When the user visits the site, and it is time for clearing the session cookies, an AJAX request is made to that page. This way, the user does not experience any delay.
However, to make this secure, you'll need to store one-use SID for each cleaning page call.
精彩评论