Using PHP Laravel to Read QR Code Barcode on the Server Side

If you want to use the PHP Laravel framework to build a web-based barcode and QR code reader, you can implement the barcode detection logic on either the client side or the server side. Dynamsoft offers a variety of SDKs for different platforms, including desktop, mobile, and web. In this article, we will focus on how to leverage the PHP extension, built with the Dynamsoft C++ Barcode SDK, to read barcodes and QR codes on the server side.

Prerequisites

PHP Laravel Installation on Windows and Linux

Install PHP 7.4, Composer and Laravel.

  • PHP 7.4
  • Composer
    • Windows Run Composer-Setup.exe
    • Linux
        php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
        php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
        php composer-setup.php
        php -r "unlink('composer-setup.php');"
        sudo mv composer.phar /usr/local/bin/composer
      
  • Laravel:

      composer global require laravel/installer
    

Steps to Implement Server-Side Barcode and QR Code Reading Using PHP Laravel

In the following paragraphs, we will guide you through the process of developing a PHP Laravel project that can read barcode and QR code from image files on the server side.

Step 1: Install the PHP Barcode QR Code Reader Extension

There is no pre-built binary package available. To read barcodes and QR codes in PHP, you must build and install the PHP extension from source code on both Windows and Linux.

Step 2: Scaffold a Laravel Project

After installing the extension, initiate a new Laravel project:

composer create-project laravel/laravel web-barcode-qrcode-reader

To avoid compatibility issues, specify the Laravel version:

php artisan --version
Laravel Framework 8.83.23

composer create-project laravel/laravel:^8.0 web-barcode-qrcode-reader

Step 3: Create a Controller

Laravel controllers manage HTTP requests. We can employ a controller to handle uploaded image files and decode the barcodes and QR codes. A new controller can be created using the make:controller Artisan command:

php artisan make:controller ImageUploadController

The command generates an ImageUploadController.php file in the app/Http/Controllers directory. You need to open the file and implement the barcode reading functionality:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class ImageUploadController extends Controller
{
    function __construct() {
        DBRInitLicense("LICENSE-KEY");
        DBRInitRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"BestCoverage\",\"DeblurLevel\":9,\"ExpectedBarcodesCount\":512,\"ScaleDownThreshold\":100000,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_SCAN_DIRECTLY\"},{\"Mode\":\"LM_STATISTICS\"},{\"Mode\":\"LM_LINES\"},{\"Mode\":\"LM_STATISTICS_MARKS\"}],\"GrayscaleTransformationModes\":[{\"Mode\":\"GTM_ORIGINAL\"},{\"Mode\":\"GTM_INVERTED\"}]}}");		
    }

    function page()
    {
     return view('barcode_qr_reader');
    }

    function upload(Request $request)
    {
     $validation = Validator::make($request->all(), [
      'BarcodeQrImage' => 'required'
     ]);
     if($validation->passes())
     {
      $image = $request->file('BarcodeQrImage');
      $image->move(public_path('images'), $image->getClientOriginalName());

      $resultArray = DecodeBarcodeFile(public_path('images/' . $image->getClientOriginalName()), 0x3FF | 0x2000000 | 0x4000000 | 0x8000000 | 0x10000000); // 1D, PDF417, QRCODE, DataMatrix, Aztec Code

      if (is_array($resultArray)) {
        $resultCount = count($resultArray);
        echo "Total count: $resultCount", "\n";
        if ($resultCount > 0) {
            for ($i = 0; $i < $resultCount; $i++) {
                $result = $resultArray[$i];
                echo "Barcode format: $result[0], ";
                echo "value: $result[1], ";
                echo "raw: ", bin2hex($result[2]), "\n";
                echo "Localization : ", $result[3], "\n";
            }
        }
        else {
            echo 'No barcode found.', "\n";
        }
      } 

      return response()->json([
       'message'   => 'Successfully uploaded the image.'
      ]);
     }
     else
     {
      return response()->json([
       'message'   => $validation->errors()->all()
      ]);
     }
    }
}
  • You need to replace LICENSE-KEY with a valid license obtained from the Dynamsoft customer portal.
  • Initializing the barcode SDK instance and setting the license key happen in the __construct() method. - Using DBRInitRuntimeSettingsWithString() is optional as the default settings usually suffice.
  • The uploaded images are saved in the public/images directory.
  • The DecodeBarcodeFile() method is used to process the image files.

Next, create the barcode_qr_reader view.

Step 4: Create a Web View

In the resources/views directory, create a barcode_qr_reader.blade.php file containing the HTML5 code for uploading images:

<!DOCTYPE html>
<html>

<head>
    <title>PHP Laravel Barcode QR Reader</title>
    <meta name="_token" content="{{csrf_token()}}" />
</head>

<body>
    <H1>PHP Laravel Barcode QR Reader</H1>
    <form action="{{ route('image.upload') }}" method="post" enctype="multipart/form-data">
    @csrf
        Select barcode image:
        <input type="file" name="BarcodeQrImage" id="BarcodeQrImage" accept="image/*"><br>
        <input type="submit" value="Read Barcode" name="submit">
    </form>
    <img id="image" />
    <script>
        var input = document.querySelector('input[type=file]');
        input.onchange = function() {
            var file = input.files[0];
            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                {
                    let image = document.getElementById('image');
                    image.src = e.target.result;
                }
            }
            fileReader.readAsDataURL(file);
        }
    </script>
</body>

</html>

To implement CSRF Protection in Laravel, use the @csrf Blade directive in the form:

<form action="{{ route('image.upload') }}" method="post" enctype="multipart/form-data">
    @csrf
    ...
</form>

Finally, define the web routes in public/routes/web.php.

Route::get('/barcode_qr_reader', 'App\Http\Controllers\ImageUploadController@page');
Route::post('/barcode_qr_reader/upload', 'App\Http\Controllers\ImageUploadController@upload')->name('image.upload');

Step 5: Run the PHP Laravel Barcode QR Code Reader

Start the Laravel server and access the project by navigating to http://127.0.0.1:8000/barcode_qr_reader in your web browser.

php artisan serve

PHP Laravel barcode QR code reader

Source Code

https://github.com/yushulx/php-laravel-barcode-qr-reader