二維碼(QR Code)廣泛應用於行動支付、登入驗證、產品追溯、活動報名等場景。PHP 生成二維碼主要有兩條路徑:**呼叫外部 API(如 Google Chart)** 快速原型、**本地類庫(PHP QR Code)** 離線可控。本文詳細對比兩者優劣、參數細節、POST/GET 兩種請求方式、完整可執行代碼與部署建議。
⚠️ 注意:Google 於 2019 年正式關閉 Image Charts API,以下代碼**僅供歷史參考**,新專案請改用方案二或其他現代 API(如 goqr.me、api.qrserver.com、自建服務)。
<?php
function generateQRfromGoogle($data, $widthHeight = 150, $EC_level = 'L', $margin = 0) {
$url = urlencode($data);
echo '
';
}
// 使用
$data = '版權所有:https://www.example.com';
generateQRfromGoogle($data);
?>
<?php
function qrcodePost($width, $height, $string) {
$post = [
'cht' => 'qr',
'chs' => "{$width}x{$height}",
'chl' => $string,
'choe' => 'UTF-8'
];
$ch = curl_init('https://chart.googleapis.com/chart');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($post),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
]);
$result = curl_exec($ch);
curl_close($ch);
return $result; // 回傳二進位圖片資料
}
// 使用:直接輸出圖片
header('Content-Type: image/png');
echo qrcodePost(300, 300, '版權所有:https://www.example.com');
?>
專案地址:sourceforge.net/projects/phpqrcode(LGPL 授權)
<?php include 'vendor/phpqrcode/phpqrcode.php'; // 或 qrlib.php $data = '版權所有:https://www.example.com'; $errorCorrectionLevel = 'L'; // L(7%) M(15%) Q(25%) H(30%) $matrixPointSize = 4; // 模組大小(像素),建議 3~10 $margin = 2; // 邊距(模組數) // 直接輸出至瀏覽器 QRcode::png($data, false, $errorCorrectionLevel, $matrixPointSize, $margin); // 或儲存檔案 QRcode::png($data, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, $margin); ?>
| 參數 | 類型 | 說明 | 建議值 |
|---|---|---|---|
| $text | string | 編碼內容(URL、文字、JSON 等) | 視需求 |
| $outfile | string/false | 儲存路徑;false 直接輸出 | false / 'path.png' |
| $level | string | 糾錯等級:L/M/Q/H | L (一般)、H (戶外/易損) |
| $size | int | 模組像素大小 | 4~6 |
| $margin | int | 邊距模組數 | 2~4 |
| $saveandprint | bool | 是否同時儲存並輸出 | false |
| $back_color | array | 背景色 RGB (0-255) | [255,255,255] |
| $fore_color | array | 前景色 RGB | [0,0,0] |
<?php
include 'vendor/phpqrcode/phpqrcode.php';
$data = 'https://www.example.com';
$tempFile = 'qr_raw.png';
QRcode::png($data, $tempFile, 'H', 6, 2); // 高糾錯為了嵌入 Logo
// 使用 GD 合成 Logo
$qr = imagecreatefrompng($tempFile);
$logo = imagecreatefrompng('logo.png');
$qrW = imagesx($qr); $qrH = imagesy($qr);
$logoW = imagesx($logo); $logoH = imagesy($logo);
$dstX = ($qrW - $logoW) / 2;
$dstY = ($qrH - $logoH) / 2;
imagecopy($qr, $logo, $dstX, $dstY, 0, 0, $logoW, $logoH);
header('Content-Type: image/png');
imagepng($qr);
imagedestroy($qr); imagedestroy($logo);
unlink($tempFile);
?>
| 維度 | Google Chart API (已停用) | PHP QR Code | 現代替代 API (goqr.me 等) |
|---|---|---|---|
| 離線可用 | ❌ | ✅ | ❌ |
| 資料隱私 | ❌ 經過第三方 | ✅ 本地生成 | ❌ |
| 生成速度 | 網路延遲 | 極快 (ms) | 網路延遲 |
| 自訂樣式 | 有限 | 支援顏色/Logo 合成 | 部分支援 |
| 維護狀態 | 已關閉 | 社群維護 | 商業/開源 |
| 推薦度 | ⭐ (僅舊專案) | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
https://api.qrserver.com/v1/create-qr-code/?data=...&size=200x200composer require endroid/qrcode,現代 PHP 封裝、支援 Twig、Symfony、Laravel 整合。