PHP生成二维码demo

版权声明:本文为博主原创文章,未经博主允许不得转载。有问题可加微信meizu_mx4 https://blog.csdn.net/sinat_15955423/article/details/84794867

先说好用的二维码生成类库qr-code的github地址:https://github.com/endroid/qr-code

以tp5为例,我的环境是PHP7.2

使用方法:首先得安装过composer,然后在tp项目的根目录使用composer

composer require endroid/qr-code

它会自动把扩展放在vendor目录下面,vendor\endroid\qr-code里面。

如果你没有composer,你直接在github上面那个链接里下包也可以,然后把下载的包手动放在vendor目录下面。

亲测用composer下载扩展会下载一些别的东西,不知何用,为了简少vendor里面的无用扩展,不如直接下包放进去。

下面直接use这个类就能用了,附上代码:

<?php
/**
 * Created by PhpStorm.
 * User: 刘抱
 * Date: 2018/12/4
 * Time: 18:06
 */

namespace app\admin\controller;


use Endroid\QrCode\QrCode;

class Code extends Common
{
    function initialize()
    {
        parent::initialize();
    }

    /*
     * 生成二维码图片
     */
    public function qr_code()
    {
        $link = 'http://' . $_SERVER['HTTP_HOST'] . '/admin/index/index';
        $sha1 = sha1($link);
        $qrcode_dir = $_SERVER['DOCUMENT_ROOT'] . '/qrcode/' . substr($sha1, 0, 2) . '/' . substr($sha1, 2, 3) . '/';
        if (!file_exists($qrcode_dir)) mkdir($qrcode_dir, 0777, true);
        $file_name = $qrcode_dir . $sha1 . '.png';
        header('Content-Type: image/png');
        if (is_file($file_name)) {
            echo file_get_contents($file_name);
        } else {
            $qrCode = new QrCode($link);
            echo $qrCode->writeString();
            $qrCode->writeFile($file_name);
        }
        die();
    }

}

效果图

这个二维码就是$link的URL

然后图片也是能保存起来的

猜你喜欢

转载自blog.csdn.net/sinat_15955423/article/details/84794867
今日推荐