HomePHP Page 2 - Private Pages with PHP and Text Files
Creating the main PHP page - 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.
Next, you need to create the main PHP page that will do the real work. With a blank page in a text editor, open a PHP block in the standard way:
<?
As I mentioned before, PHP has a standard set of functions and methods used for working with files. The main ones that we will need are the fopen(), fread() and fclose() functions. To do anything with a file, we need to open it, and clearly, this is done using the fopen() function. We need to specify what we intend to do the file; read it, read and write to it are the most common tasks, but additional flags can be used to tell the program whether to place the file pointer at the beginning or end of the file and whether to create the file if it does not already exist. All we are going to need to do for this example, however, is open the text file containing the password for reading.
First then, create a variable that specifies the path to the text file:
$fileloc = "/apachesite/docs/pass.txt"
Next, create a variable to hold the file pointer:
$filetoread = fopen($fileloc, "r") or die("Could not open password file");
You can also use the die method to end the script and print an appropriate message on screen if the operation fails for some reason. Once the file has been opened, you’ll need to read the contents of it so that it can be compared to the input from the password form:
$storedpass = fread($filetoread, filesize($fileloc)) or die ("Could not read stored password");
You set a variable to hold the data from the file and call the fread() method which takes two parameters: the file pointer and the length of the file. You may or may not know the length of your password. For future programming ease (when the password needs to be changed) you can use the filesize() method to just grab it all. As soon the file is no longer needed, it should be closed: