How To Use HTTP Authentication With PHP

This example shows how to use HTTP Authentication with PHP, which requires you to enter user name and password for login.

To do this, simply add the following code at the top of your PHP file.

index.php
<?php

define('USERNAME', 'user');
define('PASSWORD', '123456');

// HTTP Authentication
if (!isset($_SERVER['PHP_AUTH_USER']) 
		|| !isset($_SERVER['PHP_AUTH_PW']) 
		|| ($_SERVER['PHP_AUTH_USER'] != USERNAME) 
		|| ($_SERVER['PHP_AUTH_PW'] != PASSWORD)) {
  	header('WWW-Authenticate: Basic realm="My Realm"');
  	header('HTTP/1.0 401 Unauthorized');
  	echo 'Please login.';
  	exit;
}

echo 'Hello, World!';