This article brings you how to generate a QR code under the thinkphp5 framework? (code), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Without further ado, let’s start with the code:
The first type: No need to save the file locally, display it directly on the front page:
This is the content in the controller, Oh, yes, first download the SDK: .phpqrcode class file download, download address: https://sourceforge.net/projects/phpqrcode/
Plug-in only needs: The downloaded class file is a compressed package, It contains many files and demonstration programs. We only need the phpqrcode.php file inside to generate a QR code. It is a collection file of multiple classes. We need to use the png() method (line 3090) of the QRcode class (line 2963) inside.
The file is placed in the framework extend file. You can name the folder yourself. Mine is PhpQrcode. The file inside is: phpqrcode.php
<?php namespace app\index\controller; use think\Controller; use think\Loader; Loader::import('PhpQrcode.phpqrcode',EXTEND_PATH,'.php'); class Index extends Controller { //ajax访问 //通过链接生成二维码 public function code($url = "http://www.baidu.com") { $qrcode = new \QRcode(); // $qrimage = new \QRimage(); $value = $url; //二维码内容 $errorCorrectionLevel = 'H'; //容错级别 $matrixPointSize = 6; //生成图片大小 ob_start(); $qrcode::png($value,false , $errorCorrectionLevel, $matrixPointSize, 2); // $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2); //这里就是把生成的图片流从缓冲区保存到内存对象上,使用base64_encode变成编码字符串,通过json返回给页面。 $imageString = base64_encode(ob_get_contents()); //关闭缓冲区 ob_end_clean(); //把生成的base64字符串返回给前端 $data = array( 'code'=>200, 'data'=>$imageString ); return json($data); } }
Front-end file: Of course, I use The jquery is relatively old, so you can modify it yourself if you use jquery:
<div id="logos"> <button onclick="changess()">点击</button> <img src="" class="qrcode" alt="二维码展示"/> </div> <script type="text/javascript" src="__INDEX__js/jquery.js"></script> <script type="text/javascript"> function changess() { var logos = document.getElementById ('logos'); $.ajax({ type: "GET", url: "code.html", data: '', dataType: "json", success: function(r){ if (r.code==200) { //console.log(r); var path = 'data:image/png;base64,'+r.data; //给img的sec赋值。 console.log(path); $("#logos").html("<img src="+path+">"); logos.html("<img src="+path+">"); console.log( logos.html("<img src="+path+">")); }else{ alert(r.err); } } }); } </script>
The above is the detailed content of How to generate a QR code under the thinkphp5 framework? (code). For more information, please follow other related articles on the PHP Chinese website!