ThinkPHP6通過Ucenter實現註冊登錄的示例代碼
在和ucenter通信成功後,實現註冊登錄就非常簡單瞭。簡要記錄如下。
1 新建一個controller用來繼承Ucenter\Controller\UcController,並新建構造方法,用來實例化UcController
<?php declare (strict_types = 1); namespace app\controller; use Ucenter\Controller\UcController; class uc extends UcController { /** * 構造方法,用於實例化 UcController */ public function __construct(){ $this->init(); } }
2 index controller添加uc類變量。
private $uc;
3 index方法中實例化uc控制器,對UCenter接口的操作通過$this->uc來完成。
$this->uc = new uc();
以上兩步完成後,就可以在代碼合適的地方調用ucenter接口進行註冊登錄瞭。以下是我項目中的代碼片段,僅供參考。
4 註冊時驗證用戶名是否已經存在以及是否合法
$username = $data['Content']; $result = $this->uc->uc_check_name($username); switch ($result) { case -1: $reason = "用戶名不合法"; break; case -2: $reason = "包含不允許註冊的詞語"; break; case -3: $reason = "用戶名已經存在"; break; } if ($result != 1) { $this->_resetStep(); return array(join("\n", array_merge(array('【註冊】註冊失敗', $reason), $this->_guestActions() )), 'text'); } else { $this->_setStep(self::STEP_REGISTER_PASSWORD); Session::set('username', $data['Content']); return array('【註冊】請輸入密碼', 'text'); } }
5 輸入密碼後調用ucenter進行註冊,因為ucenter註冊時必帶username,password,email,所以需要為用戶生成默認的email
//註冊->輸入密碼 if ($this->_currentStep() == self::STEP_REGISTER_PASSWORD) { $this->_resetStep(); Session::set('password', $data['Content']); //call ucenter to register user $username_valid = $this->uc->uc_check_name(Session::get('username')); Log::write('$username_valid' . $username_valid, 'debug'); if ($username_valid == 1) { //register Log::write('start register ' . Session::get('username'), 'debug'); $email = "reg_" . substr(Session::getId(), 0, 3) . time() . substr(Session::getId(), 7, 4) . "@null.null"; //$email = Session::get('username').'@'.Session::get('username').'.com'; $register_result = $this->uc->uc_register(Session::get('username'), Session::get('password'), $email); Log::write('register result is ' . $register_result, 'debug'); switch ($register_result) { case -1: $reason = "用戶名不合法"; break; case -2: $reason = "包含不允許註冊的詞語"; break; case -3: $reason = "用戶名已經存在"; break; case -4: $reason = "Email格式有誤"; break; case -5: $reason = "Email不允許註冊"; break; case -6: $reason = "該Email已經被註冊"; break; } if ($register_result > 0) { Log::write('Ucenter register successful' . Session::get('username'), 'debug'); return array(join("\n", array_merge(array('【註冊】註冊成功'), $this->_guestActions())), 'text'); } else { Log::write('Ucenter register failed' . $reason, 'debug'); $this->_resetSession(); return array(join("\n", array_merge(array('【註冊】註冊失敗', $reason), $this->_guestActions() )), 'text'); } } }
6 登錄時傳入用戶輸入的用戶名和密碼即可。登陸成功後將用戶名和密碼寫入session文件。
$result = $this->uc->uc_login(Session::get('username'), $data['Content']);
到此這篇關於ThinkPHP6通過Ucenter實現註冊登錄的示例代碼的文章就介紹到這瞭,更多相關ThinkPHP6 Ucenter註冊登錄內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!