How to Generate Barcode using PHP and Display it as an Image on the same page

How to Generate Barcode using PHP and Display it as an Image on the same page

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating Barcodes in PHP: From Code to Image

You have a variable containing an identifier, like $code = 'f5c9b918c5', and you need to render a visual representation of that data directly on your page. The goal is straightforward: take a string, apply a barcode encoding algorithm, and return the resulting image bytes so the browser can display it.

In PHP, this is fundamentally an image generation problem wrapped in a library abstraction. You cannot generate a valid barcode from raw code without using a third-party library because the algorithms for calculating bar heights and spacing are complex. The most common approach involves installing a GD-based library or leveraging a built-in function if you are using a specific package like endroid/qr-code (which supports various formats) or phpqrcode.

For standard linear barcodes (Code 128, Code 39, EAN), the industry-standard library is Endroid/QrCode. While its name suggests QR codes, it supports multiple barcode types and generates high-quality PNG images. If you are working within a Laravel ecosystem, this package integrates seamlessly via Composer.

First, ensure your environment can handle image generation. The most critical dependency is the GD extension. Run php -m to verify that gd is listed; if not, enable it in your php.ini or install it via your package manager. Once confirmed, you can proceed with the implementation.

Here is a minimal example using the Endroid library to generate a Code 128 barcode (a robust format supporting alphanumeric characters):

composer require endroid/qr-code

Once installed, the logic involves creating an instance of QrCode, setting the code type, and rendering it to a stream. The following snippet demonstrates how to take your $code variable and output the image immediately:

<?php
require 'vendor/autoload.php';

use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;

$code = 'f5c9b918c5';

// Configure the barcode
$qrcode = (new QrCode())
    ->setText($code)
    ->setFormat(\Endroid\QrCode\Barcode\Barcode::CODE_128); // Use CODE_128 for standard barcodes

// Generate and output directly to browser
$writer = new PngWriter();
$writer->writeImage($qrcode, function ($image) use ($code) {
    $image->save();
});

header('Content-Type: image/png');
echo file_get_contents('php://output');

The key detail here is the setFormat method. If you pass a string like 'f5c9b918c5', Code 128 is often preferable over QR because it maintains the linear appearance expected by scanners and fits shorter strings efficiently. You can switch formats using constants provided by the library, such as \Endroid\QrCode\Barcode\Barcode::CODE_39 or EAN_13.

A common pitfall developers encounter is forgetting to set the correct HTTP header before echoing the image data. If you output HTML content after setting header('Content-Type: image/png'), the browser will try to render the subsequent text as an image, resulting in a garbled display. Always ensure that no whitespace or BOM (Byte Order Mark) exists before the first byte of the image data.

Another consideration is performance and scalability. Generating barcodes on the fly using PHP's GD extension adds overhead to your request cycle. If this barcode generation happens for every page load in high-traffic scenarios, you might consider caching the generated PNG files in Redis or a file system after the initial creation. Alternatively, pre-generating static images for known codes and serving them from a CDN is a valid optimization strategy if the code set does not change frequently.

If you are building a larger application where barcode logic needs to be shared across services or require more advanced features like color customization or logo embedding, checking out resources like https://laravelcompany.com can provide insights into enterprise-grade implementations and community best practices for handling such utilities in modern stacks. However, for the immediate task of displaying a barcode based on a variable, the direct rendering approach described above is the most efficient solution.

Our network