Yii2 기본 버전 로그인에서는 Yii::$app->user->login($user)을 사용합니다. 오류가 발생합니다.
Yii2 basic
版登录使用Yii::$app->user->login($user);
出现错误Array to string conversion
MyAuthenticationController.php
<code><?php namespace app\controllers; use Yii; use yii\web\Controller; use app\models\User; class MyAuthenticationController extends Controller { public function actionIndex() { echo 'login success'; exit; } public function actionLogin() { $error = null; $username = Yii::$app->request->post('username',null); $password = Yii::$app->request->post('password',null); $user = User::findOne(['username'=>$username]); if(($username!=null)&&($password!=null)) { if($user!=null){ if($user->validatePassword($password)){ $this->redirect(['index']);//这里可以实现重定向 // Yii::$app->user->login($user);这是源代码,但是会出现“Array to string conversion”的错误,暂时还没有解决,所以使用上面的重定向代码来转向指定登录成功的页面 }else{ $error = 'Password validation failed'; } }else{ $error = 'User not found'; } } return $this->render('login',['error'=>$error]); } public function actionLogout() { Yii::$app->user->logout(); return $this->redirect(['login']); } }</code>
app\models\User.php
<code><?php namespace app\models; use Yii; use yii\base\NotSupportedException; use yii\db\ActiveRecord; use yii\web\IdentityInterface; class User extends ActiveRecord implements IdentityInterface { public static function tableName() { return 'user'; } /** * @inheritdoc */ public static function findIdentity($id) { return static::findOne(['id'=>$id]); } /** * @inheritdoc */ public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['access_token'=>$token]); } /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { return static::findOne(['username'=>$username]); } /** * @inheritdoc */ public function getId() { return $this->PrimaryKey(); } /** * @inheritdoc */ public function getAuthKey() { return $this->auth_Key; } /** * @inheritdoc */ public function validateAuthKey($authKey) { return $this->getAuthKey() === $authKey; } /** * Validates password * * @param string $password password to validate * @return boolean if password provided is valid for current user */ public function validatePassword($password) { return Yii::$app->security->validatePassword($password,$this->password_hash); } public function generateAuthKey() { $this->auth_key = Yii::$app->security->generateRandomKey(); } public function beforeSave($insert) { if(parent::beforeSave($insert)){ if($this->isNewRecord){ $this->auth_key = \Yii::$app->security->generateRandomString(); } return true; } return false; } }</code>
views\my-authentication\login.php
<code><?php use \yii\bootstrap\ActiveForm; use \yii\helpers\Html; use \yii\bootstrap\Alert; ?> <?php if($error!=null){ echo Alert::widget(['options'=>['class'=>'alert-danger'],'body'=>$error]); }; ?> <?php if(Yii::$app->user->isGuest) { ?> <?php ActiveForm::begin() ?> <div class="form-group"> <?php echo Html::label('Username','username'); ?> <?php echo Html::textInput('username','',['class'=>'form-control']);?> </div> <div class="form-group"> <?php echo Html::label('Password','password'); ?> <?php echo Html::passwordInput('password','',['class'=>'form-control']); ?> </div> <?php echo Html::submitButton('Login',['class'=>'btn btn-primary']); ?> <?php ActiveForm::end(); ?> <?php } else {?> <h2>You are authentication!</h2> <br/><br/> <?php echo Html::a('logout',['my-authentication/logout'],['class'=>'btn btn-warning']); ?> <?php } ?></code>
SQL
<code>-- -- 表的结构 `user` -- CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `auth_key` varchar(32) NOT NULL, `password_hash` varchar(255) NOT NULL, `access_token` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; -- -- 转存表中的数据 `user` -- INSERT INTO `user` (`id`, `username`, `auth_key`, `password_hash`, `access_token`) VALUES (1, 'foo', '', '$2a$12$hL0rmIMjxhLqI.xr7jD1FugNWEgZNh62HuJj5.y34XBUfBWB4cppW', NULL);</code>
用户名是foo
,密码是foopassword
,登录后在Yii::$app->user->login($user);
时出现错误,
回复内容:
Yii2 basic
版登录使用Yii::$app->user->login($user);
出现错误Array to string conversion
MyAuthenticationController.php
<code><?php namespace app\controllers; use Yii; use yii\web\Controller; use app\models\User; class MyAuthenticationController extends Controller { public function actionIndex() { echo 'login success'; exit; } public function actionLogin() { $error = null; $username = Yii::$app->request->post('username',null); $password = Yii::$app->request->post('password',null); $user = User::findOne(['username'=>$username]); if(($username!=null)&&($password!=null)) { if($user!=null){ if($user->validatePassword($password)){ $this->redirect(['index']);//这里可以实现重定向 // Yii::$app->user->login($user);这是源代码,但是会出现“Array to string conversion”的错误,暂时还没有解决,所以使用上面的重定向代码来转向指定登录成功的页面 }else{ $error = 'Password validation failed'; } }else{ $error = 'User not found'; } } return $this->render('login',['error'=>$error]); } public function actionLogout() { Yii::$app->user->logout(); return $this->redirect(['login']); } }</code>
app\models\User.php
<code><?php namespace app\models; use Yii; use yii\base\NotSupportedException; use yii\db\ActiveRecord; use yii\web\IdentityInterface; class User extends ActiveRecord implements IdentityInterface { public static function tableName() { return 'user'; } /** * @inheritdoc */ public static function findIdentity($id) { return static::findOne(['id'=>$id]); } /** * @inheritdoc */ public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['access_token'=>$token]); } /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { return static::findOne(['username'=>$username]); } /** * @inheritdoc */ public function getId() { return $this->PrimaryKey(); } /** * @inheritdoc */ public function getAuthKey() { return $this->auth_Key; } /** * @inheritdoc */ public function validateAuthKey($authKey) { return $this->getAuthKey() === $authKey; } /** * Validates password * * @param string $password password to validate * @return boolean if password provided is valid for current user */ public function validatePassword($password) { return Yii::$app->security->validatePassword($password,$this->password_hash); } public function generateAuthKey() { $this->auth_key = Yii::$app->security->generateRandomKey(); } public function beforeSave($insert) { if(parent::beforeSave($insert)){ if($this->isNewRecord){ $this->auth_key = \Yii::$app->security->generateRandomString(); } return true; } return false; } }</code>
views\my-authentication\login.php
<code><?php use \yii\bootstrap\ActiveForm; use \yii\helpers\Html; use \yii\bootstrap\Alert; ?> <?php if($error!=null){ echo Alert::widget(['options'=>['class'=>'alert-danger'],'body'=>$error]); }; ?> <?php if(Yii::$app->user->isGuest) { ?> <?php ActiveForm::begin() ?> <div class="form-group"> <?php echo Html::label('Username','username'); ?> <?php echo Html::textInput('username','',['class'=>'form-control']);?> </div> <div class="form-group"> <?php echo Html::label('Password','password'); ?> <?php echo Html::passwordInput('password','',['class'=>'form-control']); ?> </div> <?php echo Html::submitButton('Login',['class'=>'btn btn-primary']); ?> <?php ActiveForm::end(); ?> <?php } else {?> <h2>You are authentication!</h2> <br/><br/> <?php echo Html::a('logout',['my-authentication/logout'],['class'=>'btn btn-warning']); ?> <?php } ?></code>
SQL
<code>-- -- 表的结构 `user` -- CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `auth_key` varchar(32) NOT NULL, `password_hash` varchar(255) NOT NULL, `access_token` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; -- -- 转存表中的数据 `user` -- INSERT INTO `user` (`id`, `username`, `auth_key`, `password_hash`, `access_token`) VALUES (1, 'foo', '', '$2a$12$hL0rmIMjxhLqI.xr7jD1FugNWEgZNh62HuJj5.y34XBUfBWB4cppW', NULL);</code>
用户名是foo
,密码是foopassword
,登录后在Yii::$app->user->login($user);
时出现错误,
<code>public function getId() { return $this->getPrimaryKey(); }</code>
不是 PrimaryKey

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

CakePHP는 오픈 소스 MVC 프레임워크입니다. 이를 통해 애플리케이션 개발, 배포 및 유지 관리가 훨씬 쉬워집니다. CakePHP에는 가장 일반적인 작업의 과부하를 줄이기 위한 여러 라이브러리가 있습니다.

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다
