PHP best & secure user registration with login example

This example is explaining how to create secure user registration using php and mysql.This is very secure using salt value into database users table.It help to avoid sql injection and dictionary attack from hackers. This way is secure and better than md5 encryption method.
Here tested code.
This is have two parts.
1-User Registration
2-User Login
sql-injection

1-User Registration

From here everything is explained very simply to understand all visitors.
Here is the registration form.

User Name:
Password:
Email Address:

To more simple I’ll show the table structure.
secure user login table
Users Table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userEmail` varchar(255) NOT NULL,
  `userName` varchar(255) NOT NULL,
  `userPassword` varchar(255) NOT NULL,
  `enable` int(11) NOT NULL DEFAULT '1',
  `regDateTime` datetime NOT NULL,
  `salt` varchar(255) NOT NULL,
  PRIMARY KEY (`id`,`userEmail`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Here is the php script to process the form.This can put in the same registration.php file.
I have not added database connection details here.Hope you can create that.If you don’t know that let me know.I’ll add.

/***
	 check given username is already registred or not whether.
	 if already registered return 0
	 if given username is not registered return 1
***/
function checkuseremail($useremail) {
 	$SQL="SELECT id FROM users WHERE userEmail = '$useremail'";
	$result = mysql_query($SQL) or die(mysql_error());
	$rows = mysql_num_rows($result);
	if($rows <= 0) {
		return 0; // not registered
	} else {
		return 1; // already using given username
	}
}
/***
	 check given email address is already registred or not whether.
	 if already registered return 0
	 if given email address is not registered return 1
***/
function checkusername($username) {
	$SQL="SELECT id FROM users WHERE userName = '$username'";
	$result = mysql_query($SQL) or die(mysql_error());
	$rows = mysql_num_rows($result);
	if($rows <= 0) {
		return 0; // not registered
	} else {
		return 1;// already using given email address
	}
}
// create random salt with 5 character length and return it.
function createSalt() {
    $string = md5(uniqid(rand(), true));
    return substr($string, 0, 5);
}
if( isset($_POST['userSubmit']) && ($_POST['userSubmit']=='Registration') )  {
		//get user entered details
		 $username 		= mysql_real_escape_string(trim($_POST['userName']));
		 $userpassword  = mysql_real_escape_string(trim($_POST['userPassword']));
		 $useremail 	= mysql_real_escape_string(trim($_POST['userEmail']));
	 $errors = 0; // define variable to assign value if have errors
     // check username is already using or not
 	 $checkUsername = checkusername($username);
	 if($checkUsername==1) {
 		echo $username.' is already registered.Please use different username.';
		$errors = 1;
		die();
 	 }
 	 // check email is already using or not
	 $checkemail = checkuseremail($useremail);
	 if($checkemail==1) {
 		echo $useremail.' is already registered.Please use different email address.';
		$errors = 1;
		die();
 	 }
	 // if username and email not registered
	 if($checkUsername==0 && $checkemail==0 && $errors==0 && $userpassword !='') {
		 // create salt
		 $salt_reg = createSalt();
  		 // create hash paassword using salt and user entered password
		 $userpasswdHash = hash('sha256', $salt_reg . $userpassword);
		 $insertSql = "INSERT INTO users (id,userEmail,userName,userPassword,enable,regDateTime,salt) VALUES  ('','$useremail','$username','$userpasswdHash',1,NOW(),'$salt_reg')";
		 $results_insert = @mysql_query($insertSql) or die(mysql_error());
		 if($results_insert) {
			  echo 'Successfully Registered.';
		 }
		 else {
			  echo 'Registration Error.Please check the details again and submit.';
		 }
	 }  // end if condition
}  // end check if submit

Additional:-
mysql_real_escape_string()


2-User Login

This is the login form.

User Name:
Password:

You can put this script in the login.php same as registration.

if(isset($_POST['userSubmit']) && $_POST['userSubmit']=='Login') {
		$username = mysql_real_escape_string(trim($_POST['userName']));
		$userpassword = mysql_real_escape_string(trim($_POST['userPassword']));
 	    $errors = 0;
			// check uname and pswd
			$sql_check = "SELECT id,userEmail,userName,userPassword,salt FROM users WHERE userName='$username'";
			$result_check = mysql_query($sql_check) or die(mysql_error());;
			//********** check the username ***********************
			if(mysql_num_rows($result_check) < 1) //no such user exists
			{
				echo 'No such username exists.'; // wrong
				$errors = 1;
				die();
			}
			 //********** check the password **********************
			 // get user details to array
			 $userData = mysql_fetch_array($result, MYSQL_ASSOC);
			 // get that user's salt value
			 $db_salt = trim($userData['salt']);
			 // create hash password using db salt value and user entered password
			 $hash_entered =  hash('sha256', $db_salt . $userpassword);
			// compare both user entered password hash value and db value
			if($hash_entered != $userData['userPassword']) //incorrect password
			{
				 echo 'Incorrect Paasword.'; // wrong
				 $errors = 1;
				 die();
			}
			else
			{
				// if login details correct assign user values to the session variable
				$_SESSION['userID']=$userData['id'];
 				$_SESSION['userEmail']=$userData['userEmail'];
				$_SESSION['userName']=$userData['userName'];
	 		    //'Successfully Login
				header("location: home.php");
			}
 } // end if check login

That's only. Hope everything are clear and understandable. If you have any questions,suggestions put the comment below.Appreciate and glad to help you. 🙂
Thank you.