0

I have an admin system and a user system on my website. Some data on the user system will not change, but the admin data will change instead. So I was wondering if there was a way to restrict the admin session (when they login) only to the admin directory (/admin), so that it does not interfere with the rest of my website?

Thanks,

Lucas

Lucas
  • 16,930
  • 31
  • 110
  • 182
  • 4
    The question is not clear enough – zerkms Apr 08 '12 at 12:40
  • nope, it can express more than one particular problem PS: there is no "folders" in http - the wrong terms is the first thing that confuses the question – zerkms May 04 '12 at 07:14

4 Answers4

1

There are many ways to handle something like this. Probably the easiest is to check the permissions and $_SERVER['REQUEST_URI'], and if the user isn't in the admin/ area, redirect into it.

// Assuming you've saved an admin flag in session
// and the user request URI doesn't contain admin/
if ($_SESSION['admin'] === TRUE && !preg_match('/admin\//' $_SERVER['REQUEST_URI'])) {
  // redirect into the admin/ area
  header("Location: http://example.com/admin");
  exit();
}

Update:

By popular request, here's the reverse to enforce an admin login in the admin/ directory

if ((!isset($_SESSION['admin'] || $_SESSION['admin'] === FALSE)  && preg_match('/admin\//' $_SERVER['REQUEST_URI'])) {
  // redirect out of the admin/ area
  header("Location: http://example.com/");
  exit();
}

Actually, assuming the admin pages are separate scripts, you don't really need the preg_match() in this part. But if you have an MVC pattern where the admin script may not actually be served from a file in the admin directory, use the regex match.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • +1 and you should do it the other way round too, like in my answer, so that non-admins can't access the admin area. – Shomz Apr 08 '12 at 12:54
  • yep, thank you! I was looking for an answer in something like session_start(). But it still works anyway. Thank you! – Lucas Apr 09 '12 at 08:16
1

It is not a solution, but it is a workaround. You can use same session for this too. Just create the session identifier for each path at the path name as

$_SESSION['path/to/admin']['var1'] = 'value1';
$_SESSION['path/to/admin']['var2'] = 'value2';

Such way, you can retrieve the value of path independent session variables.

Starx
  • 77,474
  • 47
  • 185
  • 261
1

Use session_name before calling session_start. In that you may be able to differentiate between user and admin areas.

  • User

    session_name("user");
    session_start();
    
  • Admin

    session_name("admin");
    session_start();
    
Alexander
  • 23,432
  • 11
  • 63
  • 73
0

Not sure I understood the question completely, but you can always check if the user is an admin, and if not, just redirect them from the admin system to the user system.

Tamara Wijsman
  • 12,198
  • 8
  • 53
  • 82
Shomz
  • 37,421
  • 4
  • 57
  • 85