简体   繁体   中英

Prevent user to access if has not logged in

I am currently working on developing a simple web system, so an user first will be directed to a login page, then a processing page. If its account data provided is correct, it will be directed to the main page, so it can carry out some actions, at last it can logout.

So what I want to ask is: how can I prevent user to access the processing, main or logout page before they login, I mean, if I do not limit it, the login action is by some means useless. I am using wamp to develop the web system.

I have considered making use of the session variable, however, I have no idea how to check the value of the variable. If I start a session at the login page, so if I skip the login page but directed go to the main page, do I have those session variable present in the main page?

1) Add session_start(); at the top of the php page to initialize sessions.

2) Add if statement

if($_SESSION['logged_in'] == 1) { ..show page.. } else { show login page }

3) Create a login form which validates data, if data is correct then it adds $_SESSION['logged_in'] = 1; and redirects to profile page with logout button.

That's all :)!

I suggest that you check some tutorials, since it will give you some more information how to do that - http://www.intechgrity.com/create-login-admin-logout-page-in-php-w/ or any other link via google - "How to create login/logout functions with SESSIONS".

About your question, in each page you will put session_start(); at the start of the file, they will have all sessions you have specified for user.

EDIT:

Added few useful links -

http://www.php.net/manual/en/book.session.php

http://www.tizag.com/phpT/phpsessions.php/

http://www.w3schools.com/php/php_sessions.asp

well,this is what i will do. Check with an if statement if a session variable that holds, for example, the username from the login page exists, then if it doesn't show an error 404 page, or redirect the user to any error page...you might want to create that yourself anyway (so that it redirects them back to the login page).

<?
session_start();
if(!$_SESSION['username']){
 header("Location: HTTP/1.1 404 File Not Found", 404);
          exit;}
?>

You could also create a new file and place this code there so that you call it on everypage that will require a user to login before accessing it....

但是第一次尝试访问非登录页面然后您将被重定向到登录页面,然后尝试访问相同的非登录页面,即使您没有登录,您也可以第二次访问该页面。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM