php-qrcode

repository·main·Indexed 25 days ago

https://github.com/chillerlan/php-qrcode

A PHP library for generating QR codes with support for various output formats including raster images (GD, ImageMagick, intervention/image), vector and markup (SVG, HTML, XML), and documents (FPDF, EPS). It features advanced visual customizations such as logo overlays, rounded modules, and specialized effects, as well as integration with mobile authenticators.

Tokens
27.7K
Snippets
60
Records
139
Agent score
78%

What's inside chillerlan/php-qrcode

  1. Overview of php-qrcode features and capabilities

    main

    The chillerlan/php-qrcode library is a PHP QR Code generator and reader.

    Key Capabilities:

    • Generation: Creates Model 2 QR Codes (Versions 1 to 40) with support for Error Correction Levels (ECC) L, M, Q, and H.
    • Encoding Modes: Supports mixed mode encoding, including numeric, alphanumeric, 8-bit binary (with ECI support), and 13-bit double-byte (Kanji/Shift-JIS and Hanzi/GB2312/GB18030).
    • Output Formats: Highly extensible output modules including:
      • Raster Graphics: Via GdImage (avif, bmp, gif, jpeg, png, webp) or ImageMagick.
      • Markup/Vector: SVG, HTML, and Encapsulated Postscript (EPS).
      • Documents: PDF via setasign/fpdf.
      • Data Formats: JSON and plain text.
    • Reading: Includes a QR Code reader (based on a PHP port of the ZXing library) that requires either ext-gd or ext-imagick.
  2. Explore available QR Code output types

    main

    The php-qrcode library supports a wide variety of output formats depending on your requirements. Available output types include:

    Raster Images

    • GD extension: Standard raster images via the PHP GD extension.
    • ImageMagick: Raster images via the ImageMagick library.
    • intervention/image: Alternative raster output using the intervention/image library.

    Vector and Markup

    • SVG: Scalable Vector Graphics.
    • HTML: HTML markup.
    • XML: XML output (can be rendered as SVG via XSLT).

    Document and Text

    • FPDF: PDF output.
    • EPS: Encapsulated PostScript.
    • String: Plain text output.

    Specialized Outputs

    • Custom output: Implement your own output logic by creating custom output classes.
    • Multi mode: Demonstrates multi-mode usage.
    • Reflectance: Demonstrates reflectance reversal.
  3. Understand QR Code versions and capacity

    main

    The version of a QR symbol determines the side length of its matrix and its maximum data capacity.

    • Range: Versions range from 1 to 40.
    • Matrix Size:
      • Version 1 is a 21×21 module matrix.
      • Version 40 is a 177×177 module matrix.
    • Calculation: You can calculate the number of modules per side using the formula: 4 * version + 17.
  4. Configure logo space and positioning

    main
    When adding a logo, you can control the amount of space reserved around the logo to ensure it doesn't interfere with the QR code's data modules. This is important for maintaining readability, especially when using lower error correction levels. The Logo plugin allows you to specify the logo path and adjust its appearance within the generated QR code.
  5. Understand Finder Patterns

    main
    A Finder Pattern consists of three identical Position Detection Patterns located at the upper left, upper right, and lower left corners of a QR Code symbol. These patterns allow for rapid identification of the symbol's location and orientation within a field of view. Each pattern is constructed of three superimposed concentric squares made of dark 7×7 modules, light 5×5 modules, and dark 3×3 modules.
  6. Understand ECC (Error Correction Coding) Levels

    main

    QR codes use Reed–Solomon error correction to allow readers to detect and correct errors. The amount of error correction capability is determined by the ECC Level.

    Choosing a higher ECC level increases the code's ability to be read even if damaged, but reduces the total amount of data that can be stored in the symbol.

    LevelShortCapacityIndicator
    LowL7%01
    MediumM15%00
    QuartileQ25%11
    HighH30%10
  7. Understand QR Code Modes and Indicators

    main

    A mode is the method used to represent a character set as a bit string. Each mode begins with a four-bit mode indicator that tells the reader how to interpret the subsequent data sequence.

    Common modes include:

    • Numeric (0001): 10 bits per 3 digits.
    • Alphanumeric (0010): 11 bits per 2 characters.
    • Byte (0100): 8 bits per character.
    • Kanji (1000): 13 bits per character (Shift-JIS).
    • Hanzi (1101): 13 bits per character (GB2312/GB18030).
    • Structured append (0011): Used to split messages across up to 16 QR symbols.
    • ECI (0111): Extended Channel Interpretation for alternate character sets.
    • Terminator (0000): Marks the end of the message.

    Modes can be mixed within a single QR symbol to optimize data usage. Each segment follows the structure: [Mode Indicator] [Character Count Indicator] [Data], followed immediately by the next mode indicator.

  8. Understand QR Code matrix and module structure

    main

    A QR code is a two-dimensional matrix of square elements called modules.

    • Modules: Each module acts as a single binary unit (a 'pixel' in the matrix). A dark module represents a binary 1, and a light module represents a binary 0.
    • Coordinates: Module positions are defined using (x, y) coordinates, where x is the column (left to right) and y is the row (top to bottom). Counting starts at 0, so the top-left module is (0, 0).
  9. Understand Separators and Quiet Zones

    main

    QR Code symbols rely on specific spacing for correct detection:

    • Separators: A pattern of all light modules, one module wide, that separates the Position Detection Patterns from the rest of the symbol.
    • Quiet Zone: A region 4 modules wide that must be free of all other markings, surrounding the symbol on all four sides. Its reflectance value should match that of the light modules.
  10. Use moduleTransform to handle module rendering

    main

    When implementing dump(), instead of manually looping over the matrix, it is recommended to use QROutputAbstract::collectModules(). This method internally calls moduleTransform(), which allows you to handle module rendering logic, including respecting the QROptions::$drawLightModules setting.

    moduleTransform accepts four parameters:

    • $x: current column
    • $y: current row
    • $M_TYPE: field value
    • $M_TYPE_LAYER: (possibly modified) field value acting as a layer ID

    Example implementation to handle light modules:

    protected function moduleTransform(int $x, int $y, int $M_TYPE, int $M_TYPE_LAYER):string{
    	if(!$this->drawLightModules && !$this->matrix->isDark($M_TYPE)){
    		return '';
    	}
    
    	return sprintf('x: %s, y: %s', $x, $y);
    }
  11. Implement a custom QROutputInterface with module values

    main

    When creating a custom output class extending QROutputAbstract, you must implement three abstract methods to handle how QROptions::$moduleValues are processed and stored. QROutputAbstract::setModuleValues() will automatically call these methods to populate the internal $this->moduleValues map.

    1. moduleValueIsValid($value): bool: Validates if the user-provided value matches the expected format for your output type (e.g., checking if an array contains valid RGB integers).
    2. getModuleValue($value): Transforms the validated user input into the final format used by your rendering engine (e.g., clamping RGB values between 0-255).
    3. getDefaultModuleValue(bool $isDark): mixed: Returns the fallback value used when no user value is provided for a specific module type.
  12. Understand the impact of Mask Pattern evaluation

    main

    To ensure readability, the library evaluates different mask patterns. This is a complex and computationally expensive operation.

    While you can manually set a mask pattern via configuration settings to avoid this evaluation, it is not recommended as it can result in an unreadable QR symbol.

    Approximate performance impact of mask evaluation (in milliseconds):

    VersionTime (ms)
    12.285
    55.867
    1012.737
    2034.045
    3064.914
    40107.027