thinkphp5.1+qrcode 二维码使用

1、注意:PHP版本 要求 7.1+

2、用composer 安装endroid/qrode ,进入项目根目录,安装完成会在vendor目录下面

composer require endroid/qrcode

3、将二维码生成封装为服务

位置:/application/common/service/QrcodeService.php

<?php
/**
 * 二维码服务
 */

namespace app\common\services;

use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;

class QrcodeService
{
    protected $_qr;
    protected $_encoding = 'UTF-8';              // 编码类型
    protected $_size = 300;                  // 二维码大小
    protected $_logo = false;                // 是否需要带logo的二维码
    protected $_logo_url = '';                   // logo图片路径
    protected $_logo_size = 80;                   // logo大小
    protected $_title = false;                // 是否需要二维码title
    protected $_title_content = '';                   // title内容
    protected $_generate = 'display';            // display-直接显示  writefile-写入文件
    protected $_file_name = './';                 // 写入文件路径
    const MARGIN = 10;                        // 二维码内容相对于整张图片的外边距
    const WRITE_NAME = 'png';                     // 写入文件的后缀名
    const FOREGROUND_COLOR = ['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0];          // 前景色
    const BACKGROUND_COLOR = ['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0];    // 背景色

    public function __construct($config)
    {
        isset($config['generate']) && $this->_generate = $config['generate'];
        isset($config['encoding']) && $this->_encoding = $config['encoding'];
        isset($config['size']) && $this->_size = $config['size'];
        isset($config['logo']) && $this->_logo = $config['logo'];
        isset($config['logo_url']) && $this->_logo_url = $config['logo_url'];
        isset($config['logo_size']) && $this->_logo_size = $config['logo_size'];
        isset($config['title']) && $this->_title = $config['title'];
        isset($config['title_content']) && $this->_title_content = $config['title_content'];
        isset($config['file_name']) && $this->_file_name = $config['file_name'];
    }

    /**
     * 生成二维码
     * @param $content //需要写入的内容
     * @return array | page input
     */
    public function createServer($content)
    {
        $this->_qr = new QrCode($content);
        $this->_qr->setSize($this->_size);
        $this->_qr->setWriterByName(self::WRITE_NAME);
        $this->_qr->setMargin(self::MARGIN);
        $this->_qr->setEncoding($this->_encoding);
        $this->_qr->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::HIGH));   // 容错率
        $this->_qr->setForegroundColor(self::FOREGROUND_COLOR);
        $this->_qr->setBackgroundColor(self::BACKGROUND_COLOR);
        // 是否需要title
        if ($this->_title) {
            $this->_qr->setLabel($this->_title_content, 16, null, LabelAlignment::CENTER);
        }
        // 是否需要logo
        if ($this->_logo) {
            $this->_qr->setLogoPath($this->_logo_url);
            $this->_qr->setLogoWidth($this->_logo_size);
        }

        $this->_qr->setValidateResult(false);

        if ($this->_generate == 'display') {
            // 展示二维码
            // 前端调用 例:<img src="https://localhost/qr.php?url=base64_url_string">
            header('Content-Type: ' . $this->_qr->getContentType());
            return $this->_qr->writeString();
        } else if ($this->_generate == 'writefile') {
            // 写入文件
            $file_name = $this->_file_name;
            return $this->generateImg($file_name);
        } else {
            return ['success' => false, 'message' => 'the generate type not found', 'data' => ''];
        }
    }

    /**
     * 生成文件
     * @param $file_name //目录文件 例: /tmp
     * @return array
     */
    public function generateImg($file_name)
    {
        $file_path = $file_name . DIRECTORY_SEPARATOR . uniqid() . '.' . self::WRITE_NAME;

        if (!file_exists($file_name)) {
            mkdir($file_name, 0777, true);
        }

        try {
            $this->_qr->writeFile($file_path);
            $data = [
                'url' => $file_path,
                'ext' => self::WRITE_NAME,
            ];
            return ['success' => true, 'message' => 'write qrimg success', 'data' => $data];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => $e->getMessage(), 'data' => ''];
        }
    }

}

4、控制器中使用

<?php
namespace app\index\controller;
use think\Queue;
use app\common\services\QrCodeService;
use think\Request;

class Index
{
    public function index()
    {
        // 自定义二维码配置
        $config = [
            'title'         => true, // 是否显示标题
            'title_content' => 'test_1',
            'logo'          => true, // 是否使用logo
            'logo_url'      => './static/1.jpg',
            'logo_size'     => 80,
        ];

        // 直接输出
        $qr_url = 'http://www.baidu.com?id=' . rand(1000, 9999);

        $qr_code = new QrCodeService($config);
        $qr_img = $qr_code->createServer($qr_url);
        echo $qr_img;

        // 写入文件
        $qr_url = '这是个测试二维码';
        $file_name = './static/qrcode';  // 定义保存目录
        $config['file_name'] = $file_name;
        $config['generate']  = 'writefile';

        $qr_code = new QrCodeService($config);
        $rs = $qr_code->createServer($qr_url);
        print_r($rs);

        exit;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ThinkPHP 5.1 可以使用 Workerman 实现实时推送功能,具体实现步骤如下: 1. 安装 Workerman 可以使用 Composer 安装 Workerman: ``` composer require workerman/workerman ``` 2. 创建 Workerman 控制器 在应用的 controller 目录下创建 Workerman 控制器,例如创建 `Push.php`,并在该控制器中实现推送功能: ```php namespace app\controller; use think\worker\Server; class Push extends Server { // 监听的地址和端口号 protected $socket = 'websocket://0.0.0.0:2346'; // 接收到客户端消息时触发 public function onMessage($connection, $data) { // 将客户端发送的消息广播给所有客户端 foreach ($this->worker->connections as $conn) { $conn->send($data); } } } ``` 3. 在路由中定义 Workerman 路由 在 `route` 目录下的 `route.php` 文件中定义 Workerman 路由,例如: ```php use think\facade\Route; // 定义 Workerman 路由 Route::get('push', 'push/index'); ``` 4. 启动 Workerman 服务 在命令行中使用以下命令启动 Workerman 服务: ``` php think worker:server ``` 5. 在页面中调用推送接口 在需要推送消息的页面中,调用推送接口,例如: ```javascript var ws = new WebSocket('ws://localhost:2346'); ws.onopen = function() { ws.send('Hello, Workerman!'); }; ws.onmessage = function(event) { console.log(event.data); }; ``` 以上就是使用 ThinkPHP 5.1 实现 Workerman 的推送功能的步骤。需要注意的是,在使用 Workerman 时需要开启 PHP 的长连接,因此需要使用 CLI 环境运行 PHP。此外,需要在浏览器中测试推送功能时,需要使用支持 WebSocket 的浏览器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值