在Yii下建立工程并实现用户注册登陆图文解析.docx
《在Yii下建立工程并实现用户注册登陆图文解析.docx》由会员分享,可在线阅读,更多相关《在Yii下建立工程并实现用户注册登陆图文解析.docx(16页珍藏版)》请在冰豆网上搜索。
在Yii下建立工程并实现用户注册登陆图文解析
在Yii下建立工程并实现用户注册登陆
【下载Yii库,解压并使用命令建立工程】
以库文件在桌面并把工程sys建立在F盘的wamp/www文件夹下为例输入指令:
cdDesktop
cdyii/framework
yiicwebappF:
wamp/www/sys
过程中如果出现‘’”php.exe”’不是内部或外部命令,也不是可运行的程序’的提示
解决方法:
打开yiic.bat,在setPHP_COMMAND后添加php的路径
修改path环境变量(把php.exe的路径设置到环境变量上去,在分号后面添加即可)
数据库
数据库代码:
--phpMyAdminSQLDump
--version3.4.5
--
--主机:
localhost
--生成日期:
2015年04月01日09:
04
--服务器版本:
5.5.16
--PHP版本:
5.3.8
SETSQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SETtime_zone="+00:
00";
/*!
40101SET@OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT*/;
40101SET@OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS*/;
40101SET@OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION*/;
40101SETNAMESutf8*/;
--数据库:
`sys`
----------------------------------------------------------
--表的结构`user`
CREATETABLEIFNOTEXISTS`user`(
`userId`int(10)NOTNULLAUTO_INCREMENT,
`userName`varchar(64)CHARACTERSETutf8NOTNULL,
`password`varchar(32)CHARACTERSETutf8NOTNULL,
PRIMARYKEY(`userId`)
)ENGINE=InnoDBDEFAULTCHARSET=utf8mb4AUTO_INCREMENT=3;
--转存表中的数据`user`
INSERTINTO`user`(`userId`,`userName`,`password`)VALUES
(1,'admin','21232f297a57a5a743894a0e4a801fc3'),
(2,'aa','4124bc0a9335c27f086f24ba207a4912');
40101SETCHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT*/;
40101SETCHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS*/;
40101SETCOLLATION_CONNECTION=@OLD_COLLATION_CONNECTION*/;
工程文件结构
修改$yiic的路径为框架文件的路径
修改$yii的路径
连接数据库,修改main.php中’db’的内容,如下
【views】
Yii的views目录下有layouts和site两个文件夹
layouts中的main.php为页面主要框架,而site的内容显示在$content
自行修改菜单
php
$this->pageTitle=Yii:
:
app()->name.'-Register';
$this->breadcrumbs=array(
'Register',
);
?
>
$form=$this->beginWidget('CActiveForm',array(
'id'=>'register-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
echo$form->errorSummary($model);
phpecho$form->labelEx($model,'userName');?
phpecho$form->textField($model,'userName');?
phpecho$form->error($model,'userName');?
phpecho$form->labelEx($model,'password');?
phpecho$form->passwordField($model,'password');?
--渲染密码-->
phpecho$form->error($model,'password');?
phpechoCHtml:
submitButton('Submit');?
php$this->endWidget();?
/*@var$thisSiteController*/
/*@var$modelLoginForm*/
/*@var$formCActiveForm*/
app()->name.'-Login';
'Login',
php$form=$this->beginWidget('CActiveForm',array(
'id'=>'login-form',
));?
submitButton('Login');?
--form-->
【models】
Yii中的Model主要实现的功能为
(1)具备属性来存储数据
(2)publicfunctionsrules()用来定义验证规则
(3)publicfunctionattributeLabels()声明属性对于的标签名称
classRegisterFormextendsCFormModel{
public$userName;
public$password;
publicfunctionrules(){
returnarray(
array('userName,password','required')
}
classLoginFormextendsCFormModel
{
private$_identity;
/**
*Declaresthevalidationrules.
*Therulesstatethatusernameandpasswordarerequired,
*andpasswordneedstobeauthenticated.
*/
publicfunctionrules()
//usernameandpasswordarerequired
array('userName,password','required'),
//passwordneedstobeauthenticated
array('password','authenticate'),
*Authenticatesthepassword.
*Thisisthe'authenticate'validatorasdeclaredinrules().
publicfunctionauthenticate($attribute,$params)
if(!
$this->hasErrors())
$this->_identity=newUserIdentity($this->userName,$this->password);
$this->_identity->authenticate())
$this->addError('password','Incorrectusernameorpassword.');
*Logsintheuserusingthegivenusernameandpasswordinthemodel.
*@returnbooleanwhetherloginissuccessful
publicfunctionlogin()
if($this->_identity===null)
$this->_identity->authenticate();
if($this->_identity->errorCode===UserIdentity:
ERROR_NONE)
$duration=$this->rememberMe?
3600*24*30:
0;//30days
Yii:
app()->user->login($this->_identity,$duration);
returntrue;
else
returnfalse;
【Controllers】
classSiteControllerextendsController
*Declaresclass-basedactions.
publicfunctionactions()
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
'page'=>array(
'class'=>'CViewAction',
publicfunctionactionIndex(){
$this->render('index');
publicfunctionactionRegister(){
$model=newRegisterForm;
if(isset($_POST['RegisterForm'])){
$model->attributes=$_POST['RegisterForm'];
$userName=$model->userName;//can'tbewrittenas"$userName=trim($model->userName);"or"$userName=isset($model->userName);"
$password=md5($model->password);
$conn=Yii:
app()->db;
$msql="selectuserNamefrom`user`whereuserName='$userName'";
$command=$conn->createCommand($msql);
$num=$command->queryRow();//返回userName='$userName'那条记录
if($num){
$this->refresh();
}else{
$sql="insertinto`user`(userName,password)values('$userName','$password')";
$command=$conn->createCommand($sql);
$dataReader=$command->query();
if($dataReader){
$this->redirect(Yii:
app()->createUrl('/site/Login'));//控制器间跳转
exit();
$this->render('register',array('model'=>$model));
publicfunctionactionLogin(){
$model=newLoginForm;
if(isset($_POST['LoginForm'])){
$model->attributes=$_POST['LoginForm'];
$username=$model->userName;
$sql="select*from`user`whereuserName='$username'";
$row=$command->queryAll();//获取所有数据
foreach($rowas$k=>$v){//获取到的数据为二维数组
$name=$v['userName'];
$pw=$v['password'];
if($name){
if($pw==$password){
app()->session['user']=$name;//记录登录用户的session
app()->createUrl('/site/content'));
echo"passwordiswrong";
echo"userisnotexist";
$this->refresh();//刷新页面
//displaytheloginform
$this->render('login',array('model'=>$model));
publicfunctionactionContent(){
$model=newContentForm;
if(isset($_POST['ContentForm'])){
$model->attributes=$_POST['ContentForm'];
$content=$model->content;
$sql="insertinto`user`(message)values('$content')";
$data=$command->query();
if($data){
app()->createUrl('/site/index'));
$this->render('content',array('model'=>$model));
*Thisistheactiontohandleexternalexceptions.
publicfunctionactionError()
if($error=Yii:
app()->errorHandler->error)
if(Yii:
app()->request->isAjaxRequest)
echo$error['message'];
$this->render('error',$error);
目录下的文件
classControllerextendsCController
public$layout='//layouts/column1';
public$menu=array();
public$breadcrumbs=array();
classUserIdentityextendsCUserIdentity
publicfunctionauthenticate()
$users=array(
//username=>password
'demo'=>'demo',
'admin'=>'admin',
isset($users[$this->username]))
$this->errorCode=self:
ERROR_USERNAME_INVALID;
elseif($users[$this->username]!
==$this->password)
ERROR_PASSWORD_INVALID;
ERROR_NONE;
return!
$this->errorCode;
最终效果:
数据库数据:
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1