在Yii下建立工程並實現用戶註冊登陸

                          在Yii下建立工程並實現用戶註冊登陸


編輯工具:Netbeans,wampserver

數據庫:MySQL


相應工程代碼下載鏈接:Yii下用戶註冊登錄系統


【下載Yii庫,解壓並使用命令建立工程】

以庫文件在桌面並把工程sys建立在F盤的wamp/www文件夾下爲例輸入指令:

cd Desktop

cd yii/framework

yiic webapp F:wamp/www/sys

 

過程中如果出現‘’”php.exe”’不是內部或外部命令,也不是可運行的程序’的提示

 

 

解決方法:

打開yiic.bat,在set PHP_COMMAND後添加php的路徑

 

 

修改path環境變量(把php.exe的路徑設置到環境變量上去,在分號後面添加即可)

 

 

 

數據庫

 

 

數據庫代碼:

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

SET time_zone = "+00:00";

 


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;

/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;

/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;

/*!40101 SET NAMES utf8 */;

 

--

-- 數據庫: `sys`

--

 

-- --------------------------------------------------------

 

--

-- 表的結構 `user`

--

 

CREATE TABLE IF NOT EXISTS `user` (

  `userId` int(10) NOT NULL AUTO_INCREMENT,

  `userName` varchar(64) CHARACTER SET utf8 NOT NULL,

  `password` varchar(32) CHARACTER SET utf8 NOT NULL,

  PRIMARY KEY (`userId`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;


工程文件結構

 

 

< protected / views / yiic.php >

修改$yiic的路徑爲框架文件的路徑

 

 

< protected / index.php >

修改$yii的路徑

 

 

< protected / config / main.php >

連接數據庫,修改main.php’db’的內容,如下

 

 

views

Yiiviews目錄下有layouts和 site 兩個文件夾

< protected / views / layouts / main.php >

layouts中的main.php爲頁面主要框架,而site的內容顯示在 $content

 

自行修改菜單

 

 

< protected / site >

 

 

< protected / views / site / Register.php >

<?php

        $this->pageTitle=Yii::app()->name . ' - Register';

        $this->breadcrumbs=array(

            'Register',

        );

?>

<div class="form">
    <?php 
       $form=$this->beginWidget('CActiveForm', array(
            'id'=>'register-form',
            'enableClientValidation'=>true,
            'clientOptions'=>array(
                    'validateOnSubmit'=>true,
            ),
        )); 
    ?>
    <?php

        echo $form->errorSummary($model);

    ?>
    <div class="row">

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

        <?php echo $form->textField($model,'userName'); ?>

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

    </div>

    <div class="row">

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

        <?php echo $form->passwordField($model,'password'); ?>     <!--渲染密碼-->

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

    </div>  

    <div class="row buttons">

         <?php echo CHtml::submitButton('Submit'); ?>

    </div>

    <?php $this->endWidget(); ?>

</div>

 

< protected / views / site / Login.php >

<?php

/* @var $this SiteController */

/* @var $model LoginForm */

/* @var $form CActiveForm  */

	$this->pageTitle=Yii::app()->name . ' - Login';

	$this->breadcrumbs=array(

		'Login',

	);

?>

 

<h1>Login</h1>

 

<div class="form">

	<?php $form=$this->beginWidget('CActiveForm', array(

		'id'=>'login-form',

		'enableClientValidation'=>true,

		'clientOptions'=>array(

			'validateOnSubmit'=>true,

		),

	)); ?>

	<div class="row">

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

		<?php echo $form->textField($model,'userName'); ?>

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

	</div>

	<div class="row">

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

		<?php echo $form->passwordField($model,'password'); ?>

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

	</div>

	<div class="row buttons">

		<?php echo CHtml::submitButton('Login'); ?>

	</div>

 	<?php $this->endWidget(); ?>

</div><!-- form -->

 

models 

Yii中的Model主要實現的功能爲

1)具備屬性來存儲數據

2public functions rules() 用來定義驗證規則

3public function attributeLabels() 聲明屬性對於的標籤名稱

 

< protected / models / RegisterForm.php>

<?php

    class RegisterForm extends CFormModel{

        public $userName;

        public $password;

        public function rules(){

            return array(

                array('userName,password','required')

            );
        }
    }

?>

 

< protected / models / LoginForm.php >

<?php

class LoginForm extends CFormModel

{

	public $userName;

	public $password; 

	private $_identity;


	/**

 	* Declares the validation rules.

 	* The rules state that username and password are required,

	* and password needs to be authenticated.

 	*/

	public function rules()

	{

		return array(

			// username and password are required

			array('userName, password', 'required'),

			// password needs to be authenticated

			array('password', 'authenticate'),

		);

	}

	/**

	 * Authenticates the password.

 	 * This is the 'authenticate' validator as declared in rules().

 	 */

	public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())

		{

			$this->_identity=new UserIdentity($this->userName,$this->password);

			if(!$this->_identity->authenticate())

				$this->addError('password','Incorrect username or password.');

		}

	} 

	/**

 	  * Logs in the user using the given username and password in the model.

 	  * @return boolean whether login is successful

          */

	public function login()

	{

		if($this->_identity===null)

		{

			$this->_identity=new UserIdentity($this->userName,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		} else {
			return false;

		}
	}
}

 

