Thursday, July 09, 2009

Simple Registration and Login system in PHP

Steal my code!!

Need a simple registration and login system for your website?? Are you a beginner in PHP?
This might help you !
Here are just 4 steps to have a ready-to-use simple registration and login system..
Add more style and more functionality, as per your requirement ! :)

1) Create a table in your database to store the users' details using the following code.

CREATE TABLE users (
id int(10) NOT NULL auto_increment,
username varchar(40),
password varchar(50),
regdate varchar(20),
email varchar(100),
location varchar(150),
last_login varchar(20),
PRIMARY KEY(id))


2) Create a file with the following code and call it header.php
The header file selects the database and creates a connection to the database. It also has an important function, Strip, which is used several times in our code later. The Strip function checks if the magic_quotes_gpc is on or off and accordingly converts the string that is passed to it into a format that can be stored into the mysql database.
Note: If you are using PHP version 5.3 or later, please change the Strip function accordingly, as magic_quotes_gpc() is deprecated from version 5.3.

<?php

$dbhost="localhost";
$dbusername=""; //your database username here
$dbpassword=""; //your database password here
$database_name="";
//your database name here
$connection=mysql_connect("$dbhost","$dbusername","$dbpassword")
or die("Couldn't connect to server");

$db=mysql_select_db("$database_name",$connection)
or die("Couldn't select the database");

function Strip($str){
if ( get_magic_quotes_gpc() )

return mysql_real_escape_string( htmlspecialchars( trim( stripslashes($str) ) ));
else
return mysql_real_escape_string( htmlspecialchars( trim( $str ) ) );
}

?>



3) Create a file with the following code and call it register.php.
register.php creates a html form to enter users' details, validates them and stores them in the users table in the database. It throws errors if the user does not enter a valid values in the fields.


<?php
require 'header.php';
?>

<html>
<head>
<style>
body {background-color: #C0C0C0}
p {margin-left: 20px}
</style>
<title> Register an Account </title>
</head>
<body>

<?php
//function that validates the form
function validate_form(){
global $err;
$err='';

//function Strip is called to clean the user's input
$_POST['uname']= Strip($_POST['uname']);
$_POST['passwd']=Strip($_POST['passwd']);
$_POST['passwd_again']=Strip($_POST['passwd_again']);
$_POST['location']=Strip($_POST['location']);
$_POST['email']=Strip($_POST['email']);

//checking if any of the mandatory fields are empty
if(!$_POST['uname'] || !$_POST['passwd'] || !$_POST['passwd_again'] || !$_POST['email']) {
$err.='You did not fill in a required field<br/>';
}

//validating the username
$pattern="/^[a-zA-Z][a-zA-Z0-9_]{5,10}$/";
if((preg_match($pattern,$_POST['uname']))==0){
$err.='Username should be alphanumeric with a length between 6 and 16 and should start with an alphabet.</br>';
}

//checking if the username selected by the user is already in use
$qry = "SELECT username FROM users WHERE username='".$_POST['uname']."'";
$sqlmembers=mysql_query($qry);
$name_check=mysql_fetch_array($sqlmembers);
$name_checkk=mysql_num_rows($sqlmembers);
if($name_checkk!=0) {
$err.='Sorry, the username: <strong>'.$_POST['uname'].'</strong>'.' is already in use<br/>';
}

//checking if the user is already registered
$qry1 = "SELECT email FROM users WHERE email='".$_POST['email']."'";
$sqlusers=mysql_query($qry1);
$name_cheq=mysql_fetch_array($sqlusers);
$name_cheqq=mysql_num_rows($sqlusers);
if($name_cheqq!=0) {
$err.='You are already registered! The email: <strong>' .$_POST['email'].'</strong>'.' is already in use<br/>';
}

//validating the password
if(strlen($_POST['passwd'])<6 || strlen($_POST['passwd'])>16){
$err.='Your Password should be of length between 6 and 16.</br>';
}

//checking if the passwords match
if($_POST['passwd'] !=$_POST['passwd_again']) {
$err.='Passwords did not match<br/>';
}

//validating the email address
if(!preg_match("/^[a-zA-Z][\w\.\-]+[a-zA-Z0-9]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,4}$/", $_POST['email'])) {
$err.='Invalid email address<br/>';
}
}

function show_form(){ //displays the registration form
?>

<center>
<h2>Register</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table align="center" border="1" cellspacing="0" cellpadding="3">
<tr><td>Username* </td>
<td><input type="text" name="uname" value="<?php echo $_POST['uname']; ?>" maxlength="40"></td></tr>
<tr><td>Password* </td>
<td><input type="password" name="passwd" maxlength="50">
</td></tr>
<tr><td>Confirm Password* </td>
<td><input type="password" name="passwd_again" maxlength="50">
</td></tr>
<tr><td>Email* </td>
<td><input type="text" name="email" value="<?php echo $_POST['email']; ?>"maxlength="100">
</td></tr>
<tr><td>Location </td>
<td><input type="text" name="location" value="<?php echo $_POST['location']; ?>"maxlength="150">
</td></tr>
<tr><td colspan="2" aign="right">
<center><input type="submit" name="submit" value="Sign Up"></center>
</td></tr>
</table>
</form>
</center>

<?php
}

if(isset($_POST['submit'])) {
// if the user submits the form
validate_form(); //validate the form
$_POST['passwd'] = sha1($_POST['passwd']); //encrypt the password
$regdate = date('m d, Y');

if(!$err==''){
// if there were errors i.e., if the user has not submitted valid values
print "<p style=\"color : red;\">$err</p>"; show_form(); //display the errors
}
else{
//if there were no errors, insert the user details into the users table

$insert = "INSERT INTO users(username, password, regdate, email, location,last_login)
VALUES('".$_POST['uname']."',
'".$_POST['passwd']."',
'$regdate',
'".$_POST['email']."',
'".$_POST['location']."',
'Never'
)";
$sqlmembers=mysql_query($insert);
?>

<h1>Registered</h1>
//user is redirected to another page
<p>Thank you, your information has been added to the database,
you may now <a href="login.php" title="Login">log in</a>.</p>
//user is provided with a link to login
<?php

}} else { // if form hasn't been submitted, just show the registration form
show_form();
}
?>
</body>
</html>



4)Create a file with the following code and call it login.php
login.php displays the login form, allows the user to login if he enters the correct details else, throws errors.

<?php
require 'header.php';
?>

<html>
<head>
<style>
body {background-color: #C0C0C0}
p {margin-left: 20px}
</style>
<title> Login </title>
<body>

<?php

function validate_login(){
//validate the login details
global $err;
$err='';
$_POST['uname']=Strip($_POST['uname']);
$_POST['passwd']=Strip($_POST['passwd']);

if(!$_POST['uname'] | !$_POST['passwd']) {
$err.='You did not fill in a required field<br/>';
}

//check if the username entered exists in the database
$qry = "SELECT username, password FROM users WHERE username='".$_POST['uname']."'";
$sqlmembers = mysql_query($qry);
$info = mysql_fetch_array($sqlmembers);

$check = mysql_num_rows($sqlmembers);

if($check == 0) {
$err.='That account does not exist<br/>';
}

//encrypt the password the user entered
$_POST['passwd'] = sha1($_POST['passwd']);

//validate the password
if($_POST['passwd'] != $info['password']) {
$err.= 'Incorrect password, please try again<br/>';
}
}
function show_login(){
//function that displays the login form

?>
<center>
<h1>Login</h1>
<form action = "<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table align = "center" border = "1" cellspacing = "0" cellpadding = "3">
<tr><td> Username </td>
<td><input type = "text" name="uname" value="<?php echo $_SESSION['username']; ?>" maxlength="40">
</td></tr>
<tr><td>Password </td>
<td><input type="password" name = "passwd" maxlength="50">
</td></tr>
<tr><td colspan="2" align ="right">
<center><input type="submit" name="submit" value="Login"></center>
</td></tr>
</table>
</form>
</center>

<?php
}

if(isset($_POST['submit'])){
//if the user submits the form

validate_login();

if(!$err==''){
//if there were errors, display the errors
print "<p style=\"color : red;\">$err</p>"; show_login();
}
else
//if there were no errors login the user and update the last login date of the user
{
$date = date('m d, Y');
$qry = "UPDATE users SET last_login = '$date' WHERE username='".$_POST['uname']."'";
$query = mysql_query($qry);

$_SESSION['username'] = $_POST['uname'];
$_SESSION['password'] = $_POST['passwd'];

?>

<h1> Logged in </h1>
<p> Welcome back <?php echo $_SESSION['username']; ?>, you are logged in.</p>

<?php

}}else { //if form has not been submitted
show_login();
}
?>

</body>
</html>



You are done !! :)

Suggestions or comments are most welcome!

1 comment:

aDitya said...

Now...that's a good start. Why don't you consider creating custom login control with this kind of code something like the .NET custom controls...not sure if that kind of stuff exists for PHP but...
I a bit curious about your next..what will it be??