I have a site that stores registered user's site preferences in a MySQL database and am hoping to modify this so that non-registered us开发者_开发知识库ers can use browser cookies to benefit from site configurations too.
Is there a common way to do this? My thoughts were to create an additional database table with these fields:
id
unique_cookie_hash
site_preferences
Where the unique cookie hash is what's stored in the visitor's cookie and the site preferences is a JSON encoded string containing the guest user's settings. So, for a user who is not logged in the site will check for a cookie. If the cookie exists it will try and pull up preferences via the value stored in the cookie. If the cookie does not exist or a match was not found, the site will create one and assign it some default setting values.
As the guest makes changes the site will attempt to run an UPDATE query on their unique_cookie_hash.
I'm assuming this would work (and that it's how most sites do it?) but as it's a newer concept for me I was wondering if anyone knew of any good tutorials or 'got-yas' to watch out for with this method.
Thanks.
That would work, just note that by serialising your options into a JSON string you can not select anything from them.
So if you wanted to know how many registered people like color scheme A, for example, you'd need to do all the code in PHP (at least in a non cumbersome way).
PHP has its own set of functions for managing sessions, and there are alternative (some might say better) libraries out there for session handling. It's a complex issue with unexpected security considerations, so I wouldn't try a homebrew solution without really researching it first.
Assuming you've looked into how to securely store session information, you can keep users' site preferences there, and when a user logs into their account, just copy their stored preferences to their session, which the site will actually act upon.
It depends on the number of settings, but in general I wouldn't bother with database at all, but store them settings in a cookie.
精彩评论