I have a page I want to password-protect. I've tried doing HTTP authentication, but for some reason it doesn't work on my hosting. Any other quick (and easy) way to do this? Thanks!

share|improve this question
4  
Define "doesn't work". – Oliver Charlesworth Nov 6 '10 at 23:32
    
This depends on a lot of things. Is it just one page? Do you need a visitor to stay validated even if they refresh the page? Are you willing to use sessions? – William Linton Nov 6 '10 at 23:33
    
It's just one page, they don't need to stay validated. I'd prefer not to use sessions, unless there's a really simple way to do it without forms and such. – Leticia Meyer Nov 6 '10 at 23:35

10 Answers 10

Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.

Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.

They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.

If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.

<?php
$user = $_POST['user'];
$pass = $_POST['pass'];

if($user == "admin"
&& $pass == "admin")
{
        include("secure.html");
}
else
{
    if(isset($_POST))
    {?>

            <form method="POST" action="secure.php">
            User <input type="text" name="user"></input><br/>
            Pass <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Go"></input>
            </form>
    <?}
}
?>
share|improve this answer
1  
A simple way to make this more secure: instead of storing the password, store the md5 hash. When they try to log in, check md5($pass) against the hash. Even better, store the md5 hash in a file outside the public web root. – William Linton Nov 7 '10 at 2:51
2  
You're right about storing the protected page outside the document root, because in your code, anyone could visit secure.html and bypass the PHP script (unless you're using .htaccess files or something). – William Linton Nov 7 '10 at 3:10
2  
Like willell mentioned, and I'll say again, don't treat this as a secure password script by any means. Just something I typed up in a minute or two that looked like it might fit the bill to very simply require a pass before seeing a page. – JacobN Nov 7 '10 at 6:08
    
@willell md5 is considered unsecure nowadays. – Ingo Bürk Apr 26 '14 at 15:43
    
You can increase the security by adding something like $a = 1 to your login page and then if ($a != 1){ exit(); } to your secure page that you are loading in. This should prevent access that has not gone through the login page. – Ned Hulton Feb 25 at 0:39
<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";

if (isset($_COOKIE['PrivatePageLogin'])) {
   if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>

    <!-- LOGGED IN CONTENT HERE -->

<?php
      exit;
   } else {
      echo "Bad Cookie.";
      exit;
   }
}

if (isset($_GET['p']) && $_GET['p'] == "login") {
   if ($_POST['user'] != $username) {
      echo "Sorry, that username does not match.";
      exit;
   } else if ($_POST['keypass'] != $password) {
      echo "Sorry, that password does not match.";
      exit;
   } else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
      setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
      header("Location: $_SERVER[PHP_SELF]");
   } else {
      echo "Sorry, you could not be logged in at this time.";
   }
}
?>

And the login form on the page...
(On the same page, right below the above^ posted code)

<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>
share|improve this answer
3  
Using md5 to hash passwords is a bad idea. Consider using crypt or password_hash (in PHP >= 5.5.0) or password_compat (in PHP >= 5.3.7) instead. – Sherif Feb 24 '14 at 22:46

This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.

First prepare your password salts file:

hash_generate.php:

 <?php

 $user = "Username"; // please replace with your user
 $pass = "Password"; // please replace with your passwd
 // two ; was missing

 $useroptions = ['cost' => 8,];
 $userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions);
 $pwoptions   = ['cost' => 8,];
 $passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);

 echo $userhash;
 echo "<br />";
 echo $passhash;

 ?>

Take your output $userhash and $passhash and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"

.htaccess

 deny from all

now no one can peek into the hash. Next up is your index.php:

index.php:

<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
    $user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
    $pass = $_POST['pass'];
}    

$useroptions = ['cost' => 8,]; // all up to you
$pwoptions   = ['cost' => 8,]; // all up to you
$userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);  // hash entered pw
$hasheduser  = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass  = file_get_contents("stuff/pass.txt"); // and our stored password


if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {

    // the password verify is how we actually login here
    // the $userhash and $passhash are the hashed user-entered credentials
    // password verify now compares our stored user and pw with entered user and pw

    include "pass-protected.php";

} else { 
    // if it was invalid it'll just display the form, if there was never a $_POST
    // then it'll also display the form. that's why I set $user to "" instead of a $_POST
    // this is the right place for comments, not inside html
    ?>  
    <form method="POST" action="index.php">
    User <input type="text" name="user"></input><br/>
    Pass <input type="password" name="pass"></input><br/>
    <input type="submit" name="submit" value="Go"></input>
    </form>
    <?php 
} 
share|improve this answer
Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.

If you want you can also make it so only certain ip addresses can login.. :) really easy with lighttpd

Update: I will post some examples soon, so don't vote down for no examples, i just need to get some down for this answer.

