All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Simple HTTP Authentication Using PHP To Make Your Site More Secure

Last Updated : Jul 1, 2023

IN - PHP HTML | Written & Updated By - Ashish

In this tutorial we will create simple HTTP Authentication using PHP to make your webpages more secure, HTTP Authentication is used to provide login or authenticate users to some webpages whenever user visits on that webpage.It acts like a login system but its easy to create.

You may also like protect webpage with password using PHP.

Simple HTTP Authentication Using PHP To Make Your Site More Secure

To Create HTTP Authentication Using PHP It Takes Only one Step:-

  1. Make a PHP file and define markup,scripting

Step 1. Make a PHP file and define markup,scripting

We make a PHP file and save it with a name authenticate.php

<?php
$authenticate = false;
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
{
 $name = $_SERVER['PHP_AUTH_USER'];
 $pass = $_SERVER['PHP_AUTH_PW'];
 if ($name == 'user' && $pass == 'pass')
 {
  $authenticate = true;
 }
}
 
if ($authenticate==false)
{
 header('WWW-Authenticate: Basic realm="Restricted Page Enter Details To Continue"');
 header('HTTP/1.0 401 Unauthorized');
 echo "Authentication Failed Refresh To Do It Again";
} 

else
{
 ?>
 <html>
 <body>
 <h1>Simple HTTP Authentication Using PHP To Make Your Site More Secure</h1>
 <p>All Your Content Comes Here</p>
 </body>
 </html>
 <?php
}
?>

In this step we first create a variable 'authenticate' and set it to false it means the user is not authenticate himself.

Then we check if user submitted the authenticate form and if yes then check the submitted name and password matched to our name and pass if all matched then we set 'authenticate' variable to true it means the user authenticate himself and allow him to access the webpage then we show our webpage.

You may also like login form with limited login attempts using JavaScript.

In second if condition we check 'authenticate' variable if it is set to false it means the user is not authenticate himself so show him the authenticate login box to access the webpage.

In this if condition we add the necessary header which is required to create a simple HTTP Authentication and under first header there is 'Basic realm' you can add any message under this to show to the user at the time of authentication.

And if user cancels the authentication we print the message to refresh the page and do it again.

Thats all, this is how to create Simple HTTP Authentication using PHP to make your website more secure. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

I hope this tutorial on http authentication in php helps you and the steps and method mentioned above are easy to follow and implement.