PHP Tutorial: Developing a Login – Part 1 - Data structure




First of all, I am going to create a very simple table using mysql, the user’s email address will function as his/her username.

 
CREATE TABLE users (
  userID int(11) NOT NULL AUTO_INCREMENT,
  email varchar(255) NOT NULL,
  pass char(32) NOT NULL,
  PRIMARY KEY (userID),
  UNIQUE KEY email (email)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;
 

We won’t be discussing user registration/creation in this part, so we’ll just insert a default user into the table and apply some MD5 hashing to the password.

 
INSERT INTO users(email, pass)
VALUES('admin@yourdomain.com', MD5('123456'))
 

Next I define a very basic interface, which will function as a type of contract that our data class must adhere to in order to interface with our eventual login class. (Useful for integration with existing systems etc)

 
interface Iuser
{
 	public function valid($email, $password);
}
 

In the following crude class we
  • implement the interface
  • escape the input values in order to prevent injection attacks
  • return an array containing the results of the query


 
class user implements Iuser
{
	private function connect()
	{
		$mysqli = @new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
		if (mysqli_connect_errno())	{
			throw new Exception(mysqli_connect_error());
		}
		return $mysqli;
	}	
	public function valid($email, $password)
	{
		$db = $this->connect();	
		$email = $db->real_escape_string($email);
		$password = $db->real_escape_string($password);
		$result = $db->query("SELECT userID, email											FROM users
					WHERE email = lower('$email')
					AND pass = md5('$password')");	
		$row = $result->fetch_assoc();
		$result->close();
		$db->close();
		return $row;
	}
}
 

Looking at the constructor of the class responsible for authentication, notice that we are making use of type hinting, this will restrict the developer to only assign classes that adheres to our contract defined via the Iuser interface.

 
class Authenticate
{
	public function __construct(Iuser $datasource)
	{
		$this->datasource = $datasource;
	}




No Entries Found

Post comment

Name *
Email
Title
Body *
Security code
*
* Required fields

Latest Articles

Top 5 Articles

Programming humor


Collection of funny programming articles
2006-10-08 14:23:43

How to create your own RSS Reader


It is very simple creating your own rss reader, the following article looks at a few methods of doing this.
2008-06-23 13:18:25

PHP: Snippets


Collection of PHP snippets
2010-05-22 00:06:45

Javascript Reference: Dropdown


A quick reference about working with dropdown boxes (select element) in javascript.
2007-02-17 16:36:41

Event driven programming in PHP


An article looking at adding some kind of event driven model to PHP 5
2008-07-28 12:48:09