🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
在只能手机如此普及的今天,二维码作为推广的的展现,应用的越来越多了。一个二维码中可以蕴藏很多信息。那么,就让我来介绍一下,如何在 thinkphp5 框架中生成二维码。 ## 下载类库 前往[https://packagist.org](https://packagist.org/)搜索 phpqrcode ,我选择的是 ~~~ composer require aferrandini/phpqrcode ~~~ 打开 cmd 进入项目根目录,通过 composer 输入上面的命令 ![](https://box.kancloud.cn/d5b7ded44b3c6f95eb47a00fa53bc8f2_554x258.png) 等待完成即可。 ## 功能实现 在 common.php 中新建,生成二维码函数 ~~~ <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: 流年 <liu21st@gmail.com> // +---------------------------------------------------------------------- // 应用公共文件 /** * 功能:生成二维码 * @param string $qrData 手机扫描后要跳转的网址 * @param string $qrLevel 默认纠错比例 分为L、M、Q、H四个等级,H代表最高纠错能力 * @param string $qrSize 二维码图大小,1-10可选,数字越大图片尺寸越大 * @param string $savePath 图片存储路径 * @param string $savePrefix 图片名称前缀 */ function createQRcode($savePath, $qrData = 'PHP QR Code :)', $qrLevel = 'L', $qrSize = 4, $savePrefix = 'qrcode') { if (!isset($savePath)) return ''; //设置生成png图片的路径 $PNG_TEMP_DIR = $savePath; //检测并创建生成文件夹 if (!file_exists($PNG_TEMP_DIR)) { mkdir($PNG_TEMP_DIR); } $filename = $PNG_TEMP_DIR . 'test.png'; $errorCorrectionLevel = 'L'; if (isset($qrLevel) && in_array($qrLevel, ['L', 'M', 'Q', 'H'])) { $errorCorrectionLevel = $qrLevel; } $matrixPointSize = 4; if (isset($qrSize)) { $matrixPointSize = min(max((int)$qrSize, 1), 10); } if (isset($qrData)) { if (trim($qrData) == '') { die('data cannot be empty!'); } //生成文件名 文件路径+图片名字前缀+md5(名称)+.png $filename = $PNG_TEMP_DIR . $savePrefix . md5($qrData . '|' . $errorCorrectionLevel . '|' . $matrixPointSize) . '.png'; //开始生成 \PHPQRCode\QRcode::png($qrData, $filename, $errorCorrectionLevel, $matrixPointSize, 2); } else { //默认生成 \PHPQRCode\QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2); } if (file_exists($PNG_TEMP_DIR . basename($filename))) return basename($filename); else return FALSE; } ~~~ 在 Tools.php 中新建 qrcode 方法 ~~~ // 二维码 public function qrcode() { $savePath = APP_PATH . '/../Public/qrcode/'; $webPath = '/qrcode/'; $qrData = 'http://www.cnblogs.com/nickbai/'; $qrLevel = 'H'; $qrSize = '8'; $savePrefix = 'NickBai'; if($filename = createQRcode($savePath, $qrData, $qrLevel, $qrSize, $savePrefix)){ $pic = $webPath . $filename; } echo "<img src='".$pic."'>"; } ~~~ 访问[http://www.phper.com/index/tools/qrcode](http://www.phper.com/index/tools/qrcode)会在页面中显示这样的验证码 ![](https://box.kancloud.cn/bad90bf828aeee165a03737a6287e1f5_269x270.png)