文章目錄
安裝endroid/qr-code
環境PHP7.4+Codeigniter2
使用 codeigniter2,用舊的框架,原本就有其包袱,特別是在預算有限,經費有限的情況下。
讓本地端可以執行qrcode產生的功能
安裝 endroid/qr–code version 4.6.1
安裝的路徑
/application/third_party
terminal指令
composer require endroid/qr-code:4.6.1
composer如何安裝特定版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
安裝vendor/package的1.2.3版本: composer require vendor/package:1.2.3 安裝vendor/package的1.2.3版本或以上版本,但小於2.0.0: composer require vendor/package:^1.2.3 安裝vendor/package的最新1.2.x版本: composer require vendor/package:~1.2.3 安裝vendor/package的2.0.0版本或以上版本: composer require vendor/package:>=2.0.0 |
接著重點來了,如何讓它運作?
Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); use Endroid\QrCode\Builder\Builder; use Endroid\QrCode\Writer\PngWriter; use Endroid\QrCode\Encoding\Encoding; use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh; class qr_code_model extends CI_Model { public function __construct() { parent::__construct(); // 確保已引入Composer的自動載入文件 require_once APPPATH . 'third_party/vendor/autoload.php'; } public function generate_qr_code($text) { // 建構QR碼 $result = Builder::create() ->writer(new PngWriter()) ->data($text) ->encoding(new Encoding('UTF-8')) ->errorCorrectionLevel(new ErrorCorrectionLevelHigh()) ->size(300) ->margin(10) ->build(); // 產生二進位字串(適用於直接輸出到瀏覽器) return $result->getString(); } public function get_qr_code_content_type() { // 產生並返回內容類型(適用於設定回應頭) $result = Builder::create()->build(); return $result->getMimeType(); } } |
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Qr_test extends CI_Controller { public function index() { $this->load->model('qr_code_model'); $qrCodeImage = $this->qr_code_model->generate_qr_code('Hello CodeIgniter!'); $contentType = $this->qr_code_model->get_qr_code_content_type(); header('Content-Type: ' . $contentType); echo $qrCodeImage; } } |