The Tricky.net

PHP
Log in with PHP

Sometimes you may want to protect part of your website from unwanted visitors, for example, the page which allows you to change the settings of your website. This is possible in PHP. First of all, you have to organize your website and decide which parts you want to protect and which parts you want to keep open. Once you've decided which pages you want to protect, use this tutorial!!

Start by making a login form on a public page, where you will be able to enter your login data. This code can be included anywhere on the page.

 
<form method='post' action='login.php'>
 <table><tr><td>Username:</td><td><input type='text' name='username'></td></tr>
 <tr><td>Password:</td><td><input type='password' name='password'></td></tr>
 <tr><td></td><td><input type='submit' name='submit' value='Log in'></td></tr></table>
</form>
 

At the beginning, you specify the transfer method, in this case POST. The action attribute specifies which page the user will be sent to when he clicks the submit button. Then there's a table in which there are two input boxes and a submit button, one box for the username and the other one for the password.

Now we want to make a page (login.php) which checks if the user has put in a valid username-password combination and logs in the user. First you have to set the variable which checks if the user can log in to false to avoid some security problems:
 
$logIn = false
 

Then you have to check the user has the right to log in. In this tutorial I will use mysql data for the login credentials, but you can use any function you want in PHP. Just skip this part and set the variable we just made to true when the user can log in. First you have to connect to the mysql database:
 
//variables
$dbhost = 'localhost';
$dbuser = 'root';
$dbpassword = 'password';
 
//do the connection
$conn = mysql_connect($dbhost, $dbuser, $dbpassword) or die ('Error connecting to mysql');
 
//open a specific database
$dbname = 'myDatabase';
mysql_select_db($dbname, $conn);
 

Now we're connected, we want to test the user input. But don't forget the input has to be checked before putting it in the query, as some people find it funny to hack into your site.
 
//First check the user input
if(get_magic_quotes_gpc()) {
 $username = stripslashes($_POST['username']);
 $password = stripslashes($_POST['password']);
} else {
 $username = $_POST['username'];
 $password = $_POST['password'];
}
$username = mysql_escape_string($_POST['username'], $conn);
$password = mysql_escape_string($_POST['password'], $conn);
//Then make the query and execute it
$query = "SELECT * FROM LOGINTABLE WHERE Username = '".$username."' and Password = '".$password."'";
$query_result = mysql_query($query);
//If there is one result the user can be logged in
if (mysql_num_rows($query_result)==1){
 $logIn = true;
}else{
 $logIn = false;
}
//And close the mysql connection
mysql_close($conn);
 

Remark: NEVER put the passwords of your users as clear-text in the database. This tutorial is to help you unerstand the basics of a login script, and shouldn't directly be used in a security-sensitive (non-local) context. See http://phpsec.org/articles/2005/password-hashing.html for more information.

The user input has been checked and the $logIn boolean has been set to the correct value. The user can now be logged in or sent back to the homepage of your site:

 
//If the user can log in
if($logIn){
 //Start the session and set the OK var to true
 session_start();
 $_SESSION["OK"] = true;
 
 //And send the user to the private part of your website
 header("Location: loggedIn.php");
}else{
 //If the user isn't logged in, send him back to the homepage
 header("Location: index.php");
}
die;
 

The user has been logged in and sent to the page which is reserved for the users who have logged in. But someone could try to access the page directly by accessing the page directly from his web browser. To prevent this, we have to check if the user has been logged in at each page request by including a file which checks if the Session variable has been set (check.php):

 
//Start the session if it hasn't been started yet
if(!defined("SESSIONSTARTED")){
 session_start();
}
//Check if the user has been logged in
if(!isset($_SESSION["OK"]) || $_SESSION["OK"] == false){
 //If he hasn't, send him back to the homepage
 echo "<meta http-equiv='refresh' content='3;URL=index.php'/>Please log in";
 die;
}
//Tell your program the session has been started. This will prevent some useless error messages
define("SESSIONSTARTED", 1);

Now we have a file we can include (actually require) at the beginning of each file where the user has to be logged in by using the following code:

 
require("check.php");
 
//Insert the rest of your code here
 

Congratulations! You now have a way to protect some of your pages. But there is still one more problem, the user needs to be able to log out. This is quite useful if you want to log in in a webcafe and you don't want the next person to access the site with your login data. We need one more page (logout.php) which logs out the user.

 
//First check if the user is logged in, this again prevents some error messages
include("check.php");
 
//Delete the session variables
unset($_SESSION["OK"]);
session_unset();
 
//And send the user back to the homepage
echo "<meta http-equiv='refresh' content='3;URL=index.php'/>You have been logged out";
 

You now have a fully working login system. You can download all files here.

 
<< Start < Prev 1 2 3 4 5 6 7 Next > End >>

Page 2 of 7