- Saved searches
- Use saved searches to filter your results more quickly
- License
- splitbrain/php-qrcode
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Генерация QR-кода в PHP
- Быстрый старт
- Вывод в браузер:
- Сохранение в файл:
- Описание параметров
- Данные в QR-коде
- Набрать номер телефона:
- Написать SMS:
- Добавить контакт:
- Email:
- Мессенджеры:
- Прозрачный фон
- Изменить цвет фона
- Изменить цвет пикселей
- Инверсия цветов
- Логотип в центре
- Генерируем QR-код на PHP
- Saved searches
- Use saved searches to filter your results more quickly
- License
- Licenses found
- chillerlan/php-qrcode
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
barcode.php — Generate QR Code from a single PHP file. MIT license.
License
splitbrain/php-qrcode
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Generate SVG QR Codes. MIT license.
composer require splitbrain/php-qrcode
use splitbrain\phpQRCode\QRCode; echo QRCode::svg('hello world');
The above will directly output the generated SVG file. This file has no styles attached. Use CSS to style howver you want it:
s — Symbology (type of QR code). One of:
Генерация QR-кода в PHP
Вопрос генерации QR-кодов в PHP достаточно освещён, есть много библиотек, одной из них является «PHP QR Code» – быстрый и легкий класс, рассмотрим его применение совместно с графической библиотекой GD.
Быстрый старт
Вывод в браузер:
require_once __DIR__ . '/phpqrcode/qrlib.php'; QRcode::png('https://snipp.ru/');
Сохранение в файл:
require_once __DIR__ . '/phpqrcode/qrlib.php'; QRcode::png('https://snipp.ru/', __DIR__ . '/qr.png');
Описание параметров
QRcode::png($text, $outfile, $level, $size, $margin, $saveandprint);
$text – текст, который будет закодирован в изображении. $outfile – куда сохранить файл, false – вывести в браузер. $level – уровень коррекции ошибок:
Значение | Уровень | Процент восстановления |
---|---|---|
L | Низкий (по умолчанию) | 7% |
M | Средний | 15% |
Q | Четверть | 25% |
H | Высокий | 30% |
$margin – отступ от краев, задаётся в единицах, указанных в $size . $saveandprint – если true , то изображение одновременно сохранится в файле $outfile и выведется в браузер.
Данные в QR-коде
Для мобильных устройств, в данных можно использовать «протоколы приложений», тем самым при распознавании QR-кода сразу открыть нужное приложение, например набрать телефонный номер, написать письмо, открыть диалог в WhatsApp или Viber и т.д.
Набрать номер телефона:
$text = 'tel:+7903xxxxxxx'; QRcode::png($text);
Написать SMS:
$text = 'sms:+7903xxxxxxx'; QRcode::png($text);
Добавить контакт:
$name = 'Иван Иванов'; $phone = '+7903xxxxxxx'; $text = 'BEGIN:VCARD' . "\n"; $text .= 'FN:' . $name . "\n"; $text .= 'TEL;WORK;VOICE:' . $phone . "\n"; $text .= 'END:VCARD'; QRcode::png($text);
Email:
$text = 'mailto:mail@example.com?subject=Тема письма'; QRcode::png($text);
Мессенджеры:
/* WhatsApp */ $text = 'whatsapp://send?phone=+7903xxxxxxx'; QRcode::png($text); /* Viber */ $text = 'viber://chat?number=+7903xxxxxxx'; QRcode::png($text); /* Skype */ $text = 'skype://логин?call'; QRcode::png($text);
Прозрачный фон
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP', __DIR__ . '/tmp.png', 'M', 6, 2); /* Замена белых пикселей на прозрачный */ $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); $bg_color = imageColorAllocate($im, 0, 0, 0); imagecolortransparent ($im, $bg_color); for ($x = 0; $x < $width; $x++) < for ($y = 0; $y < $height; $y++) < $color = imagecolorat($im, $x, $y); if ($color == 0) < imageSetPixel($im, $x, $y, $bg_color); >> > /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Изменить цвет фона
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'M', 6, 2); $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); /* Цвет фона в RGB */ $bg_color = imageColorAllocate($im, 255, 145, 43); for ($x = 0; $x < $width; $x++) < for ($y = 0; $y < $height; $y++) < $color = imagecolorat($im, $x, $y); if ($color == 0) < imageSetPixel($im, $x, $y, $bg_color); >> > /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Изменить цвет пикселей
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'M', 6, 2); $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); /* Цвет в RGB */ $fg_color = imageColorAllocate($im, 0, 133, 178); for ($x = 0; $x < $width; $x++) < for ($y = 0; $y < $height; $y++) < $color = imagecolorat($im, $x, $y); if ($color == 1) < imageSetPixel($im, $x, $y, $fg_color); >> > /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Инверсия цветов
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'M', 6, 2); $im = imagecreatefrompng(__DIR__ . '/tmp.png'); imagefilter($im, IMG_FILTER_NEGATE); /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($im);
Логотип в центре
Если у QR-кода поднять уровень коррекции ошибок до максимального, то можно спокойно вставить логотип без потери читаемости. Phpqrcode генерирует изображение в формате PNG-8, поэтому потребуется преобразовать его в PNG-24, чтобы избежать потерю цветов у логотипа.
require_once __DIR__ . '/phpqrcode/qrlib.php'; /* Генерация QR-кода во временный файл */ QRcode::png('QR-код сгенерированный в PHP - Snipp.ru', __DIR__ . '/tmp.png', 'H', 6, 2); /* Конвертация PNG8 в PNG24 */ $im = imagecreatefrompng(__DIR__ . '/tmp.png'); $width = imagesx($im); $height = imagesy($im); $dst = imagecreatetruecolor($width, $height); imagecopy($dst, $im, 0, 0, 0, 0, $width, $height); imagedestroy($im); /* Наложение логотипа */ $logo = imagecreatefrompng(__DIR__ . '/logo.png'); $logo_width = imagesx($logo); $logo_height = imagesy($logo); $new_width = $width / 3; $new_height = $logo_height / ($logo_width / $new_width); $x = ceil(($width - $new_width) / 2); $y = ceil(($height - $new_height) / 2); imagecopyresampled($dst, $logo, $x, $y, 0, 0, $new_width, $new_height, $logo_width, $logo_height); /* Вывод в браузер */ header('Content-Type: image/x-png'); imagepng($dst);
Генерируем QR-код на PHP
QR-code, уже давно распространен повсеместно, во всех сферах человеческой жизни. Вроде такая популярная вещь, а нормальной библиотеки (Open Source) на PHP — нет. Товарища deltalab, очень напрягла эта проблема и он решил переписать имеющиеся в наличии С библиотеки ibqrencode от Kentaro Fukuchi, на более привычный ему язык PHP.
PHP QR-Code c открытым исходным кодом (LGPL) библиотека для создание QR code и 2-х мерных штрих-кодов. Базируется на коде ibqrencode библиотеки на C. Обеспечивает API для создания штрихкодов в формате PNG, JPEG с помощью GD2. Реализовано на чистом PHP, без каких-либо внешних зависимостей, кроме конечно GD2.
UPD:
— Что такое QR можно узнать на из Википедии
— Тематический блог на Хабре, где можно постичь масштабы его распространения
— Интересный QR-генератор, с расширенным функционалом PHP QR Code and Data Matrix Generator
— Генератор «красивых» QR, вставка текста в QR mojiq.kazina.com
— Онлайн QR декодер QRDecoder
— Еще одна реализация QR кодирования на Perl+PHP www.swetake.com/qr/qr_cgi_e.html
— QR code плагин для WordPress anton.shevchuk.name/wordpress/qr-code
— PHP-класс для генерации QR-кода от Павла Новицкого www.e-luge.net/blog/full/655063.html
— MX QR code под ExpressionEngine. Базируется на коде от Swetake — MX QR code
— QR-code модуль для Drupal drupal.org/project/qrs_sheets
— Кодируем в QR с помощь Google Charts API
UPD2:
— Самая лучшая считывалка QR-code с экрана BarShow и лучший генератор BarCapture от Jaxo Systems. Написано на Java так-что для пользователей Linux/MacOS в самый раз, есть и бинарники.
— Расширенная утилита для считывания с Web-камеры bcWebCam
— Еще одна считывалка QR-code прямо с экрана, без телефона QuickMark прямая ссылка ~7mb
nzeraf.com
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A QR code generator and reader with a user friendly API. PHP 7.4+
License
Apache-2.0, MIT licenses found
Licenses found
chillerlan/php-qrcode
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A PHP QR Code generator based on the implementation by Kazuhiko Arase, namespaced, cleaned up, improved and other stuff.
It also features a QR Code reader based on a PHP port of the ZXing library.
Hi! Please check out the v5.0-beta release and leave your feedback in this discussion thread. Thanks!
Attention: there is now also a javascript port: chillerlan/js-qrcode.
- Creation of Model 2 QR Codes, Version 1 to 40
- ECC Levels L/M/Q/H supported
- Mixed mode support (encoding modes can be combined within a QR symbol). Supported modes:
- numeric
- alphanumeric
- 8-bit binary
- 13-bit double-byte:
- kanji (Japanese, Shift-JIS)
- hanzi (simplified Chinese, GB2312/GB18030) as defined in GBT18284-2000
- GdImage
- ImageMagick
- Markup types: SVG, HTML, etc.
- String types: JSON, plain text, etc.
- Encapsulated Postscript (EPS)
- PDF via FPDF
- PHP 7.4+
- ext-mbstring
- optional:
- ext-fileinfo (required by QRImagick output)
- ext-gd
- ext-imagick with ImageMagick installed
- setasign/fpdf for the PDF output module
For the QRCode reader, either ext-gd or ext-imagick is required!
- The user manual is at https://php-qrcode.readthedocs.io/ (sources)
- An API documentation created with phpDocumentor can be found at https://chillerlan.github.io/php-qrcode/
- The documentation for QROptions container can be found here: chillerlan/php-settings-container
composer require chillerlan/php-qrcode
< "require": < "php": "^7.4 || ^8.0", "chillerlan/php-qrcode": "dev-main#" > >
Note: replace dev-main with a version constraint, e.g. ^4.3 — see releases for valid versions.
We want to encode this URI for a mobile authenticator into a QRcode image:
$data = 'otpauth://totp/test?secret=B3JX4VCVJDVNXNZ5&issuer=chillerlan.net'; // quick and simple: echo '
new QRCode)->render($data).'" alt="QR Code" />';
Wait, what was that? Please again, slower! See Advanced usage in the manual. Also, have a look in the examples folder for some more usage examples.
Using the built-in QR Code reader is pretty straight-forward:
// it's generally a good idea to wrap the reader in a try/catch block because it WILL throw eventually try< $result = (new QRCode)->readFromFile('path/to/file.png'); // -> DecoderResult // you can now use the result instance. $content = $result->data; $matrix = $result->getMatrix(); // -> QRMatrix // . or simply cast it to string to get the content: $content = (string)$result; > catch(Throwable $e)< // oopsies! >
Hi, please check out some of my other projects that are way cooler than qrcodes!
- js-qrcode — a javascript port of this library
- php-authenticator — a Google Authenticator implementation (see authenticator example)
- php-httpinterface — a PSR-7/15/17/18 implemetation
- php-oauth-core — an OAuth 1/2 client library along with a bunch of providers
- php-database — a database client & querybuilder for MySQL, Postgres, SQLite, MSSQL, Firebird
- php-tootbot — a Mastodon bot library (see @dwil)
I don’t take responsibility for molten CPUs, misled applications, failed log-ins etc.. Use at your own risk!
The word «QR Code» is a registered trademark of DENSO WAVE INCORPORATED
https://www.qrcode.com/en/faq.html#patentH2TitleAbout
A QR code generator and reader with a user friendly API. PHP 7.4+