PHP 生成二维码并打包下载
1. composer安装qrcode
composer require 2amigos/qrcode-library
2. 生成二维码
use Da\QrCode\QrCode; public function getCode($code) { $dir = iconv("UTF-8", "GBK", './qrcode'); mkdir($dir, 0777, true); $url = Yii::$app->request->hostInfo . '/area?code=' . $code; //二维码内容自定义 $qrCode = (new QrCode($url)) ->setSize(250) ->setMargin(5) // ->setForegroundColor(51, 153, 255) // ->setBackgroundColor(51, 153, 255) ->writeFile(Yii::$app->basePath . '/web/qrcode/' . $code . '.png'); }
3.打包文件夹并下载
<?php namespace app\libs; class downLoadZip { public function downLoadFiles() { $exportPath = './qrcode'; $filename = $exportPath . '.zip'; $zip = new \ZipArchive(); //参数1:zip保存路径,参数2:ZIPARCHIVE::CREATE没有即是创建 if (!$zip->open($filename, \ZIPARCHIVE::CREATE)) { echo "创建[exportPath.zip]失败<br/>"; return; } //echo "创建[$exportPath.zip]成功<br/>"; $this->createZip(opendir($exportPath), $zip, $exportPath); $zip->close(); header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename=' . basename($filename)); //文件名 header("Content-Type: application/zip"); //zip格式的 header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件 header('Content-Length: ' . filesize($filename)); //告诉浏览器,文件大小 $this->deldir('./qrcode'); @readfile($filename); unlink('qrcode.zip'); //删除服务器压缩文件,释放服务器资源 } function createZip($openFile, $zipObj, $sourceAbso, $newRelat = '') { while (($file = readdir($openFile)) != false) { if ($file == "." || $file == "..") continue; /*源目录路径(绝对路径)*/ $sourceTemp = $sourceAbso . '/' . $file; /*目标目录路径(相对路径)*/ $newTemp = $newRelat == '' ? $file : $newRelat . '/' . $file; if (is_dir($sourceTemp)) { //echo '创建'.$newTemp.'文件夹<br/>'; $zipObj->addEmptyDir($newTemp);/*这里注意:php只需传递一个文件夹名称路径即可*/ $this->createZip(opendir($sourceTemp), $zipObj, $sourceTemp, $newTemp); } if (is_file($sourceTemp)) { //echo '创建'.$newTemp.'文件<br/>'; $zipObj->addFile($sourceTemp, $newTemp); } } } public function deldir($dir) { //先删除目录下的文件: $dh = opendir($dir); while ($file = readdir($dh)) { if ($file != "." && $file != "..") { $fullpath = $dir . "/" . $file; if (!is_dir($fullpath)) { unlink($fullpath); } else { $this->deldir($fullpath); } } } } }