How to restrict access to some pages but not others - PHP

Associate
Joined
24 Sep 2005
Posts
209
I need to restrict access to several PHP pages, to users with administrative access. I'm not sure what the best way to implement this is, and would appreciate any advice.

I'm assuming staff members have already logged into the network to have access to my webbased system, so staff logins are not required (although would be a bonus).

I've looked into scripts to restrict access to pages, and the code below works but I don't like the fact the password is hardcoded into the PHP script, rather than accessed from the database.

Is there any quick way to modify these scripts to check a username and password is in the database, rather than check against a hard coded value?

Thanks for your time

Code:
<html>
<body>
<h1>Please log in for access</h1>
<div>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <label>User name:
      <input type="text" name="username" /></label><br />
    <label>Password:
      <input type="password" name="password" /></label>
    <input type="submit" value="Log In" />
  </form>
</div>
</body>
</html>

The following code is config.inc.php and includes the username and password - Ideally I want these to be from a database.

Code:
<?php
define('ADMIN_USER', 'technician');
define('ADMIN_PASS', 'password');
 ?>
The following line is included at the top of every page I wish to "secure"
Code:
<?php require 'secure.inc.php'; ?>

This is the secure.inc.php code that is called from each secure page.

Code:
<?php
require_once 'access.inc.php';
if (!loggedIn()) {

  include 'login.inc.php';
  exit;
}
?>


The following code, access.inc.php is called from within secure.inc.php.

Code:
<?php
require_once 'config.inc.php';

session_start();

function loggedIn()
{
  return isset($_SESSION['authorized']);
}

// Process login attempt
if (isset($_POST['username'])) {
  if ($_POST['username'] == ADMIN_USER and
      $_POST['password'] == ADMIN_PASS) {
    $_SESSION['authorized'] = TRUE;
  }
}

// Process logout
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['authorized']);
}
?>
 
Back
Top Bottom