Какова лучшая практика для использования Cookie для аутентификации с PHP?

необходимо ли когда-либо использовать защищенные членские переменные?

Зависит от того, насколько придирчивый Вы о скрывающемся состоянии.

  • , Если Вы не хотите утечки внутреннего состояния, затем объявляя все Ваши членские частные переменные, способ пойти.
  • , Если Вы действительно не заботитесь, что подклассы могут получить доступ к внутреннему состоянию, затем защищенному, достаточно хорошо.

, Если разработчик приезжает и разделяет Ваш класс на подклассы, они могут испортить его, потому что они не понимают его полностью. С членами парламента, не занимающими официального поста, кроме открытого интерфейса, они не видят реализацию определенные детали того, как вещи делаются, который дает Вам гибкость изменения его позже.

6
задан Dan Whitinger 27 October 2009 в 23:33
поделиться

4 ответа

nothing is safe on the client side.

You change the login flag on Cookies easily on any browser. Thus it is more recommended to be saving login-related data on php's $_SESSION

If you wish to extend the session, simply look at session_set_cookie_params().

By default, the same session will be used for the current domain and all the paths on that domain. Thus it is readable for both blahblahblah.com/ and blahblahblah.com/login/

When the user logs in, save the username and the hash of the password in the Session.

At the start of each script, verify the Session's username and password with the one in database. If is correct, then set a flag (e.g. $userLoggedIn = true) to indicate on server-side that the user is logged in. else false.

3
ответ дан 17 December 2019 в 04:48
поделиться

The cookie is per domain, so no matter how deep you are in your directory structure, the cookie will be read OK (as long as your domain stays the same - NB this means that www.example.com and example.com can be different cookies).

I'd suggest having an authentication check that compares the session ID in the cookie with eg a database table listing logged in users and their session ID - this check can be in its own method/include file that is include()'d on each page. That way the check will be performed on every page load. NB this is basic and there are much more secure methods - some of which have been mentioned in other comments here.

As Mauris said though, nothing is safe on the client side - don't use a cookie to store a "logged_in" value which you check for true/false!

0
ответ дан 17 December 2019 в 04:48
поделиться

Its a good idea to have one script do the session/login check and include it in the secure pages. AS for the depth , you can define that in the setcookie() if the directory parameter is set to "/" then its accessible all across.

Generally its a good idea to use sessions instead of cookies , as thats more secure , but you can decide to build your own session system based on encrypted data in the cookie and that can work too , but again sessions, which store data on the server side are recommended.

0
ответ дан 17 December 2019 в 04:48
поделиться

Some thoughts, in no particular order:

  • Separate out the various layers: persistent storage vs authentication.
  • PHP sessions are quite robust and are the recommended way to maintain persistent storage.
  • You can have a valid session, but not a valid login.
  • Avoid multiple cookies. One is enough. PHP sessions work with one cookie.
  • You can set sub-domains and paths on cookies, but there's really little point unless you set lots, which is not recommended (see above).
  • Put everything you think you might want in a cookie in the session instead.
  • You should have some common code that all your pages include. That is where you initialize your session. Then everything will Just Work. It can also verify the login is valid, too.
  • Have one place that does the login authentication and everything associated with that.
  • Don't forget a logout screen!
2
ответ дан 17 December 2019 в 04:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: