Documentation menu
On this page
Packages · v2.x
QrCode
The QrCode package (src/packages/QrCode) generates QR codes and reads them, without any dependency: encoder written in PHP (ISO/IEC 18004, versions 1 to 40), SVG images (PNG with the gd extension), contents signed with APP_SECRET that can expire, rotate or be used once, and a short code for every QR code that must be read: when the camera cannot scan it, the code printed under it (e.g. 7Q2K-4MXA) is typed instead and gives the same result.
The reader is the <neo-qr-reader> element: the browser decodes the camera image (BarcodeDetector API), the server verifies what was scanned or typed and answers in JSON.
Module
| Manager | NeoPHP\Package\QrCode\QrCodeManager (final) |
| Interface | NeoPHP\Package\QrCode\QrCodeManagerInterface |
| Attribute | #[Package(provider: QrCodeProvider::class, requires: [CacheManager::class])] |
| Requires | Cache component (short codes and image URLs); APP_SECRET (signed QR codes and short codes); PHP extension gd for the PNG images only |
Inject QrCodeManagerInterface in a service, a command or a controller:
use NeoPHP\Package\QrCode\QrCodeManagerInterface;
public function __construct(private QrCodeManagerInterface $qrCodes)
{
}
Quick start
A ticket that changes every 30 seconds, displayed with its short code:
#[Route('/tickets/{id}', name: 'ticket_show')]
public function show(Ticket $ticket): Response
{
$qr = $this->signedQrCode(['ticket' => $ticket->getNumber()], rotate: 30);
return $this->render('ticket/show.html.twig', ['qr' => $qr]);
}
{{ qr.toSvg()|raw }}
<p>Code: <strong>{{ qr.code }}</strong></p>
The scanner of the organizer, and the endpoint that checks the tickets:
{{ qr_reader(path('ticket_scan'), { csrf_token: csrf_token('scan') }) }}
#[Route('/scan', name: 'ticket_scan', methods: ['POST'])]
public function scan(Request $request): JsonResponse
{
$this->denyAccessUnlessGranted('ROLE_ORGANIZER');
$payload = $request->toArray();
$result = $this->readQrCode((string) ($payload['content'] ?? ''), $payload['source'] ?? null);
if (!$result->isValid() || !$result->isSigned()) {
return $this->qrCodeReadResponse($result);
}
$ticket = $this->getRepository(Ticket::class)->findOneBy(['number' => $result->getData()['ticket']]);
return $this->json(['valid' => $ticket !== null, 'name' => $ticket?->getHolder()->getName()]);
}
The reader sends what the camera scanned or what was typed ({"content": "NQR1....", "source": "qr"} or {"content": "7Q2K-4MXA", "source": "code"}): readQrCode() gives the same result in both cases. Any readable QR code is valid (a URL, a text): isSigned() makes sure it is a ticket issued by the site.
Configuration
config/packages/qr_code.yaml (generated by neo install):
| Key | Default | |
|---|---|---|
path |
/_qr |
URL path of the routes of the package |
cache_pool |
~ |
Cache pool of the short codes and of the image URLs (~ = default pool). The array adapter only lives during one request |
image_ttl |
86400 |
Seconds during which an image URL of qr_code_url() stays valid |
defaults.size |
300 |
Width and height in pixels (21 to 4096) |
defaults.margin |
4 |
Quiet zone in modules (4 recommended) |
defaults.error_correction |
medium |
low (7 %), medium (15 %), quartile (25 %), high (30 %) |
defaults.foreground / background |
#000000 / #FFFFFF |
#RGB or #RRGGBB, the background can be transparent |
code.length |
8 |
Characters of the short codes (6 to 16) |
code.ttl |
2592000 |
Lifetime of the short code of a fixed content (30 days, ~ = as long as the cache keeps it) |
signed.ttl |
~ |
Lifetime of a signed QR code without ttl or rotate (~ = never expires) |
signed.leeway |
5 |
Seconds of tolerance after the expiration |
reader.route |
false |
Adds the public POST {path}/read endpoint (see Security) |
Generating a QR code
$qr = $this->qrCodes->create('https://toapp.fr/e/brunch-42', ['size' => 400]);
$qr->toSvg(); // <svg ...>, no dependency
$qr->toPng(); // PNG binary (gd)
$qr->toDataUri(); // data:image/svg+xml;base64,... for an <img src>
$qr->toDataUri('png');
$qr->render('png'); // svg or png
$qr->toTerminal(); // drawing in Unicode blocks for a console
Options of create() (and of every builder below): size, margin, error_correction, foreground, background, logo (path of an SVG, PNG, JPEG, WebP or GIF file; SVG only in the SVG rendering), logo_size (0.1 to 0.3 of the width) and code (true or a lifetime in seconds: registers the short code). The same options can be changed on the model before the first rendering:
$qr = $this->qrCodes->create('https://toapp.fr')
->size(600)
->colors('#111318', '#FFF1E8')
->logo($this->projectDir . '/public/logo.png', 0.22);
A logo hides the middle of the code: the error correction becomes high automatically.
The encoder chooses the most compact mode (numeric, alphanumeric or byte in UTF-8), the smallest version that holds the content, raises the error correction when it does not make the code bigger, and keeps the mask with the lowest penalty. getMatrix() returns the modules (Encoder\Matrix: getSize(), isDark($x, $y), getVersion(), getErrorCorrection(), getMask()).
Contents recognized by the phones:
| Method | Content |
|---|---|
wifi($ssid, $password, 'WPA', $hidden) |
WIFI:T:WPA;S:...;P:...;; (joins the network) |
vcard(['name' => ..., 'phone' => ..., 'email' => ..., 'organization' => ..., 'title' => ..., 'url' => ..., 'address' => ..., 'note' => ...]) |
vCard 3.0 (adds the contact) |
email($to, $subject, $body) |
mailto: |
phone($number) |
tel: |
sms($number, $message) |
SMSTO: |
geo($latitude, $longitude) |
geo: (opens the map) |
json($data) |
JSON text |
Signed QR codes
signed() puts data signed with APP_SECRET in the QR code: NQR1.<data in base64url JSON>.<HMAC-SHA256 signature>. Nobody can forge one or change the data, and the expiration is part of the signed data.
// Valid one hour
$qr = $this->qrCodes->signed(['invitation' => 18], ttl: 3600);
// Changes every 30 seconds: a screenshot sent to a friend is useless a few seconds later
$qr = $this->qrCodes->signed(['ticket' => 'TA-7Q2-0042'], rotate: 30);
// Refused after its first valid read
$qr = $this->qrCodes->signed(['voucher' => 'DRINK-12'], ttl: 86400, once: true);
$qr->getExpiresAt(); // DateTimeImmutable or null
$qr->getCode(); // 8352-QG0V: a signed QR code always has a short code
With rotate, the content is the same during a window of rotate seconds: refresh the image on the page of the participant, for example every rotate seconds with a route that returns qrCodeResponse() and a header with the new code:
#[Route('/tickets/{id}/qr.svg', name: 'ticket_qr')]
public function qr(Ticket $ticket): Response
{
$qr = $this->signedQrCode(['ticket' => $ticket->getNumber()], rotate: 30);
$response = $this->qrCodeResponse($qr);
$response->setHeader('X-QR-Code', (string) $qr->getCode());
return $response;
}
The data is readable by anyone who scans the code (base64url is not encryption): put an identifier in it, never a secret or personal data.
Short codes
Every QR code that must be read can have a short code of 8 characters (Crockford base 32: digits and letters without I, L, O, U), displayed by groups of 4: 7Q2K-4MXA. It is typed when the camera does not work, the screen is broken or the QR code is unreadable, and read() returns exactly what the QR code would have returned.
signed()always registers the code, until the expiration of the QR code (plusleeway).create($content, ['code' => true])orcode($content, $ttl)registers the code of any content (code.ttlby default).qr_code_short(content)displays it in a template.
The code is derived from the content with APP_SECRET (the same content always gives the same code) and kept in the cache pool: it can only be guessed by trying, and 8 characters give 2^40 combinations. When typing, the separators and spaces are ignored, lower case is accepted, and O, I, L are read as 0, 1, 1.
Reading a QR code
read() accepts what a reader scanned or a typed short code and returns a Model\ReadResult. The second argument tells where the input comes from: qr (scanned: never read as a short code, even when the content looks like one), code (typed: only a short code) or null (guessed). <neo-qr-reader> sends it as source:
$result = $this->qrCodes->read($input, $source);
$result->isValid(); // false: unknown code, invalid signature, expired, already used
$result->getSource(); // qr (scanned) or code (typed)
$result->getType(); // signed, url, email, phone, sms, wifi, vcard, geo, json or text
$result->getData(); // data of signed(), decoded JSON, fields of a Wi-Fi network or a vCard...
$result->getContent(); // raw content
$result->getCode(); // short code
$result->getExpiresAt(); // DateTimeImmutable of a signed QR code
$result->getError(); // ReadResult::ERROR_* or null
$result->toArray(); // JSON of the endpoint
{
"valid": true,
"source": "code",
"type": "signed",
"signed": true,
"data": {"ticket": "TA-7Q2-0042"},
"content": "NQR1.eyJkIjp7InRpY2tldCI6IlRBLTdRMi0wMDQyIn0sImUiOjE3NTAwMDAwMzB9.6Hw-tPinbtcUEQUH-95EYQ",
"code": "8352-QG0V",
"expires_at": "2026-06-13T20:41:30+00:00",
"error": null,
"message": null
}
| Error | When |
|---|---|
empty |
Nothing scanned or typed |
unknown_code |
Short code never registered or expired |
invalid_signature |
Signed content forged, modified, or signed with another APP_SECRET |
expired |
Signed QR code read after its expiration plus leeway |
already_used |
Signed QR code created with once: true, already read |
getMessage() gives an English message for the error: translate the error code in the application.
The decoding of the image happens in the browser: the server never receives a photo, only the text read by the camera.
The reader element
qr_reader() writes the <neo-qr-reader> element and its script ({path}/reader.js, served by the package):
{{ qr_reader(path('ticket_scan'), {
csrf_token: csrf_token('scan'),
label_manual: 'Saisir le code',
label_submit: 'Vérifier',
label_placeholder: 'Code sous le QR code',
}) }}
- The camera starts at once (
autostart: falseto wait for the button), back camera of the phones by default (facing: 'user'for the front one), torch button when the phone has one. - The browser decodes the image with the
BarcodeDetectorAPI (Chrome, Edge, Android, Safari 17+). Without it, or when the camera is refused, the element shows the manual entry of the short code with an explanation. - The Type the code button always opens the manual entry: the typed code is formatted while typing (
7Q2K-4MXA). manual: 'only'shows only the manual entry,manual: falsehides it.- Each scan or code is sent in
POSTto the endpoint as JSON ({"content": "...", "source": "qr"}), with the CSRF token in theX-CSRF-Tokenheader (csrf_headerto change it). The same content is not sent twice duringcooldownmilliseconds (2500). - The answer colors the frame (
data-state="valid"/"invalid"when the status is 2xx / not 2xx orvalidisfalse), displays itsmessageand makes the phone vibrate.
Options: id, class, cooldown, facing, autostart, manual, csrf_token, csrf_header, label_start, label_stop, label_torch, label_manual, label_submit, label_placeholder, label_unsupported, label_denied.
Events (they bubble):
const reader = document.querySelector('neo-qr-reader');
reader.addEventListener('qr-scan', (event) => {
// event.detail.content, event.detail.source (qr or code)
// event.preventDefault() keeps the content in the page instead of sending it
});
reader.addEventListener('qr-result', (event) => {
// event.detail.result (JSON of the endpoint), event.detail.status
});
reader.addEventListener('qr-error', (event) => console.warn(event.detail.error));
Without endpoint (qr_reader()), only the qr-scan event is dispatched. Methods: reader.start(), reader.stop(), reader.submit(content, source).
Styles: the element uses a shadow DOM; change --qr-accent, --qr-valid, --qr-invalid, --qr-radius or the parts camera, video, frame, status, tools, form, input, submit and message:
neo-qr-reader { --qr-accent: #C2410C; --qr-radius: 24px; }
neo-qr-reader::part(input) { font-family: monospace; }
The camera needs HTTPS (or localhost). The security headers of config/framework/app.yaml forbid the camera by default (Permissions-Policy: camera=()): the package allows it (camera=(self)) on the HTML pages that hold a <neo-qr-reader> only, the other directives and the other pages keep the configured policy.
The element is 480 pixels wide at most: neo-qr-reader { max-width: none; } lets it fill its container.
Templates
| Function | Result |
|---|---|
qr_code(content, options) |
The QR code as inline SVG |
qr_code_url(content, options, format) |
URL of the image (svg or png), served by {path}/{key}.{format} and cached by the browser |
qr_code_short(content, ttl) |
Short code of the content (registers it) |
qr_reader(endpoint, options) |
<neo-qr-reader> element and its script |
{{ qr_code(url('event_show', { id: event.id }), { size: 200, foreground: '#111318' }) }}
<img src="{{ qr_code_url('https://toapp.fr', {}, 'png') }}" alt="QR code" width="300" height="300">
<p>{{ qr_code_short(invitation.url) }}</p>
A model of create() or signed() passed to a template: {{ qr.toSvg()|raw }}, {{ qr.code }}, {{ qr.expiresAt|date('H:i:s') }}.
Controllers
AbstractController uses the QrCodeController trait:
| Method | |
|---|---|
qrCode($content, $options) |
create() |
signedQrCode($data, $rotate, $ttl, $once, $options) |
signed() |
readQrCode($input, $source) |
read() |
qrCodeResponse($qrCodeOrContent, 'svg') |
Image response (svg or png, Cache-Control: no-store) |
qrCodeReadResponse($resultOrInput) |
JSON response of a read: 200 when valid, 422 otherwise |
Commands
| Command | |
|---|---|
qr:generate <content> |
Draws the QR code in the console, or writes it with --output=file.svg|file.png; --size, --error-correction, --code, --signed (a JSON content is decoded), --rotate, --ttl, --once. Prints the version, the error correction, the short code and the expiration |
qr:read <input> |
Prints the read() result of a content or a short code in JSON; exit code 1 when not valid |
php bin/neo qr:generate "https://toapp.fr" --output=public/qr.png --size=600
php bin/neo qr:generate '{"ticket": "TA-0042"}' --signed --ttl=3600
php bin/neo qr:read 8352-QG0V
QrCodeManagerInterface
| Method | |
|---|---|
create(string $content, array $options = []): QrCode |
QR code of a text |
signed(mixed $data, ?int $rotate = null, ?int $ttl = null, bool $once = false, array $options = []): QrCode |
Signed QR code with its short code |
wifi(), vcard(), email(), phone(), sms(), geo(), json() |
Contents recognized by the phones |
code(string $content, ?int $ttl = null): string |
Registers and returns the short code of a content |
read(string $input, ?string $source = null): ReadResult |
Reads a scanned content (qr) or a short code (code) |
imageUrl(string $content, array $options = [], string $format = 'svg'): string |
URL of the cached image |
fromImageKey(string $key): ?QrCode |
QR code of an image URL |
getPath(), getReaderScript(), getReaderScriptUrl(), getConfig() |
Routes, script and configuration |
Security
- Keep the reading endpoint behind a role. A controller of the application that calls
readQrCode()afterdenyAccessUnlessGranted()decides who can check a ticket.reader.route: trueadds a publicPOST {path}/readthat tells anyone whether a code is valid: keep it for public contents only. - Rotating codes against screenshots. A ticket shown with
rotate: 30cannot be shared by a screenshot: the copy expires within 30 seconds (plusleeway). The short code follows the same window. - Single use.
once: truerefuses a second read in the cache pool; for tickets, also mark the ticket as used in the database (several cache pools or a cleared cache forget it). - No secret in the data. The data of a signed QR code is signed, not encrypted: anyone can decode it.
- APP_SECRET. Changing it invalidates every signed QR code and every short code. Keep the same value on all the servers.
- The camera is allowed on the pages of the reader only (
Permissions-Policy), never on the rest of the site. - The image URLs only serve the contents created by
qr_code_url()(random key of 128 bits kept in the cache), never an arbitrary text.
Errors
Every error throws NeoPHP\Package\QrCode\Exception\QrCodeException (extends FrameworkException): content too long for a version 40 QR code, unknown option, invalid size, color, error correction or format, logo missing or SVG logo in a PNG, gd missing for PNG, APP_SECRET empty, no cache pool, data that cannot be encoded in JSON, file that cannot be written by qr:generate. A read never throws for a bad input: it returns a ReadResult with an error.
Changelog
- v2.9.0 — QrCode package: encoder without dependency (ISO/IEC 18004, versions 1 to 40, numeric, alphanumeric and UTF-8 byte modes, 4 error correction levels, automatic mask),
Model\QrCoderendered in SVG, PNG (gd), data URI and terminal, colors and logo, Wi-Fi, vCard, e-mail, phone, SMS, position and JSON contents, signed contents (signed(): HMAC withAPP_SECRET, expiration, rotation, single use), short codes typed when a QR code cannot be scanned,read()returning aModel\ReadResultin JSON,<neo-qr-reader>element (camera withBarcodeDetector, torch, manual entry of the short code, events, camera allowed in thePermissions-Policyof its pages),qr_code(),qr_code_url(),qr_code_short()andqr_reader()view functions,/_qrroutes,QrCodeControllercontroller helpers,qr:generateandqr:readcommands,QR codesdoctor check,config/packages/qr_code.yamlgenerated byneo install.