Controllers

 用戶註冊登錄操作,主要爲數據的查詢、插入

< protected / controllers / SiteController.php >

<?php
class SiteController extends Controller
{
    	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
        
        public function actionIndex(){
            
            $this->render('index');
        }
    
        public function actionRegister(){
            $model = new RegisterForm;

            if(isset($_POST['RegisterForm'])){

                $model->attributes=$_POST['RegisterForm'];
                //不能寫成"$userName = trim($model->userName);" or "$userName = isset($model->userName);"
                $userName = $model->userName;   
                $password = md5($model->password);
                
                $conn = Yii::app()->db;              
                $msql = "select userName from `user` where userName = '$userName' ";
                $command = $conn->createCommand($msql);
                $num = $command->queryRow();                    //返回userName='$userName'那條記錄
                if($num){
                    $this->refresh();
                } else {
                    $sql="insert into `user`(userName,password) values('$userName','$password')";
                    $command = $conn->createCommand($sql);
                    $dataReader = $command->query();
                    if($dataReader){
                        $this->redirect(Yii::app()->createUrl('/site/Login'));                  //控制器間跳轉
                        exit();
                    }
                }
                
                $this->refresh();
            }

            $this->render('register',array('model'=>$model));
         }
           
         public function actionLogin(){
		$model=new LoginForm;
                
                if(isset($_POST['LoginForm'])){
                    
                    $model->attributes = $_POST['LoginForm'];
                    $username = $model->userName;
                    $password = md5($model->password);
                    
                    $conn = Yii::app()->db;
                    $sql = "select * from `user` where userName = '$username'";
                    $command = $conn->createCommand($sql);
                    $row = $command->queryAll();                  //獲取所有數據
                    
                    foreach($row as $k => $v){              //獲取到的數據爲二維數組
                        $name = $v['userName'];
                        $pw = $v['password'];
                    }
                    if($name){
                        if($pw == $password){
                            Yii::app()->session['user'] = $name;             //記錄登錄用戶的session
                            $this->redirect(Yii::app()->createUrl('/site/content'));
                        } else {
                            echo "password is wrong";
                            $this->refresh();
                        }
                    } else{
                        echo "user is not exist";
                        $this->refresh();                  //刷新頁面
                    }
                }
                
		// display the login form
		$this->render('login',array('model'=>$model));
	}
        
        public function actionContent(){
            $model = new ContentForm;
            
            if(isset($_POST['ContentForm'])){
                $model->attributes = $_POST['ContentForm'];
                $content = $model->content;
                
                $conn = Yii::app()->db;
                $sql = "insert into `user`(message)values('$content')";
                $command = $conn->createCommand($sql);
                $data = $command->query();
                if($data){
                    $this->redirect(Yii::app()->createUrl('/site/index'));
                }
            }
            
            $this->render('content',array('model'=>$model));
        }
      
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
}
?>


 

< protected / components >目錄下的文件

< Controller.php >

<?php

	class Controller extends CController

	{

		public $layout='//layouts/column1';

		public $menu=array();

		public $breadcrumbs=array();

	}

?>

 

 

< UserIdentity.php >

<?php

class UserIdentity extends CUserIdentity

{
	public function authenticate()

	{

		$users=array(

			// username => password

			'demo'=>'demo',

			'admin'=>'admin',

		);

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

			$this->errorCode=self::ERROR_USERNAME_INVALID;

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

			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
			$this->errorCode=self::ERROR_NONE;

		return !$this->errorCode;
	}
}

?>

 

 

最終效果:

 

 

數據庫數據:


備註:

        以上項目在建立的時候,視圖文件都在views/site上,當建立的是大工程的時候,工程文件就會變多,文件管理也會變得麻煩,而且,以上的文件結構也是不規範的,不符合MVC的文件結構,因此,可以參考以下工程文件結構

        把相應的代碼寫到相應的控制器文件下,不過有兩點需要注意:

        (1)每個控制器下最好也寫上actionError()函數,可以用於錯誤提示

               

        (2)由於每個控制器名稱和視圖名稱是對應的,當視圖下的文件名稱是什麼,對應的控制器動作名稱也要相同

                  例如:

                   

             controllers/RegisterController 的動作actionIndex() 和 views/register下的index.php 對應一致,否則會出現“The system is unable to find the requested action "index".” 的錯誤

                

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章