PHP Tutorial: Developing a Login – Part 1 - Validation




Server side validation

Before comparing any user input to the database, we need to make sure that it confirms to the desire format.

Within the authentication class:

Create two private methods

  • valid_email($email)
  • valid_password($password)

In the valid_email method we validate the username:
  • Check if the user entered anything (Required field)
  • Check if the field is a valid email address using a regular expression.

 
private function valid_email($email)
{
	if (empty($email)) {
		$this->errors.= COMPLETE_EMAIL.'<br/>';
	}
	else if (preg_match('/\w+([-+.\']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/', $email) == 0) {
		$this->errors.= INVALID_EMAIL.'<br/>';
	}
}
 

In the valid_password method we validate the password the user entered:
  • Check if the user entered anything (Required field)
 
private function valid_password($password)
{
	if (empty($password)) {
		$this->errors.= COMPLETE_PASSWORD.'<br/>';
	}
}
 

Create a login method:
  • Call the valid_email method to validate the username
  • Call the valid_password method to validate the password
  • If the preceding conditions were met, compare the validated input to the database with the method coming from which is essentially our data layer – which we passed via the constructor previously.
  • If rows were returned, assign the returned row to the session else notify that the username and password are invalid.
 
public function login($email, $password)
{		
	$this->valid_email($email);
	$this->valid_password($password);
 
	if (empty($this->errors))
	{
		try
		{
			$details = $this->datasource->valid($email, $password);
 
			if (isset($details))
			{
				$_SESSION[$this->session] = $details;
				$this->redirect();
			}
			else {
				$this->errors = INVALID_USER_PASS;
			}
		}
		catch(Exception $ex)
		{
			$this->errors = $ex->getMessage();
		}
	}
}
 



1 2


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

Javascript Reference: Dropdown


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

PHP: Snippets


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

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