Basic Auth by PHP
- 2021年5月10日
- 技術情報
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
yuuma at 2021年05月10日 11:00:09