简体   繁体   中英

Authenticate users based on url with regular expressions

I am building a PHP User login and Administration system. Every user has a role which is specified by the Administrator.

Let's say Role A has value url=/users/* . This means that a user with Role A should access every webpage that sits in the directory /users . Eg the users should access mydomain.com/users/myprofile.php , mydomain.com/users/friends/index.php but not mydomain.com/foo/index.php .

I think that a good solution is to achieve that with regular expressions.

EG. I have the rule which is url=/users/* . I replace the * sign with a regular expression, remove the url= at the start of the rule, then I get the URL of the page that the user visited and i perform a preg_match(rule,url), if returns yes the user is authenticated, if not i redirect him.

Questions:

1. With what regular expression the * sign should be replaced? I was thinking of [a-zA-Z0-9\\-\\#]+ .

2. Is it safe to use $_SERVER['REQUEST_URI'] to get the current URL that the user visited. Is it safe to use it for this purpose?

3. Is there any other way of achieving that?

You might look at this from a different angle. Usually, every page will have a method for checking the user's credentials - what you do is confirm that the rights he has allow him access to that page. So, for example, every page in the users/ directory will call a function that checks the user's cookie and confirms he is in the user group.

You don't need to check $_SERVER['REQUEST_URI'] because the page knows where it is (if not, use __DIR__ etc.)

If you need it to be more complicated, you can set up user capabilities and check these for all page additions eg

if ($visitor->hascapability(X) {
    showlink(); //etc. etc.
}

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