How to implement login in yii
1. Create the data table shop_admin
CREATE TABLE `shop_admin` ( `adminid` int(10) UNSIGNED NOT NULL COMMENT '主键ID', `adminuser` varchar(32) NOT NULL DEFAULT '' COMMENT '管理员账号', `adminpass` char(32) NOT NULL DEFAULT '' COMMENT '管理员密码', `adminemail` varchar(50) NOT NULL DEFAULT '' COMMENT '管理员邮箱', `logintime` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '登陆时间', `loginip` bigint(20) NOT NULL DEFAULT '0' COMMENT '登陆IP', `createtime` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '创建时间' ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. Login page
<?php use yii\bootstrap\ActiveForm; use yii\helpers\Html; $form = ActiveForm::begin([ 'id' => 'abc-form', 'options' => ['class' => 'form-horizontal'], ])?> <?= $form->field($model, 'adminuser')->textInput(['placeholder' => "用户名"])->label('账号') ?> <?= $form->field($model, 'adminpass')->passwordInput()->label('密码') ?> <?= Html::submitButton('提交') ?> <?php ActiveForm::end() ?>
3. Controller
Related article tutorial recommendations: yii Tutorial
<?php namespace app\controllers; use yii\web\Controller; use app\models\Admin; use Yii; class IndexController extends Controller { public function actionIndex() { // 不使用布局 $this->layout = false; $model = new Admin; // 是否是post提交 if (Yii::$app->request->isPost) { // 获得post提交参数 $post = Yii::$app->request->post(); if($model->login($post)){ return "登陆成功"; } else { return "登陆失败"; } } else { return $this->render("index", ['model' => $model]); } } }
4, Model
<?php namespace app\models; use yii\db\ActiveRecord; use Yii; class Admin extends ActiveRecord { public static function tableName() { return "{{%admin}}"; } public function rules() { return [ ['adminuser', 'required'], ['adminpass', 'required'], // 验证密码是否正确 ['adminpass', 'validatePass'] ]; } public function validatePass() { if (!$this->hasErrors()) { // 判断用户名密码是否正确 $data = self::find() ->where(['adminuser' => $this->adminuser]) ->andwhere(['adminpass' => md5($this->adminpass)]) ->one(); if (is_null($data)) { $this->addError('adminpass', 'adminuser or adminpass error'); } } } public function login($data) { if($this->load($data) && $this->validate()) { // 登陆信息写入session $session = Yii::$app->session; $session->open(); $session->set('adminuser', $this->adminuser); // 更新登陆时间和IP $this->updateAll(['logintime' => time(), 'loginip' => ip2long(Yii::$app->request->userIP)], ['adminuser' => $this->adminuser]); return true; } return false; } }
For more yiiIntroduction to Programming tutorials, please pay attention to the PHP Chinese website.
The above is the detailed content of How to implement login in yii. For more information, please follow other related articles on the PHP Chinese website!