How to implement the scan function in php: 1. Generate a QR code, generate a unique identifier uuid, and use redis to save temporary information; 2. Maintain communication between user requests and the server through a long connection ;3. Use your mobile phone to scan the QR code to obtain the unique identifier uuid, and determine whether the identifier is valid.
#The operating environment of this article: Windows 7 system, PHP version 7.4, Dell G3 computer.
How to implement the scan function in php?
PHP scan code login
Scan code login specific implementation method
Scan code login specific implementation process:
(uuid is used as key, the corresponding value is set to -1, -1 means not scanned, the validity period of this identification is set to three minutes, and a QR code will be regenerated after expiration).
public function index(){ $uuid = self::createRandomStr('6'); $url = $this->code($uuid); //二维码链接地址 Redis::sAdd($uuid,'-1'); Redis::command('Expire',[$uuid,180]);//设置过期时间 return view('home.send.index',['url'=>$url,'uuid'=>$uuid]); } /** * 生成二维码url * @param $text */ public function code($uuid){ $host='http://'.$_SERVER["HTTP_HOST"].'/api/send'; $url='http://qr.liantu.com/api.php?text='.$host.'?uuid='.$uuid; return $url; }
(-1 is not scanned , 0 means that the user has scanned the QR code ps: when scanning the QR code again, the prompt has expired, and the remaining values represent the user's primary key id)
/** * 验证uuid是否过期 * @param Request $req * @return string|void */ public function confirm(Request $req){ $uuid = $req->uuid; $result = implode('',Redis::sort($uuid)); if($result == ''){//当uuid不存在时表示该标识已失效,重新生成二维码 return '该链接地址已过期'; } if($result == '-1'){ return ''; }elseif($result == '0'){ return '用户已扫描'; }else{ return '用户已确认登录';//获取用户的user_id 直接登录。 } }
public function index(Request $req){ $uuid = $req->uuid; $info = Code::getOne(['uuid'=>$uuid]); $result = implode('',Redis::sort($uuid)); if(!$result){ return $this->ajaxMsgError('该二维码已失效'); } Redis::sRem($code,'-1'); Redis::sadd($code ,0); return $this->ajaxMsgOk('扫描成功,请确认登录'); }
public function dologin(Request $req){ $user_id = $req->user_id; $uuid= $req->uuid; $user = User::getOne(['id'=>$user_id]); if($user){ if($user->status != 1){ return $this->ajaxMsgError('该用户已被禁用'); } Redis::sadd($uuid,$user_id); return $this->ajaxSuccess('登录成功'); }else{ //用户不存在 return $this->ajaxError('该用户不存在'); } }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement the scan function in php. For more information, please follow other related articles on the PHP Chinese website!