designing4u.de Yet Another Coding Blog

16May/080

User registration class – simple authorization of user

This days almost any site is providing the users a simple registration to provide certain services only for registered users. This way you can collect their e-mails and keep in touch with them. If you planing on developing a social platform or just web 2.0 project you need to authorize your users and ask them to provide a valid e-mail address. In this simple example I will show you, how you can do that using this simple class.

This example doesn't provide out of box solution for your site and you need to have at least a little bit knowledge in object oriented programming to adjust it to your needs. In this example I wont use a configuration file and the configuration will be done in constructor method, however it is highly recommended that you create this file to keep maintaining your project fast and easy.

Let's start with defining our class, some variables and the constructor.
[source:php]
class Register {

//@string name of table, where the information will be stored
private $table_name;
//@array holds user input
private $input;
//@string subject of confirmation email
private $mail_subject;
//@string body of confirmation email
private $mail_body;
//@bool html mail true/false
private $mail_html;
//@array displays error messages
public $error;

function __construct() {
$con = mysql_connect('localhost','root','pass') or die(mysql_error());
if($con) {
mysql_select_db('test',$con);
}
$this->table_name = "test_user";
$this->mail_subject = "confirmation mail";
$this->mail_body = "Here comes the text of confirmation e-mail. Click on this link %s to confirm your email.";
$this->mail_html = true;
}
}
[/source]
$this->table_name is a string property, which holds information about MySQL table, in which we will save our new registered user. $this->input is an array, in which we will save the user input. As you will see later, we do that, to make the user input safe for MySQL INSERT function. $this->mail_subject and $this->mail_body are two properties, which will be responsible for holding the information we will later send to our new user after successful registration. $this->mail_html is a boolean property, which tells our script to either send HTML or plain text e-mail after successful registration. $this->error property is an array, which we will use to display all errors to the user, which our script will generate. In our constructor method we initialize data base connection and all the properties we will later use in our class. Let's move farther to our registration method.
[source:php]
public function registerUser() {
foreach($_POST as $k=>$v) {
$this->input[$k] = mysql_real_escape_string($v);
}
//Check users input
if($this->checkInput()) {
//Check, if username exists already
if($this->checkUser('username')) {
//Check if email exists already
if($this->checkUser('email')) {
//save user in database
if($this->insertUser()) {
//send mail with confirmation link
if($this->sendMail()) {
$this->success = "Thanks for registration. Check your e-mail for further details.";
return true;
} else {
//revert changes in database
$this->deleteUser();
$this->error[] = "something went wrong, please try again later send mail";
return false;
}
} else {
$this->error[] = "something went wrong, please try again later insert user";
return false;
}
} else {
$this->error[] = "email exists";
return false;
}
} else {
$this->error[] = "username exists";
return false;
}
} else {
return false;
}
}
[/source]
We define this method as public because we will call it after our user clicks the submit button. We than loop through the $_POST variable and make the input safe against MySQL injection. First we check, if all the input is valid and meets our expectations according to password length, valid email etc. After that we provide a user check against the information saved in our database to determine, if an user with provided username or e-mail exists in our database. If it does we display corresponding error message. If our script passes this check we save new user in our database and send an e-mail with activation link. If our script return true after sending an activation e-mail we display a success message for our user with prompt to check his/hers e-mail and activate account. Simple logic, you can probably find in each user authorization. Let's take a closer look at corresponding methods, which I just mentioned:
[source:php]
private function checkInput() {
if(strlen($this->input['username']) < 5 || $this->input['username'] == '') {
$this->error[] = "username too short";
}
if(strlen($this->input['username']) > 16) {
$this->error[] = "username too long";
}
if($this->input['password'] == '' || $this->input['password1'] == '') {
$this->error[] = "you need to provide a password";
}
if($this->input['password'] != $this->input['password1']) {
$this->error[] = "password mismatch";
} else {
$this->input['password'] = md5($this->input['password']);
}
return (is_array($this->error) && !empty($this->error)) ? false : true;
}
[/source]
This method validates user input. It is just a simple example and it doesn't validate the e-mail address. You should feel free to add any other validations you can imagine to this method. In the last step we check, if provided passwords match and if they do, we encode the password with md5() function. We do that to ensure the user, that his or hers data wont be abused later, when we use it for example to save it in session variables and check against database information to authenticate the user. If $this->error is an array and it's not empty, it means user input is not valid and we return false, otherwise true.
[source:php]
private function checkUser($case='') {
switch($case) {
case 'username':
$sql = mysql_query("SELECT COUNT(*) AS exist FROM ".$this->table_name." WHERE username='".$this->input['username']."';");
break;
case 'email':
$sql = mysql_query("SELECT COUNT(*) AS exist FROM ".$this->table_name." WHERE email='".$this->input['email']."';");
break;
default:
break;
}
return (mysql_result($sql,0,'exist') > 0) ? false : true;
}
[/source]
In this method we check, if username or password exists in database. If it does we return false, otherwise true. At this point I should probably mention that AJAX gives you possibility to perform this validation on client side. Server side validation is just another check to ensure that provided data is really that, what we expect to save in our database. If you want to use this class in your AJAX request to perform checks on user input, you would have to change most of the methods to public and probably write another method which will set user input you will later use to perform those checks.
[source:php]
private function insertUser() {
$sql = mysql_query("INSERT INTO ".$this->table_name." (id, username, password, email, confirmed) VALUES (NULL,'".$this->input['username']."','".$this->input['password']."','".$this->input['email']."','0');") or die(mysql_error());
return ($sql) ? true : false;
}

private function deleteUser() {
$sql = mysql_query("DELETE FROM ".$this->table_name." WHERE username='".$this->input['username']."' AND email='".$this->input['email']."';");
}
[/source]
InsertUser and deleteUser are just simple methods to either save of delete a user from the database.
[source:php]
private function sendMail() {
if($this->email_html) {
$header = 'MIME-Version: 1.0' . "\r\n";
$header.= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$header.= 'From: "yourmail@domain.com"' . "\r\n";
} else {
$header = 'From:yourmail@domain.com';
}

$body = sprintf($this->mail_body,"www.yourdomain.com?activation=youractivationcode");

return (@mail($this->input['email'], $this->mail_subject, $body, $header)) ? true : false;
}
[/source]
The last method replaces %s with the confirmation link, sends a confirmation mail and returns true on success and false in case of any errors. That's all. As I already mentioned this class doesn't provide a ready solution for your internet site and it should be adjusted to your needs. It's just a schema you can always start with, when you writing applications, which provide user registration. At the end lets take a closer look, how you should use this class.
[source:php]
if(isset($_POST['submit']) && $_POST['submit'] == 'register') {
include('register.class.php');
$register = new Register;
if($register->registerUser()) {
echo (isset($register->success)) ? $register->success : '';
} else {
foreach($register->error as $error) {
echo $error."
";
}
include('form.php');
}
} else {
include('form.php');
}
[/source]
We include and instantiate our class only in case, when our clicks a submit button. We then call the registerUser method and display success or error message depending on the case. You might also provide a redirection after successful registration to prevent the users from reloading the page. However our class would retrieve an error message saying that username already exists, it is just a nice way to do the things. And here the code of form.php in case you need it:
[source:html]




[/source]
And the table structure:
[source:sql]
CREATE TABLE IF NOT EXISTS `test_user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) collate latin1_general_ci NOT NULL,
`password` varchar(32) collate latin1_general_ci NOT NULL,
`email` varchar(255) collate latin1_general_ci NOT NULL,
`confirmed` enum('0','1') collate latin1_general_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
)
[/source]
I'm waiting for your comments about this one. Cheers.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.