TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

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 https://barcode.tec-it.com/. 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 = "http://barcode.tec-it.com/barcode.ashx?data=$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:

<?php

function barcodeGenerator($msg)
{
    $msg = urlencode($msg);
    $url = "http://barcode.tec-it.com/barcode.ashx?data=$msg&code=Code128&dpi=96&dataseparator=";
    return $url;
}


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


?>

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<form class="py-28 mx-auto w-full max-w-sm space-y-4" action="index.php" method="post">
    <?php
    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"
               type="text"
               name="barcodeText"
               placeholder="Barcode">
    </div>

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

</body>
</html>

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: