Unauthorized access to a PHP page prompts the user for a password. Once the password is entered the original page will show.
- The access is recorded in the session so it only needs to be entered once.
- It is possible for multiple pages to share the same scope so access to one page grants access to another page.
Add to the top of the page you want to protect:
require_once 'protect.php';
Protect\with('form.php', 'my_password');
Now we need to provide a page to prompt the user for the password. It can look like anything you want. The only two requirements are:
- It must POST the form (i.e.
action="POST"
) - The password field must be named
password
The following is an example form:
<html>
<body>
<form method="POST">
<?php if( $_SERVER['REQUEST_METHOD'] == 'POST' ) { ?>
Invalid password
<?php } ?>
<p>Enter password for access:</p>
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
</body>
</html>
Place this in the form.php
file (or whatever the first argument to
the with
method is).
If you need to secure multiple pages and want access on one page to
grant access on all pages simply provide a third argument to with
.
The value of this argument can be anything you desire. It just needs
to be the same for all pages. You probably also want to make the form
and password the same for all pages.
You should not modify the protect.php file at all. You should just copy it in your project and leave it as is. Then, on the page you want to protect with this code, you add the two lines I provided above. As indicated by both the comments, the name of the parameter and the example string I used, you should enter the hashed password (NOT the password in clear) in the with function.
This means that the two lines might look like that :
And this is all you have to do. The protect.php file recieves the hashed password through the second argument of the with function, and this is all it needs to check against the one entered by the user in the form.