在只能手機如此普及的今天,二維碼作為推廣的的展現,應用的越來越多了。一個二維碼中可以蘊藏很多信息。那么,就讓我來介紹一下,如何在 thinkphp5 框架中生成二維碼。
## 下載類庫
前往[https://packagist.org](https://packagist.org/)搜索 phpqrcode ,我選擇的是
~~~
composer require aferrandini/phpqrcode
~~~
打開 cmd 進入項目根目錄,通過 composer 輸入上面的命令

等待完成即可。
## 功能實現
在 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)會在頁面中顯示這樣的驗證碼
