Create Login form

Hi i’m only new to php framework. I want to ask how to create a simple login function, I have been reading a few basic tutorials but I cant find a way to create a login function with database.

Hello and welcome. In that case, head to the Larry Ullman tutorial series. One of his posts is exactly about login form with database.

At the first, you must create table, for example table user

And, here the script (sample)


CREATE TABLE IF NOT EXISTS `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `username` varchar(32) NOT NULL,

  `password` varchar(32) NOT NULL,

  `salt` varchar(32) NOT NULL,

  PRIMARY KEY (`id`),

  UNIQUE KEY `username` (`username`)

) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;

Then, head to file protected/config/main.php, and modify:

(Assumption using database mysql)




'db'=>array(

    'connectionString' => 'mysql:host=localhost;dbname=test',

    'emulatePrepare' => true,

    'username' => 'root',

    'password' => 'root',

    'charset' => 'utf8',

),



And modify also gii:




'modules'=>array(

    // uncomment the following to enable the Gii tool		

    'gii'=>array(

    'class'=>'system.gii.GiiModule',

    'password'=>'gii',

    // If removed, Gii defaults to localhost only. Edit carefully to taste.

    'ipFilters'=>array('127.0.0.1','::1'),

    ),		

),



After that, login using default username and password (admin/admin), and then enter to gii page. b[/b]

Then create model and give name User as Model in Model Generator, then generate CRUD through CRUD Generator.

Then, open in protected/models/User.php and add :


// hash password

public function hashPassword($password, $salt)

{

    return md5($salt.$password);

}

	

// password validation

public function validatePassword($password)

{

    return $this->hashPassword($password,$this->salt)===$this->password;

}

	

//generate salt

public function generateSalt()

{

    return uniqid('',true);

}

	

public function beforeValidate()

{

    $this->salt = $this->generateSalt();

    return parent::beforeValidate();

}

	

public function beforeSave()

{

    $this->password = $this->hashPassword($this->password, $this->salt);

    return parent::beforeSave();

}

Now, open file protected/views/user/_form.php, and remark like this:


<!-- 

	<div class="row">

		<?php echo $form->labelEx($model,'salt'); ?>

		<?php echo $form->textField($model,'salt',array('size'=>32,'maxlength'=>32)); ?>

		<?php echo $form->error($model,'salt'); ?>

	</div>

-->

And open your user CRUD page, then insert new username in that page.

After finishing insert data, you should view username, password and salt has been enrcrypted, then logout.

Open and modify, file protected/components/UserIdentity.php


class UserIdentity extends CUserIdentity

{

    private $_id;

	/**

	 * Authenticates a user.

	 * The example implementation makes sure if the username and password

	 * are both 'demo'.

	 * In practical applications, this should be changed to authenticate

	 * against some persistent user identity storage (e.g. database).

	 * @return boolean whether authentication succeeds.

	 */

	public function authenticate()

	{

	/*	

                remark default authentification

                $users=array(

			// username => password

			'demo'=>'demo',

			'admin'=>'admin',

		);

		if(!isset($users[$this->username]))

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		else if($users[$this->username]!==$this->password)

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else

			$this->errorCode=self::ERROR_NONE;

		return !$this->errorCode;

        }

        */

            

            $users= User::model()->findByAttributes(array('username'=>$this->username));

            

            if($users===null) {

                $this->errorCode = self::ERROR_USERNAME_INVALID;                

            }

            else if(!$users->validatePassword($this->password)) {

                $this->errorCode = self::ERROR_PASSWORD_INVALID;

            }

            else {           

                $this->errorCode = self::ERROR_NONE;

                $this->_id = $users->id;

            }

            return !$this->errorCode;

	}

        

        public function getId() {

            return $this->_id;

        }

}

Then, head to login page, and enter username and password which inserted before in CRUD page.

The system should display success login page. Happy trying… :rolleyes:

wow…thank you everyone for sharing…I will try your suggestions God bless… ;D

Just download a Yii Framework package From This link. :)

You will get a Demo App also with it.So that you can check a User login system is already present in Blog demo app.

Try to go through this code.And come up with the problems which you are facing.;)

Welcome to the Yii Community. :)

thank you very much for your help i tried this codes, but i get an error when logging in a new user. The error is in "C:\xampp\htdocs\sampleyii\protected\components\UserIdentity.php" and it says "Property "UserIdentity._id" is not defined."




 $this->_id = $users->id;



you are getting error due to this line.This code will assign a current user to the application after successful login.Please check it.




<?php


/**

 * UserIdentity represents the data needed to identity a user.

 * It contains the authentication method that checks if the provided

 * data can identity the user.

 */

class UserIdentity extends CUserIdentity

{

	private $_id;


	/**

	 * Authenticates a user.

	 * @return boolean whether authentication succeeds.

	 */

	public function authenticate()

	{

		

		/*

		 * $user=User::model()->find('LOWER(usr_username)=?',array(strtolower($this->username)));

		if($user===null)

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		else if(!$user->validatePassword($this->password))

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else

		{

			$this->_id=$user->id;

			$this->username=$user->username;

			$this->errorCode=self::ERROR_NONE;

		}

		 */

	    $user=User::model()->find('LOWER(usr_username)=?',array(strtolower($this->username)));


		if($user===null)

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		//else if ($user->usr_pass !== $this->password)

		else if(!$user->validatePassword($this->password))

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		elseif($user->usr_status == 0)

		    $this->errorCode=self::ERROR_PASSWORD_INVALID;

		else

		{

                    $this->_id=$user->usr_id;

                    $this->username=$user->usr_username;

                    $this->setState('email', $user->usr_email);

                    $this->setState('firstname', $user->usr_first_name);

                    

                    $this->errorCode=self::ERROR_NONE;

		}

		return $this->errorCode==self::ERROR_NONE;

	}


	/**

	 * @return integer the ID of the user record

	 */

	public function getId()

	{

		return $this->_id;

	}

}




Use this code in your UserIdentity class.

And in your login action in controller file Use this kind of code to Redirect User on any pf the page




public function actionLogin()

	{

		$this->layout="login-layout";


		$model=new LoginForm;


		// if it is ajax validation request

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}


		// collect user input data

		if(isset($_POST['LoginForm']))

		{

			$model->attributes=$_POST['LoginForm'];

			// validate user input and redirect to the previous page if valid

			if($model->validate() && $model->login()){

					

				if(Yii::app()->user->returnUrl==Yii::app()->baseUrl.'/index.php'){


					$uid=Yii::app()->user->id;

					//User::model()->updateByPk($uid, array('last_login'=>time()));

					$this->redirect(array('site/index'));

				}else{

					$this->redirect(Yii::app()->user->returnUrl);

				}

			}

				

			//$this->redirect(Yii::app()->user->returnUrl);

		}

		// display the login form

		$this->render('login',array('model'=>$model));

	}




thank you very much for your help,actually the first codes you gave worked already i found out the cause of error. i forgot to declare _id variable, i really appreciate your help thank you.its now working. :D

That is great Great…!!

Cheer ! :lol: