2019-01-06 Pujan Niroula 1 Minute(s) Read

Create Simple HTTP Authentication in PHP

img-simple http authentication php.jpg

Normally, we use login system to secure our information on our webpage.  If we have to create simple and secure login system then it will takes little time and some pre-planing.

If you just want to authenticate for a single page then login system is bit lengthy and complex. If you just want to authenticate for just a page then HTTP Authentication is Perfect solution.

It will show a little popup asking for username and password when you visit page like following.


Let's get started...

$usr = 'admin';
$pwd = 'demo@111';
$login = false;
$login_error = 'Unauthorized access!!!';
$login_success = 'Welcome, You got access!!!';

First of all I set username, password, default login status, login error message and login success message.

if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Protected Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo $login_error;
    exit;
} else {
    if ($_SERVER['PHP_AUTH_USER']==$usr && $_SERVER['PHP_AUTH_PW']==$pwd) {
        $login = true;
    }
}

After that I checked the box is submitted or not if it is not submitted it will show box. If popup is submitted then It will check the submitted username and password is matched to $usr and $pwd variable. If it's matched it will change default login status to true.

if(!$login) {
    echo $login_error;
    exit();
} else {
    /**Place your contents here*/
    echo $login_success;
};

Finally, It will check the variable named $login is true or false. If it's false it will print error else it will print success.

You can place your protected contents on that last.
Let's wrap all of codes

Code: HTTP Authentication with PHP

<?php
$usr = 'admin';
$pwd = 'demo@111';
$login = false;
$login_error = 'Unauthorized access!!!';
$login_success = 'Welcome, You got access!!!';
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Protected Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo $login_error;
    exit();
} else {
    if ($_SERVER['PHP_AUTH_USER']==$usr && $_SERVER['PHP_AUTH_PW']==$pwd) {
        $login = true;
    }
}
if(!$login) {
    echo $login_error;
    exit();
} else {
    /**Your Protected content goes here*/
    echo $login_success;
};
?>

 

Comments (1) Add New Comment
Tutoring online2024-02-24 6:03 PM

each time i used to read smaller content which also clear their motive, and that is also happening with this post which I am reading here.

Reply