by Crucial:
Today I decided the code a simple login class with PHP to interact with the MySQL database.
You will need basic understanding of PHP to use this.
This is just the basics, you can add so much more to this like:
1.Change Password
2.Ban Users
3.Remember me
4.Add a registration page.
5.Add better protection(EX:IP check,Adding Salts to the passwords) 6.Additional input checks(EX:Is the user already registered?, Does the username exists that you are trying to delete?)
If you see anything wrong or want to add something please feel free to do so
Well here we go!
Login.html
PHP Code:
<html>
<head>
<title>Example of a login class</title>
</head>
<body>
<div id="main">
<h1>Enter your login info</h1>
<form action="CheckLogin.php" method="post">
<label for="username">Username: </label>
<input type="text" name="username"/><br/>
<br/>
<label for="password">Password: </label>
<input type="password" name="password"/><br/>
<br/>
<input type="submit" name="submit" value="Login"/>
</form>
</div>
</body>
</html>
LoginClass.php PHP Code:
<?php
//*************************************
// PHP Login Class Using MySQL
//*************************************
class Login {
//Username Variables
private $username;
private $password;
//MySQL Variables
private $Host;
private $MySQLUsername;
private $MySQLPassword;
private $Database;
private $Conn;
//Constructor
public function Login()
{
session_start();
$this->Host = "localhost";
$this->MySQLUsername = "root";
$this->MySQLPassword = "";
$this->Database = "testlogin";
$this->Connection();
unset($this->Host);
unset($this->MySQLUsername);
unset($this->MySQLPassword);
unset($this->Database);
}
//**********************
//Mysql Functions
//**********************
public function Connection()
{
$this->Conn = @mysql_connect($this->Host,$this->MySQLUsername,$this->MySQLPassword);
if($this->Conn)
{
mysql_select_db($this->Database) OR die('Could not select DB');
}
else
{
die(mysql_error());
}
}
public function Query($sql)
{
$result = mysql_query($sql);
if(!$result)
{
die(mysql_error());
}
return $result;
}
public function Disconnect()
{
mysql_close($this->Conn);
}
//Escapes bad values for MySQL to prevent SQL injections.
public function EscapeString($badstring)
{
if(!get_magic_quotes_gpc())
{
$goodstring = addslashes($badstring);
}
else
{
$goodstring = stripslashes($badstring);
}
$goodstring = mysql_real_escape_string($badstring);
return $goodstring;
}
public function EncryptPassword($password)
{
return sha1(md5($password));
}
//Check if the user can login
public function CheckLogin($username,$password)
{
$this->username = $this->EscapeString($username);
$this->password = $this->EscapeString($this->EncryptPassword(($password)));
$result = $this->Query("SELECT * FROM `users` WHERE `username` = '$this->username' AND `password` = '$this->password' LIMIT 1");
//If we get one result we know the login is right.
if(mysql_num_rows($result) == 1)
{
$this->username = $username;
$_SESSION['username'] = $this->username;
$_SESSION['authorized'] = 1;
header('location:Private.php');
}
else
{
die('Invalid Login');
}
}
//Add a user
public function AddUser($username,$password)
{
$username = $this->EscapeString($username);
$password = $this->EscapeString($this->EncryptPassword($password));
$result = $this->Query("INSERT INTO `users` (username,password) VALUES ('$username','$password')");
}
//Takes the result of a query and puts the information into an array
public function Result_To_Array($result)
{
$result_array = array();
for ($i=0; $row = mysql_fetch_array($result); $i++)
{
$result_array[$i] = $row;
}
return $result_array;
}
//Delete user
public function DeleteUser($username)
{
$username = $this->EscapeString($username);
$result = $this->Query("DELETE FROM `users` WHERE `username` = '$username' LIMIT 1");
}
//Checks if the user is authorized or not
public function IsAuth()
{
if(isset($_SESSION['username']) && $_SESSION['authorized'] == 1)
return true;
else
{
die('You are not authorized to view this information');
header('login.html');
}
}
//Shows user's IP
public function GetIP()
{
return $_SERVER['REMOTE_ADDR'];
}
//Display all users
public function ShowUsers()
{
$users = $this->Result_To_Array($this->Query("SELECT * FROM `users`"));
foreach($users as $user)
{
echo $user['username']."<br />";
}
}
public function LogOut()
{
session_destroy();
header('location:login.html');
}
}
?>
CheckLogin.php PHP Code:
<?php
require_once('LoginClass.php');
$Login = new Login();
if(!isset($_POST['submit']))
{
header("login.html");
}
else {
$username = $Login->EscapeString($_POST['username']);
$password = $Login->EscapeString($_POST['password']);
$Login->CheckLogin($username,$password);
}
$Login->Disconnect();
?>
Private.php
PHP Code:
<?php
require_once('LoginClass.php');
$Login = new Login();
$Login->IsAuth();
echo 'Welcome '.$_SESSION['username'].' Your IP is: '. $Login->GetIP()."<br />";
echo '<b>All Users:</b> <br />';
$Login->ShowUsers();
echo '<a href="Logout.php">Log Out?</a>';
$Login->Disconnect();
?>
Logout.php PHP Code:
<?php
require_once('LoginClass.php');
$Login = new Login();
$Login->LogOut();
?>
Here is the SQL for the table
PHP Code:
-- phpMyAdmin SQL Dump
-- version 3.2.0.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 25, 2010 at 05:21 AM
-- Server version: 5.1.36
-- PHP Version: 5.3.0
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `testlogin`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`password` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
To add a user PHP Code:
$Login->AddUser('TestAccount','SomePassword');
//And to delete a user
$Login->DeleteUser('TestAccount');
And it will encrypt the password before storing it into the database.
But like I said this is the basics and excuse the comments they aren't the best/