If you want to use sessions the following is the best way to go:

# admin.php
session_start();
if(!$_SESSION["AUTH"])
    require_once "login.php";
# Do stuff, we are logged in..

# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
    $_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.

if($_SESSION["AUTH"])
    require_once "admin.php";

This method does not contain the examples for above but you seamed interested in this method. The other method examples are still to come, I have not got enough time to get it for apache or lighttpd settings and the php header auth: http://php.net/manual/en/features.http-auth.php Will do.

share|improve this answer

I would simply look for a $_GET variable and redirect the user if it's not correct.

<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
  header('Location: http://www.staggeringbeauty.com/');
}
?>

Now, if this page is located at say: http://example.com/secrets/files.php

You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)

share|improve this answer
</html>
<head>
  <title>Nick Benvenuti</title>
  <link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
  <link rel="stylesheet" href="CSS/main.css">
  <link rel="stylesheet" href="CSS/normalize.css">
  <script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
  <script type="text/javascript">
  function tester() {
  window.location.href="admin.php";
  }
  function phpshower() {
  document.getElementById("phplogger").classList.toggle('shower');
  document.getElementById("phplogger").classList.remove('hider');
  }
  function phphider() {
  document.getElementById("phplogger").classList.toggle('hider');
  document.getElementById("phplogger").classList.remove('shower');
  }
</script>
<?php 
//if "login" variable is filled out, send email
  if (isset($_REQUEST['login']))  {

  //Login info
  $passbox = $_REQUEST['login'];
  $password = 'blahblahyoudontneedtoknowmypassword';

  //Login
  if($passbox == $password) {

  //Login response
  echo "<script text/javascript> phphider(); </script>";
  }
 }
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
 <form method="post">
  Password: <input name="login" type="text" /><br />
  <input type="submit" value="Login" id="submit-button" />
  </form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>

Basically what I did here is make a page all in one php file where when you enter the password if its right it will hide the password screen and bring the stuff that protected forward. and then heres the css which is a crucial part because it makes the classes that hide and show the different parts of the page.

  /*PHP CONTENT STARTS HERE*/
  .hider {
  visibility:hidden;
  display:none;
  }

  .shower {
  visibility:visible;
  }

  #phplogger {
  background-color:#333;
  color:blue;
  position:absolute;
  height:100%;
  width:100%;
  margin:0;
  top:0;
  bottom:0;
  }
  /*PHP CONTENT ENDS HERE*/
share|improve this answer

Not the solution, but for your interest: HTTP authentication only works, when PHP runs as Apache module. Most hosters provide PHP as CGI version only.

share|improve this answer

This helped me a lot and save me much time, its easy to use, and work well, i've even take the risque of change it and it still works.

Fairly good if you dont want to lost to much time on doing it :)

http://www.zubrag.com/scripts/password-protect.php

share|improve this answer
1  
I think you meant this: zubrag.com/scripts/password-protect.php instead – Ian M May 18 '15 at 8:03
    
Edited ! (Ok its been a while but still I've done it :D ) – Baldráni Jul 8 '15 at 12:17

You could use a simple if with a form:

if(!(isset($_POST['password'])&&$_POST['password']=="my_pass")){
    echo $login_form;
    die();
}

But there are a lot of this kind of scripts online: https://www.codester.com/items/705/php-easy-lock-password-protect-php-script

share|improve this answer

You can use this: http://ps.lixter.com/loginexample.php

<?php
$u=$_GET['usn'];
$p=$_GET['psw'];
$correct=array(
    array("admin","password"), //the combine of username and password
    array("usn1","12345"),
    array("usn2","let-me-in"),
    array("abc","pass9210"),
    array("20141218","today")
);
for ($x = 0; $x < 5; $x++) { //edit the number of pairs combination
    if ($u == $correct[$x][0] && $p == $correct[$x][1]) {
        $sta = "you have login successfully! <br>some secret document. some secret document. some secret document.";
        break;
    } else {
        $sta = "you'll have to try another one";
    }
}

echo "The username is '<b><u>" . $u . "</u></b>' and the password is '<b><u>" . $p . "</u></b>', so " . $sta . "!!";
?>
<p>
How to get in:
add the following things to the url bar:
?usn=admin&psw=password
or those:
?usn=usn1&psw=12345
?usn=usn2&psw=let-me-in
?usn=abc&psw=pass9210
?usn=20141218&psw=today
</p>
share|improve this answer
3  
It's not a very clever idea to put a plaintext password as GET parameter in a url. These urls will get logged in browser histories, router logs, open wifi networks and so on... so really anyone may get hands on the user/pass combo without special knowledge or hacking skills. – auco Jan 19 '15 at 15:27
1  
Link at the top of with answer is virus spam! – StephanieQ Jul 17 '16 at 21:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.