How do I protect a page only for logged users?

前端 未结 4 1287
南旧
南旧 2020-12-11 02:59

I created a login form that works great. But I realized the page my user is directed to can still be accessed by anybody. How do I protect the page being accessed only vie

4条回答
  •  孤街浪徒
    2020-12-11 03:39

    You should basically use session management to track whether a user is in an authenticated session or not. If not, you (re)direct them to the index page; if yes, you grant them access to whichever resource they requested.

    To use sessions, put your session setup functions at the top of every PHP script inside your application (setup functions include session handler, cookie domain and cookie name), and say session_start(). Then, check if a login flag has been defined in the current session like $_SESSION["user_is_logged_in"]. In the authentication page, you would of course define $_SESSION["user_is_logged_in"] = true; at some stage.

提交回复
热议问题