Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
* * * * * 3 votes

Creating A Simple Yet Secured Login/registration With Php5

encryption registration login

  • Please log in to reply
113 replies to this topic

#1 papabear

papabear

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 472 posts
  • Location:DarkSide

Posted 08 May 2012 - 03:28 PM

*
POPULAR

Hello everyone here's a new simple tutorial by me, I know that there's a lot of login and registration php script in this section but as I've review them.. some aren't secured and some still uses the php4 functions and some are weak and can be attack using SQL Injection that's why I decided to write up a tutorial that uses some new PHP5 functions that can help you in making your simple yet secured Login and registration script.

The very first thing that you have to do before we start is to create a database into your phpmyadmin

CREATE DATABASE `codecalltut` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `codecalltut`;


CREATE TABLE IF NOT EXISTS `users` (
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varbinary(250) NOT NULL,
  PRIMARY KEY (`userID`,`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

So we now have our database for this project. Let's create the login form now, create a file and name it index.php
then paste this login form in it.


<!DOCTYPE html>
<html>
	<head>
		<title>Codecall Tutorials - Secured Login with php5</title>
		<link rel="stylesheet" type="text/css" href="style.css" />
	</head>
	
	<body>
	
		<header id="head" >
		 <p>Codecall tutorials User Login</p>
		 <p><a href="register.php"><span id="register">Register</span></a></p>
		</header>
		
		<div id="main-wrapper">
		 <div id="login-wrapper">
			 <form method="post" action="">
				 <ul>
					 <li>
						 <label for="usn">Username : </label>
						 <input type="text" maxlength="30" required autofocus name="username" />
					 </li>
					
					 <li>
						 <label for="passwd">Password : </label>
						 <input type="password" maxlength="30" required name="password" />
					 </li>
					 <li class="buttons">
						 <input type="submit" name="login" value="Log me in" />
							<input type="button" name="register" value="Register" onclick="location.href='register.php'" />
					 </li>
					
				 </ul>
			 </form>
				
			</div>
		</div>
	
	</body>
</html>

then create a new file and name it register.php and paste this code inside that file


<!DOCTYPE html>
<html>
	<head>
		<title>Codecall Tutorials - Secured Login with php5</title>
		<link rel="stylesheet" type="text/css" href="style.css" />
	</head>
	
	<body>
		<header id="head" >
		 <p>Codecall tutorials User Registration</p>
		 <p><a href="register.php"><span id="register">Register</span></a></p>
		</header>
		
		<div id="main-wrapper">
		 <div id="register-wrapper">
			 <form method="post">
				 <ul>
					 <li>
						 <label for="usn">Username : </label>
						 <input type="text" id="usn" maxlength="30" required autofocus name="username" />
					 </li>
					
					 <li>
						 <label for="passwd">Password : </label>
						 <input type="password" id="passwd" maxlength="30" required name="password" />
					 </li>
						
						<li>
						 <label for="conpasswd">Confirm Password : </label>
						 <input type="password" id="conpasswd" maxlength="30" required name="conpassword" />
					 </li>
					 <li class="buttons">
						 <input type="submit" name="register" value="Register" />
							<input type="button" name="cancel" value="Cancel" onclick="location.href='index.php'" />
					 </li>
					
				 </ul>
			 </form>
			</div>
		</div>
	
	</body>
</html>

we know have all our form set, let's style our form a bit. create a new file and name it style.css then paste this


/* Css RESET */

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}

/* Styling the Header */
header#head {
background-color:#333333;
height: 50px;
width: 100%;
}

header#head p {
font-family: Arial, Helvetica, sans-serif;
font-size: 17px;
color:#999;
font-weight: bold;
padding: 20px;
}

header#head p #register {
float: right;
margin-top: -60px;
}

header#head p a:hover #register {
color:#999;
}

/* Styling the main wrapper */
#main-wrapper {
width: 100%;
height: 100%;
}


/* Styling the login wrapper */
#login-wrapper {
margin: 0px auto;
width: 310px;
height: 180px;
padding: 50px 1px 10px 50px;
margin-top: 150px;
-moz-box-shadow: 0px 0px 10px #888;
-o-box-shadow: 0px 0px 10px #888;
-webkit-box-shadow: 0px 0px 10px #888;
-moz-border-radius: 10px 10px 10px 10px;
-o-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
}

#register-wrapper {
margin: 0px auto;
width: 310px;
height: 250px;
padding: 50px 1px 10px 50px;
margin-top: 150px;
-moz-box-shadow: 0px 0px 10px #888;
-o-box-shadow: 0px 0px 10px #888;
-webkit-box-shadow: 0px 0px 10px #888;
-moz-border-radius: 10px 10px 10px 10px;
-o-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
}

/* Form height, margin, padding */
form ul {
	list-style: none;
	margin: 0;
	padding: 0;
}

form ul li {
	margin: .9em 0 0 0;
	padding: 0;
}

form * {
	line-height: 1em;
}

/* field labels */

label {
	clear: left;
	text-align: right;
	width: 15%;
	font-family: arial;
	font-weight: bold;
	font-size: 15px;
	color: #808080;
}

/* the fields */

input {
	font-size: .9em;
}

input {
	border: 2px solid #666;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
	background: #fff;
}

input {
	display: block;
	margin: 0;
	padding: .4em;
	width: 80%;
}

/* Place a border around focused fields */

form *:focus {
	border: 2px solid #7c412b;
	outline: none;
}

/* Display correctly filled-in fields with a green background */

input:valid {
	background: #efe;
}




/* Submit buttons */

.buttons {
	text-align: center;
	margin: 20px 0 0 -80px;
}

input[type="submit"], input[type="button"] {
	display: inline;
	margin: 0 5px;
margin-left:20px;
	width: 10em;
	padding: 10px;
	border: 2px solid #7c412b;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
	-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
	-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
	box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
	color: #fff;
	background: #ca5f34;
	font-weight: bold;
	-webkit-appearance: none;
}

input[type="submit"]:hover, input[type="submit"]:active, input[type="button"]:hover, input[type="button"]:active {
	cursor: pointer;
	background: #fff;
	color: #ef7d50;
}

input[type="button"]:active, input[type="button"]:active {
	background: #eee;
	-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
	-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
	box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
}




here's the look of our login and registration page now
registration.JPG
login.JPG

ok everything was set.. let's get into coding! create a new file and name it config.php we are going to use this file to store every constant and settings for our project. Paste this code inside config.php

<?php
	//set off all error for security purposes
error_reporting(0);


//define some contstant
	define( "DB_DSN", "mysql:host=localhost;dbname=codecalltut" ); //this constant will be use as our connectionstring/dsn

	define( "DB_USERNAME", "root" ); //username of the database
	define( "DB_PASSWORD", "" ); //password of the database
define( "CLS_PATH", "class" ); //the class path of our project

?>

Everything was explained inside the codes with comment :)

let's now create our Users class, this class will contain the function or registering and logging into our project.

create a new folder and name it class then inside that folder create a file named user.php open the file and let's start.

first let's create the class


<?php

class Users {

}

?>

What is a class? Classes are objects that contains useful functions to use in your programs. If you are an OOP(object oriented programmer) you will encounter Classes many times. Classes can be used for data hiding like encapsulation, abstraction and polymorphism.

let's declare the public/global variables that we will use into this class


class Users {
	 public $username = null;
	 public $password = null;
	 public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
}

$username= we are going to use this variable to be able to store and get the values of our form easily by just calling $this->username.

$password = like $username this variable will be use to store and get the password in the form.

$salt = salt will be use for hashing/encrypting our password.

let's create our first function in this class


public function __construct( $data = array() ) {
			   if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
			  if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}

Is this your first time seeing that __construct? __construct is one of the magic methods and it was introduced in PHP5. What is the use of __construct? The moment you call the class or create an instance of it or use it's variable, the __construct method will be executed automatically. This is a useful function for storing data to your public variables.

if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );

the parameter $data in our __construct class is an associative array and. If we pass the $_POST into this method knowing that our $_POST from the form will have something like $_POST['username'] and $_POST['password'].
this two condition there was just organizing the data and removing the slashes and html tags for security we used stripslashes() and strip_tags() functions.


Let's now create a function that we can use to get the $_POST into our form and give it to our __construct method.


public function storeFormValues( $params ) {
			  //store the parameters
			  $this->__construct( $params );
}

we will use this to get the $_POST from our forms something like Users->storeFormValues($_POST) and then we will store those values into our __construct class.

let's create the login function


public function userLogin() {
				   //success variable will be used to return if the login was successful or not.
				   $success = false;
				  try{
					 //create our pdo object
					 $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
					 //set how pdo will handle errors
					 $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
					 //this would be our query.
					 $sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

					  //prepare the statements
					 $stmt = $con->prepare( $sql );
					 //give value to named parameter :username
					 $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
					 //give value to named parameter :password
					 $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
					 $stmt->execute();

					 $valid = $stmt->fetchColumn();

					if( $valid ) {
						  $success = true;
					 }

					 $con = null;
					 return $success;
				 }catch (PDOException $e) {
					  echo $e->getMessage();
					  return $success;
				 }
}

If you can see I used PDO for my database connection and manipulation.
Why? Because it supports prepared statements and named parameters. For a basic tutorial of using the PDO Connection Please go into this thread -> Using PDO for Database Access (Beginner)

In the code above there are comments that will teach what the code is doing, and you will encounter a line that uses this

hash("sha256", $this->password . $this->salt)

what is that by the way?
it is the hash() function that was introduced to PHP5 recently. With the use of that function it's now easy to encrypt a string with different algorithms.


md2		   32	
md4		   32
md5		   32
sha1		  40
sha256		64
sha384		96
sha512	   128
ripemd128	 32
ripemd160	 40
ripemd256	 64
ripemd320	 80  
whirlpool	128
tiger128,3	32
tiger160,3	40
tiger192,3	48
tiger128,4	32
tiger160,4	40
tiger192,4	48
snefru		64
gost		  64
adler32		8
crc32		  8
crc32b		 8
haval128,3	32
haval160,3	40
haval192,3	48
haval224,3	56
haval256,3	64
haval128,4	32
haval160,4	40
haval192,4	48
haval224,4	56
haval256,4	64
haval128,5	32
haval160,5	40
haval192,5	48
haval224,5	56
haval256,5	64

how to use it?
hash(algorithm, stringtohash . salt)
salt is optional but it's highly recommended to use it for an advance security.
In this tutorial I uses the sha256 encryption algorithm.

let's continue, here's our registration function




public function register() {
	 $correct = false;
	 try {
			  $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
			  $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
			  $sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

			  $stmt = $con->prepare( $sql );
			  $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
			  $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
			  $stmt->execute();
			  return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
	   }catch( PDOException $e ) {
				 return $e->getMessage();
	   }
}


same as the login we use the
hash("sha256", $this->password . $this->salt)

our class is now complete and here's the complete Users class code.


<?php

class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";

public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}

public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}

public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();

$valid = $stmt->fetchColumn();

if( $valid ) {
$success = true;
}

$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}

public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
}catch( PDOException $e ) {
return $e->getMessage();
}
}

}

?>

sorry if there's no indention, When I pasted the code from my code editor from here the indention was missing.

Everything was set up, we now have a class where we can use login and registration, now we must include it to our config.php.

open up config.php and paste this code below to include our class

 //include the classes
include_once( CLS_PATH . "/user.php" );

then open up the index.php once again and let's include our config.php and use the class functions.
paste this code at the very top of your index.php


<?php 
include_once("config.php");
?>

<?php if( !(isset( $_POST['login'] ) ) ) { ?>

then paste this code at the very bottom of your index.php


<?php 
} else {
$usr = new Users; //create a new instance of the Users class
$usr->storeFormValues( $_POST ); //like I said before we will use the function storeFormValues to store the form values

if( $usr->userLogin() ) {
echo "Welcome"; 
} else {
echo "Incorrect Username/Password"; 
}
}
?>

the index.php will now look like this.


<?php 
include_once("config.php"); //include the settings/configuration
?>

//if user did not click the login button show the login form
<?php if( !(isset( $_POST['login'] ) ) ) { ?>

<!DOCTYPE html>
<html>
    <head>
        <title>Codecall Tutorials - Secured Login with php5</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    
    <body>
    
        <header id="head" >
         <p>Codecall tutorials User Login</p>
         <p><a href="register.php"><span id="register">Register</span></a></p>
        </header>
        
        <div id="main-wrapper">
         <div id="login-wrapper">
             <form method="post" action="">
                 <ul>
                     <li>
                         <label for="usn">Username : </label>
                         <input type="text" maxlength="30" required autofocus name="username" />
                     </li>
                    
                     <li>
                         <label for="passwd">Password : </label>
                         <input type="password" maxlength="30" required name="password" />
                     </li>
                     <li class="buttons">
                         <input type="submit" name="login" value="Log me in" />
                            <input type="button" name="register" value="Register" onclick="location.href='register.php'" />
                     </li>
                    
                 </ul>
             </form>
                
            </div>
        </div>
    
    </body>
</html>

<?php 
//else look at the database and see if he entered the correct details
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );

//if our function userLogin() returns true then the user is valid, display welcome else say it's incorrect.
if( $usr->userLogin() ) {
echo "Welcome"; 
} else {
echo "Incorrect Username/Password"; 
}
}
?>


index.php is done, let's now edit our registration.php

add this at the very top of the file


<?php 
include_once("config.php"); //include the config
?>

//if user did not click registration button show the registration field.
<?php if( !(isset( $_POST['register'] ) ) ) { ?>

and this code at the very bottom of the file like the index.php


<?php 

//if register button was clicked.
} else {
$usr = new Users; //create new instance of the class Users
$usr->storeFormValues( $_POST ); //store form values

//if the entered password is match with the confirm password then register him
if( $_POST['password'] == $_POST['conpassword'] ) {
echo $usr->register($_POST); 
} else {
//if not then say that he must enter the same password to the confirm box.
echo "Password and Confirm password not match"; 
}
}
?>



The End.

the tutorial is now done, and we've manage to create a simple yet secured login and registration!
I've attached the project files and the database backup for you to download it.
Have fun guys

Attached File  codecall.zip   5.2KB   16501 downloads
  • 10
Life has no CTRL+Z
Never Forget To HIT "LIKE" If I Helped

#2 olsanikin

olsanikin

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 20 May 2012 - 04:14 AM

Maybe its just me, but it doesnt insert anything into the database
  • 1

#3 papabear

papabear

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 472 posts
  • Location:DarkSide

Posted 20 May 2012 - 01:49 PM

Maybe its just me, but it doesnt insert anything into the database


hello thanks for replying into my tutorial
I've just tested the program and it's working fine with me :) please make sure you are using the current version of PHP
and you have created the database correctly or else it won't insert, if error occurs don't hesitate to post it here so we can troubleshoot it

Happy Coding :)
  • 0
Life has no CTRL+Z
Never Forget To HIT "LIKE" If I Helped

#4 michaelJ

michaelJ

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts
  • Programming Language:PHP
  • Learning:PHP

Posted 24 May 2012 - 03:28 AM

Hi total newbie here, first off all congrats on a nice script/tutorial and thanks for sharing :) I am about to build a new website using php with a login/register function so im wondering where would be best to start.

I have not really done much of the site yet and so im wondering if it would be better to start with your script and change the style to one of my own adding pages along the way, or, start building my site then incorporate the register/login script at a later date when needed. I have never built a website of my own before so im looking for the easiest option. Thanks.
  • 0

#5 papabear

papabear

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 472 posts
  • Location:DarkSide

Posted 24 May 2012 - 06:09 PM

Hi total newbie here, first off all congrats on a nice script/tutorial and thanks for sharing :) I am about to build a new website using php with a login/register function so im wondering where would be best to start.

I have not really done much of the site yet and so im wondering if it would be better to start with your script and change the style to one of my own adding pages along the way, or, start building my site then incorporate the register/login script at a later date when needed. I have never built a website of my own before so im looking for the easiest option. Thanks.


hello my tutorial is a very basic login and registration script, the registration is good but the login will not really work because it's basic.. the user won't appear login in every pages of your website because I didn't use $_SESSION if you know where to put and set the $_SESSION then you can get it.
But I suggest just reading it and adopting the security methods that I applied instead of my programming style, try to use your own style if you are comfortable of using it.
  • 0
Life has no CTRL+Z
Never Forget To HIT "LIKE" If I Helped

#6 cipcip

cipcip

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 51 posts
  • Location:Romania
  • Programming Language:PHP
  • Learning:Java, PHP, JavaScript, Visual Basic .NET

Posted 04 June 2012 - 12:51 PM

Thanks for this, it is a nice start to learn php5.
  • 0

#7 GuageCage

GuageCage

    CC Lurker

  • New Member
  • Pip
  • 3 posts
  • Learning:Java, C++, PHP, (Visual) Basic, JavaScript, PL/SQL, Visual Basic .NET, Bash

Posted 08 June 2012 - 11:55 AM

Yes def. Thanks for the in site. i am very concerned about security and this will help out tremendously. Thank You. :thumbup1:
  • 0

#8 Dizel

Dizel

    CC Lurker

  • New Member
  • Pip
  • 4 posts
  • Programming Language:PHP, JavaScript, PL/SQL
  • Learning:Java, C++

Posted 14 June 2012 - 10:06 AM

thanks.... thats what i called programming
  • 0

#9 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 14 June 2012 - 03:39 PM

Very well rounded, I enjoyed seeing your use of bound parameters and SHA256 as a margin for the future. My thoughts on what you are storing, a string with strip slashes applied, is there a specific reason for that? If magic quotes exists it should be checked before stripping, otherwise it could strip a slash the user enters themselves (i.e. "///alex22\\\"), which otherwise is a valid user name in a basic registration form.

Salting will become irrelevant if the salt is found (which is reasonably simple in line with an attack to gain the database contents) and a complete lookup table can be constructed from this one salt, all passwords can be found through that. If you store a random salt along with each user in a field, they cannot use the same precomputed table for each user, and non-single user targeted attacks will become increasingly infeasible. i.e. (2^256/2)^n where n is users.

salt_user . password . salt_from_filesystem for example gains the complexity of having to get two salts from two places yet still be equally effective in both uses.

You use varbinary for password but store in ASCII (1 byte = 2 bytes), I have not looked, but this could truncate the password and never have it verify correctly in the situation where the field is too small. You must use the raw output option on hash() for it to as intended. 256/8=32 bytes binary, 64 bytes ASCII = double inflation. Latin could be changed to UTF-8 for the situation where data is viewed somewhere and saved again.

You echo a PDO exception (or return one of its messages) one time, why not return the exception class (over message) or let the user handle try/catch over your class in application use?

You return a string for success in the register function, appears very static if the class were in its own file and you would have to find it. More anon.
  • 2

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#10 papabear

papabear

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 472 posts
  • Location:DarkSide

Posted 14 June 2012 - 06:32 PM

Very well rounded, I enjoyed seeing your use of bound parameters and SHA256 as a margin for the future. My thoughts on what you are storing, a string with strip slashes applied, is there a specific reason for that? If magic quotes exists it should be checked before stripping, otherwise it could strip a slash the user enters themselves (i.e. "///alex22\\\"), which otherwise is a valid user name in a basic registration form.

Salting will become irrelevant if the salt is found (which is reasonably simple in line with an attack to gain the database contents) and a complete lookup table can be constructed from this one salt, all passwords can be found through that. If you store a random salt along with each user in a field, they cannot use the same precomputed table for each user, and non-single user targeted attacks will become increasingly infeasible. i.e. (2^256/2)^n where n is users.

salt_user . password . salt_from_filesystem for example gains the complexity of having to get two salts from two places yet still be equally effective in both uses.

You use varbinary for password but store in ASCII (1 byte = 2 bytes), I have not looked, but this could truncate the password and never have it verify correctly in the situation where the field is too small. You must use the raw output option on hash() for it to as intended. 256/8=32 bytes binary, 64 bytes ASCII = double inflation. Latin could be changed to UTF-8 for the situation where data is viewed somewhere and saved again.

You echo a PDO exception (or return one of its messages) one time, why not return the exception class (over message) or let the user handle try/catch over your class in application use?

You return a string for success in the register function, appears very static if the class were in its own file and you would have to find it. More anon.


ohh yes... I should have not remove the slashes anymore since I used mysql_real_escape_string already thanks for that :D
I would like to try your suggestion about having 2 salt.. with a random one :D
I'm going to use that in the mvc framework that I'm currently doing right now.
  • 1
Life has no CTRL+Z
Never Forget To HIT "LIKE" If I Helped

#11 Derek

Derek

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts
  • Programming Language:PHP
  • Learning:PHP

Posted 17 June 2012 - 02:55 AM

Fatal error: Class 'PDO' not found in /home/**/public_html/**/class/user.php on line 47

PDO error?

$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

  • 0

#12 papabear

papabear

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 472 posts
  • Location:DarkSide

Posted 17 June 2012 - 06:34 AM

Fatal error: Class 'PDO' not found in /home/**/public_html/**/class/user.php on line 47

PDO error?

$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );


have you downloaded the source code? you might have missed something...
what PHP version you are using?
  • 0
Life has no CTRL+Z
Never Forget To HIT "LIKE" If I Helped





Also tagged with one or more of these keywords: encryption, registration, login