Your First Script: A Password Protected Site
Saturday, April 12th, 2008This is how I started learning PHP - writing a password protected site. This isn’t nearly as handy and advanced as your ordinary password protection, but it’s still cool, cooler than “Hello World“-programs anyways.
The first thing we do is to make a login-form in plain HTML, something like the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Sample login</title> </head> <body> <form action="passwordprotected.php" method="post"> <div> <strong>Username:</strong> <input type="text" name="username"><br> <strong>Password:</strong> <input type="password" name="password"><br> <input type="submit" value="Log in"> </div> </form> </body> </html>
Now, on this page there are several important things we have to know for our PHP-script. The first thing is the url/name of the PHP-file, in this case passwordprotected.php as seen in the <form>-tag. Remember, when you only write the filename of the PHP-file (as I have done) as the “action”, it has to be in the same directory as the html-page, the same goes for links etc.
The <form>-tag also holds another piece of valuable information, the method to send the data. There are two main methods that you will be using, post and get. The only real difference between those two is how you access the data in you PHP-script. Also, get will produce ugly addresses, while post won’t. There is a common misconception that post is more safe than get, but that is not true.
The last two things you have to know are the names of the username- and password-fields, if you look at the <input>-tags, you’ll see that the names are username and password.
Now you know all you need to know from the form, time to code some PHP at the next page.