HomePHP Page 3 - Private Pages with PHP and Text Files
Using the Password - PHP
You run a website that is simple enough it doesn't require a database. But your site features certain pages to which you'd like to limit access. Most of the time, that implies using a database to store passwords and usernames. There is an easier way, however. It's less secure, but it involves a lot less coding.
To use the password entered into the html form, you need to obtain it and store it in a variable. As we used the POST method to send the user input to the PHP script, we can use $_POST to get the entered password:
$password = $_POST["password"];
We can then simply compare the entered password with the stored password and act accordingly:
if (empty ($password)) { die ("No password entered"); } elseif ($password != $storedpass) { die ("Password Incorrect"); } else { Header("Location: securepage.htm") } ?>
The first if statement handles an empty $password variable in case the submit button is clicked when the input box is empty. The second statement executes the code within brackets if the password the user enters does not match the one that is stored, and outputs a message indicating that the password is wrong. Finally, if either of the first two conditions are not met, the script concludes that the password must be correct and sends a redirect header to the browser telling it to open the secure HTML page.
Before this will work, you’ll need to create a text file and place it in the same directory as the PHP file. It will need to contain the password you intend to use in plain text for now, and should have the filename referenced in the PHP file. Save all of the files, open the HTML page in a browser and experiment with the form. The page should work as intended.
When you enter the correct password, if you get an error message saying:
“Warning: Cannot modify header information – headers already sent by (thepathtoyourphpfile)”
it means that you need to switch output-buffering to “on” in the php.ini file that is found in your Windows directory.