Tutorials PHP HTTP Authentication

HTTP Authentication

There are numerous ways to protect your website content from unauthorized access, depending on your situation. If you have an API, you will authenticate through tokens. If you need to protect non-programming files like images or documents, you will need HTTP authentication using .htaccess file. If you have a registration system, you'll want a database and a login form on your website. However, you may also sometimes not want a HTML form for login. Your website might not be membership focused and having a login form might confuse users. This tutorial will teach you how to create a login system without a HTML form.

The login screen

PHP can use headers to bring up a login screen. You will need to use these headers on the initial load and on invalid attempts.

header('WWW-Authenticate: Basic realm="Employees Only"');
header('HTTP/1.0 401 Unauthorized');

The input

Data that the user enters into the login screen is stored in the $_SESSION global.

$user = (isset($_SERVER['PHP_AUTH_USER'])) ? $_SERVER['PHP_AUTH_USER'] : '';
$pass = (isset($_SERVER['PHP_AUTH_PW'])) ? $_SERVER['PHP_AUTH_PW'] : '';

The validation

You have the form and the user input, so compare the usernames and passwords. You could pull the users from a database, hard-code them into the code, or base it on some algorithm. Aesthetically, I don't like the design of that login screen so I would never use it with the general public.

An example authentication system with hard-coded credentials:

// All passwords hashed with password_hash($password, PASSWORD_DEFAULT)
$logins = array(
  'simon' => '$2y$10$eN.LoyggyjGaL9MqDndsSOCxY9HQ6yoMPcdG6q4k5m53mIJs14av2',
  'jeff'  => '$2y$10$6dXzlsg5JugQA5RgibJZTen9L2eQTP.l7PLd32DMbaY.CPlLwuHfO',
  'peter' => '$2y$10$dwvQ9DSko29KOx/et8QxU.0LPVJZa1yZ6ZzYTEvkn7UdNQtDaktma',
  'david' => '$2y$10$EvC8gsMqe0jgUwoe4nw4suQHoHR7W/k1PpQ5qOlSv0Ofluujtfxg2',

// Get system usernames
$login_keys = array_keys($logins);

// Get login form input
$user = (isset($_SERVER['PHP_AUTH_USER'])) ? $_SERVER['PHP_AUTH_USER'] : '';
$pass = (isset($_SERVER['PHP_AUTH_PW'])) ? $_SERVER['PHP_AUTH_PW'] : '';

// Compare credentials
$validated = in_array($user, $login_keys) && password_verify($pass, $logins[$user]);

// Kill script if user does not validate
if (!$validated) {
  header('WWW-Authenticate: Basic realm="Employees Only"');
  header('HTTP/1.0 401 Unauthorized');
  die ('Access Denied');

// User is validated! Continue the script.

Posted by on . Category: PHP


No comments posted yet

Comments are disabled