Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Yii2 MySQL中从表登录的分步指南_Php_Mysql_Login_Yii2 - Fatal编程技术网

Php Yii2 MySQL中从表登录的分步指南

Php Yii2 MySQL中从表登录的分步指南,php,mysql,login,yii2,Php,Mysql,Login,Yii2,我开始在Yii2中迈出第一步。到目前为止,我能够编写一个应用程序并将数据库中的表连接到它,就像我在Yii1中学习的那样 该表是contacts,并且我的create视图中的表单将数据发送到数据库,没有任何问题 问题是我只能在Yi2内置的静态用户模型中使用Admin/Admin或demo/demo登录 在Yii1.xx中,我使用组件/用户标识从数据库中的表中验证登录,就像这样(我使用了一个名为utilizador的表,其中包含id、utilizador和password): 关于Yii2,我已经阅

我开始在Yii2中迈出第一步。到目前为止,我能够编写一个应用程序并将数据库中的表连接到它,就像我在Yii1中学习的那样

该表是
contacts
,并且我的create视图中的表单将数据发送到数据库,没有任何问题

问题是我只能在Yi2内置的静态用户模型中使用Admin/Admin或demo/demo登录

在Yii1.xx中,我使用组件/用户标识从数据库中的表中验证登录,就像这样(我使用了一个名为
utilizador
的表,其中包含
id
utilizador
password
):

关于Yii2,我已经阅读了很多教程,包括一篇堆栈溢出教程,但没有一篇能告诉我如何使用MySQL数据库中的用户名和密码登录用户。Yii2没有components/useridentity.php,我不知道从哪里开始,也不知道覆盖现成的静态用户模型的正确代码是什么

我还尝试了一个扩展名为Yii2的用户,阅读了PDF指南,但不知道如何从我控制器中的供应商文件夹调用路由。做了几次尝试,但都失败了

有人能教我如何在Yii2中验证数据库登录,而不使用扩展名吗

编辑

我在Stack Overflow中阅读了本教程

还研究了Yii2用户扩展版的PDF,但不知道如何处理PDF的以下部分和下一部分。它谈到了路线,但我不知道如何使用它们:

2.3.1向用户展示 Route/user/admin/index显示注册用户的列表。您将能够看到许多有用的信息,如注册时间和ip地址、确认和阻止状态等

我也读过这篇文章: 但我认为它没有办法解决我的问题

编辑2

我尝试在Yii基本模板中实现用户模型和LoginForm模型,以验证用户登录。创建了一个数据库并连接到它。数据库作为表用户,字段包括用户名、密码、authKey、acessToken,并填充值。从ActiveRecord扩展了用户模型,并实现了\yii\web\IdentityInterface,以使内置的Yii2函数完成其工作。还编写了方法公共静态函数tableName(){return'user';}

每次尝试登录时,它都会从LoginForm模型中的validatepassword()抛出->用户名或密码错误

以下是我的代码: LoginForm模型:

public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();

        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect username or password.');
        }
    }
}
}

。。。这是我的User.php模型

<?php

namespace app\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;

public static function tableName() { return 'user'; }

   /**
 * @inheritdoc
 */
public static function findIdentity($id) {
    $user = self::find()
            ->where([
                "id" => $id
            ])
            ->one();
    if (!count($user)) {
        return null;
    }
    return new static($user);
}

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $userType = null) {

    $user = self::find()
            ->where(["accessToken" => $token])
            ->one();
    if (!count($user)) {
        return null;
    }
    return new static($user);
}

/**
 * Finds user by username
 *
 * @param  string      $username
 * @return static|null
 */
public static function findByUsername($username) {
    $user = self::find()
            ->where([
                "username" => $username
            ])
            ->one();
    if (!count($user)) {
        return null;
    }
    return new static($user);
}

/**
 * @inheritdoc
 */
public function getId() {
    return $this->id;
}

/**
 * @inheritdoc
 */
public function getAuthKey() {
    return $this->authKey;
}

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey) {
    return $this->authKey === $authKey;
}

/**
 * Validates password
 *
 * @param  string  $password password to validate
 * @return boolean if password provided is valid for current user
 */
public function validatePassword($password) {
    return $this->password === $password;
}

}

我不想放弃,但我正在考虑回到原来的Yii1.xx。在那里,我可以轻松地查询数据库,并使一个良好的登录系统正常工作。

Yii2高级应用程序默认带有数据库中登录部分的工作示例(我看到基本应用程序使用静态用户名和密码)。您不必安装任何额外的东西,只需查看代码即可。安装高级应用程序并查看前端

简而言之,SiteController使用LoginModel进行验证,然后使用LoginModel的login()将用户模型登录到用户组件

如果不想使用用户模型,只需创建自己的模型并使用该模型即可。您不想使用默认的用户组件,只需创建自己的组件即可。这很容易做到

