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.
@alexnathanson - With regard to redirect vs return, either could work and using return would obviously simplify the code as you then don't need the
redirect
andcurrent_url
methods. But when the page is rendered it is in response to a POST request which can cause user confusion if they hit the refresh for example as it will ask them if they want to re-submit the form. By doing a redirect we turn it back into a GET request as they originally requested which results in a slightly cleaner experience for the user. Yes, you could put the form inline vs as a separate file. I just try to separate code logic from markup so having them as separate files makes it a bit cleaner as the form can then be designed and styled separate from the authentication logic.@Baljeet21 - To logout you would need to delete the session variable. Some sort of button to signal to the script to do this delete.