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.
Hi there. Thanks for this great code. How could I create a button to end the session in order to close access to the protected page ? Thanks.