编辑: mate,删除下面变量的公共声明

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;

您告诉Yii忽略数据库中的内容。

创建您自己的模型,然后使用它。我将在下面发布代码。

1) 首先根据您自己的需求创建一个数据库表

 CREATE TABLE `q_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL,
  `auth_key` varchar(32) NOT NULL,
  `password_hash` varchar(20) NOT NULL,
  `access_token` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 
  • 现在转到模型生成器并使用q_用户创建模型 桌子

  • 它将生成一个QUser模型。在这种模式下,您必须
    实现IdentityInterface

    类QUser扩展\yii\db\ActiveRecord实现\yii\web\IdentityInterface

现在实现所有的方法。如果使用Netbeans,请按alt+enter

public function getAuthKey() {
        return $this->auth_key;
    }

    public function getId() {
        return $this->id;
    }

    public function validateAuthKey($authKey) {
       return $this->auth_key = $authkey;
    }

    public static function findIdentity($id) {

        return self::findOne($id);

    }

    public static function findIdentityByAccessToken($token, $type = null) {

        return $this->access_token;
    }

    public static function findByUsername($email){
        return self::findOne(['email'=>$email]);
    }

    public function validatePassword($password){
        return $this->password_hash === $password;
    }
  • 现在在登录表单中,您必须定义Quser模型,以便 返回用户

    类LoginForm扩展了模型 { 公共$username; 公共密码; 公费邮件; public$rememberMe=true

    private $_user = false;
    
    
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['email', 'password'], 'required'],
            // rememberMe must be a boolean value
    
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
            ['password','match','pattern'=>'$\S*(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$','message'=>'Password must have atleast 1 uppercase and 1 number '],
            [['password'],'string','min'=>6],
            //email validation
            ['email','email']
        ];
    }
    
    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
    
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }
    
    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }
    
    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = QUser::findByUsername($this->email);
        }
    
        return $this->_user;
    }
    
    }


就这样,这会解决你的问题

这里有几件事要做。首先,你能告诉我们到目前为止你有什么,也许是按照你读过的官方文件或堆栈溢出帖子,然后有人可以帮助你修复/理解它吗?就目前情况而言,您需要几页教程,这可能使该网站的查询范围太广。此外,当你提到官方文档或插件时,请在你的帖子中链接它们,这样人们就可以关注链接并提出建议。我们基本上需要看到官方文件是不够的,但在Yii的情况下,我认为他们会没事?我理解你的担忧,并根据它编辑了这个问题。目前我还没有代码可以显示,因为尝试没有成功,我的项目只输出错误,无法使用。你想要什么样的答案?如果它是“一个完整的工作示例”,那么我认为它属于“过于宽泛”类别(即答案必须是实质性的,并且可能在您的用例中不起作用)。官方文档是否没有包含工作示例的教程?以及。否。我无法使文档中的代码正常工作。也许,因为我对Yii2还不熟悉。是的。我认为这是我需要走的道路。我将安装先进的模板和抓取的东西需要。非常感谢。我看了基本的应用程序,我现在明白了问题所在。看那个高级的。我在看Yii2高级的,我想我可以回答
public function getAuthKey() {
        return $this->auth_key;
    }

    public function getId() {
        return $this->id;
    }

    public function validateAuthKey($authKey) {
       return $this->auth_key = $authkey;
    }

    public static function findIdentity($id) {

        return self::findOne($id);

    }

    public static function findIdentityByAccessToken($token, $type = null) {

        return $this->access_token;
    }

    public static function findByUsername($email){
        return self::findOne(['email'=>$email]);
    }

    public function validatePassword($password){
        return $this->password_hash === $password;
    }
private $_user = false;


/**
 * @return array the validation rules.
 */
public function rules()
{
    return [
        // username and password are both required
        [['email', 'password'], 'required'],
        // rememberMe must be a boolean value

        ['rememberMe', 'boolean'],
        // password is validated by validatePassword()
        ['password', 'validatePassword'],
        ['password','match','pattern'=>'$\S*(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$','message'=>'Password must have atleast 1 uppercase and 1 number '],
        [['password'],'string','min'=>6],
        //email validation
        ['email','email']
    ];
}

/**
 * Validates the password.
 * This method serves as the inline validation for password.
 *
 * @param string $attribute the attribute currently being validated
 * @param array $params the additional name-value pairs given in the rule
 */
public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();

        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect username or password.');
        }
    }
}

/**
 * Logs in a user using the provided username and password.
 * @return boolean whether the user is logged in successfully
 */
public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
    }
    return false;
}

/**
 * Finds user by [[username]]
 *
 * @return User|null
 */
public function getUser()
{
    if ($this->_user === false) {
        $this->_user = QUser::findByUsername($this->email);
    }

    return $this->_user;
}