UCenter的登录和退出登录与其它操作不同,它多了一步返回js代码,然后你需要将代码添加到前端页面,才能运行。
本篇所有操作都在tp
项目下编辑。
复制下标1的,改成下标2再修改相关信息
新增登录方法
public function login()
{
$uid = uc_user_login('username', '1');
var_dump($uid[0]);
if ($uid > 0){
$result = uc_user_synlogin($uid[0]);
var_dump($result);
}
}
string(1) "8"是用户id。
这里注意了!虽然第二个srting为空,但是它实际上是string(280),我在这儿被坑了。按我的习惯就是一看到“”
就会觉得是没数据。。
我们加个htmlspecialchars
函数把它输出出来
public function login()
{
$uid = uc_user_login('username', '1');
var_dump($uid[0]);
if ($uid > 0){
$result = uc_user_synlogin($uid[0]);
var_dump(htmlspecialchars($result));
}
}
你可以复制src里的到浏览器运行,然后你会发现dz登录了!
但还没完,因为你现在是手动运行,你总不能反回这行,让用户自己操作吧?
那我们要如何把这js代码添加进前端页面呢?我们登录一般都是ajax请求吧?那本篇就以ajax来做示例。
新建index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="but">登录</button>
<div id="script"></div>
</body>
</html>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#but').click(function(){
$.post("{:url('index/index/login')}", '', function (data) {
$('#script').append(data);
})
});
</script>
修改login方法
public function login()
{
if (request()->isPost()) {
$uid = uc_user_login('username', '1');
if ($uid > 0){
$result = uc_user_synlogin($uid[0]);
return $result;
}
} else {
return $this->fetch();
}
}
dz退出登录
访问http://localhost/tp/public/index.php/index/index/login
点击tp的登录按钮,会发现已经同步登录了。
同步退出登录
在login.html新增退出登录按钮与ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="but">登录</button>
<button id="out">退出</button>
<div id="script"></div>
</body>
</html>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#but').click(function(){
$.post("{:url('index/index/login')}", '', function (data) {
$('#script').append(data);
})
});
$('#out').click(function(){
$.post("{:url('index/index/logout')}", '', function (data) {
$('#script').append(data);
})
});
</script>
新增方法
public function logout()
{
$result = uc_user_synlogout();
return $result;
}
点击退出按钮,成功退出登录!
然后玩几遍登录→退出。搞定!