SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

PHP Barcode Generator

Barcodes are graphics that identify data in a machine-readable format. They are made up of parallel black lines. The width of the lines depends on the data to be identified.

Barcodes are useful in many fields. For example, they help in inventory management. They are also useful for over-the-counter staff. When you purchase something online, you can encode the information as a barcode. This way, it can be read by a barcode reader. Similarly, they are used in retail stores to speed up the checkout process.

In this tutorial, we are going to create a very simple barcode generator as shown below:

Barcode service

The service we are going to use for generating the barcode image is This website provides a service for generating free barcodes online.

Build the PHP function

We need a simple PHP function that can take a string and turn it into a barcode:

function barcodeGenerator($msg)
    $msg = urlencode($msg);
    $url = "$msg&code=Code128&dpi=96&dataseparator=";
    return $url;

This function is pretty straightforward, it takes a string and queries the barcode service.

Build a view page

Lastly, let's build the page. Copy the code below to index.php:


function barcodeGenerator($msg)
    $msg = urlencode($msg);
    $url = "$msg&code=Code128&dpi=96&dataseparator=";
    return $url;

if (!empty($_POST)) {
    $barcode = barcodeGenerator(urlencode($_POST['barcodeText']));


<!doctype html>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src=""></script>
<form class="py-28 mx-auto w-full max-w-sm space-y-4" action="index.php" method="post">
    if (!empty($barcode)) {
        echo '<img src="'.$barcode.'" alt="barcode">';

    <div class="flex items-center border-b border-b-2 border-teal-500 py-2">
        <input class="appearance none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none"

    <button type="submit"
            class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">


We are using Tailwind CSS to create the view page. At the top of the page, when we detect a $_POST request, we utilize the barcodeGenerator() to generate a barcode image.

The end

You have successfully built a barcode generator with PHP. Start a PHP web server with the command below:

php -S localhost:8888

Now visit the URL: http://localhost:8888/index.php from your browser. You should be able to see a barcode generator: