Basic Auth by PHP

There are several ways to add a basic authentication using php. Today I would like to share a snippet to add basic authentication easily.

Lets get started.

<?php

//you can define your custom username and password here.
$AUTH_USER = 'username';
$AUTH_PASS = 'password';

header('Cache-Control: no-cache, must-revalidate, max-age=0');
$credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));

//check credentials existence or wrong credentials
$auth_fail = (
	!$credentials ||
	$_SERVER['PHP_AUTH_USER'] != $AUTH_USER ||
	$_SERVER['PHP_AUTH_PW']   != $AUTH_PASS
);

//Ask for the auth. If credentials are not correct, deny the access.
if ($auth_fail) {
	header('HTTP/1.1 401 Authorization Required');
	header('WWW-Authenticate: Basic realm="Access denied"');
	exit;
}

After the coding process, you will get a confirmation alert box for authentication before accessing the website as below.

Well, I think you can now add basic auth in any of your PHP application neat and easily.

If you want to add basic authentication for contents like html and images etc , you can also do that by configuring .htaccess

Yuuma



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム