Have you ever wanted to make a login script so you can have membercontent?
This tutorial will show you how using php. No database will be used.
1) Creating a form
Here is the code for making the form. The form asks for your username and password. Save this code as login.php
echo("<b>Username or password is incorrect!<br />Please try again.</b>");
<form action="login2.php" method="post">
<input type="text" name="username" /><br />
<input type="password" name="password" />
<input type="submit" value="Login" />
The piece of php code will tell the viewer that he or she typed a wrong username or password.
between the <form></form> tags we have 3 input fields. 1 for the username, 1 for the password, and 1 that will submit the inputs and send it to login2.php.
Note that the form will be sent using the "post" method. This is the safest.
2)Checking the userinput
In this step we will check if the username and password are correct.
This is done with php. No html will be used.
Create a new page and call it login2.php. Give it the following content:
$usernames = array("user1", "user2", "user3", "superman");
$passwords = array("pass1", "pass2", "password3", "supermans password");
$page = "mypage.php";
You might want to edit the first 3 lines.
$usernames is an array with all the usernames. To add a new one:
$usernames = array("user1", "user2", "user3", "superman", "new one");
$passwords is an array with all the passwords. To add a new one:
$passwords = array("pass1", "pass2", "password3", "supermans password", "new one");
Make sure that the username and the password have the same position.
will be able to login with the password pass1
, not with any other password. user2
and no other.
$page is the page the user will go to when he is logged in. Change mypage.php to the page you would like to be the main page for logged in users. make sure the quotationmarks are still around it!
3) Checking if the user is still logged in
Create a new page, call it login3.php with the following code:
This code simply checks if the sesion that we made in login2.php has a value.
If it doesn't it sends you to the login page.
4) Making your pages protected
All the pages that you want to be protected need to have a .php extension! otherwise they cannot be protected. Add this piece of code to the first line.
<?php require("login3.php"); ?>
Make sure it is on the first line. Otherwise it will give you an error.
Now you pages are protected! simple?
making a log out page:
make a new .php page and add the following contents at the very beginning:
<?php session_start();session_unset();session_destroy(); ?>
Your fancy logout message here
create a link somewhere on your secured pages that leads to the logout page and the user will be logged out when he clicks the link.
An other extra: showing the user's name: just put this piece of code in any secured page where you want to show the name:
<?php echo($_SESSION["username"]); ?>