Creating a Secured Area Without Sessions

$_SERVER['PHP_AUTH_USER'] == 'Shelley' &&
     $_SERVER['PHP_AUTH_PW'] == 'TopSecret'

If using authentication with PHP's session management seems to be too much overhead, you have two other options. First, configure your web server so that only authorized users can access some files or directories. For instance, Apache users might use .htaccess files; contains some good information about that. Microsoft IIS offers a graphical user interface (GUI) administration of access rights, so that can be done, as well.

Using HTTP to Secure PHP Pages
if (!(isset($_SERVER['PHP_AUTH_USER']) &&
    isset($_SERVER['PHP_AUTH_PW']) &&
    $_SERVER['PHP_AUTH_USER'] == 'Shelley' &&
    $_SERVER['PHP_AUTH_PW'] == 'TopSecret')) {
  header('WWW-Authenticate: Basic realm="Secured
  header('Status: 401 Unauthorized');
} else {
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

However, one more or less platform-independent way is to use authentication via HTTP. If you send an HTTP status code 401 (unauthorized), browsers prompt the client for a username and a password. This information is then available using $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']however, only if you are running PHP as a server module, not in Common Gateway Interface (CGI) mode.

You can then check this and decide whether to send out a 401 header again or to show the page's actual contents. The preceding listing shows an implementation for that. Figure shows the prompt for username and password.

The browser prompts for a username and a password.

What Does PEAR Offer?

The following PEAR packages offer functionality that can be associated to sessions and HTTP authentication:

  • Auth implements various ways to authenticate users and, therefore, protect PHP pages.

  • HTTP_Session is based upon PHP's session mechanism but offers an object-oriented access to session information.