DEV Community

Xiao Ling
Xiao Ling

Posted on • Originally published at dynamsoft.com

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

If you want to use PHP Laravel framework to build a web barcode and QR code reader, you can implement the code logic either on the client side or on the server side. Dynamsoft provides a variety of SDKs for different platforms: desktop, mobile and web. In this article, we focus on how to leverage the PHP extension built with Dynamsoft C++ Barcode SDK to read barcode and QR code on the server side. If web client side programming is your type, please refer to https://www.dynamsoft.com/barcode-reader/sdk-javascript/.

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 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. To read barcode and QR code in PHP, you need to build and install the PHP extension from source code on Windows and Linux.

Step 2: Scaffold a Laravel Project

Once the extension is installed, you can start a new Laravel project.

composer create-project laravel/laravel web-barcode-qrcode-reader
Enter fullscreen mode Exit fullscreen mode

The above command installs the latest stable version of Laravel. To avoid the compatibility issue, a better way is to specify the Laravel version number.

php artisan --version
Laravel Framework 8.83.23

composer create-project laravel/laravel:^8.0 web-barcode-qrcode-reader
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Controller

Laravel controllers handle HTTP requests. We can create a controller to handle the uploaded image files and return the barcode and QR code decoding results.

php artisan make:controller ImageUploadController
Enter fullscreen mode Exit fullscreen mode

The command generates an ImageUploadController.php file in the app/Http/Controllers directory. Open the file to add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class ImageUploadController extends Controller
{
    function __construct() {
        DBRInitLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==");
        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()
      ]);
     }
    }
}
Enter fullscreen mode Exit fullscreen mode

In __construct() method, you initialize the barcode SDK instance by setting a valid license key, which can be obtained from Dynamsoft customer portal. Calling DBRInitRuntimeSettingsWithString() is optional, because the default settings are suitable for most cases.

The uploaded images are saved to the public/images directory. The DecodeBarcodeFile() method is used to read barcode and QR code from the image file.

The next step is to create the barcode_qr_reader view.

Step 4: Create a Web View

Create a barcode_qr_reader.blade.php file in the public/resources/views directory. The file contains the HTML5 code for uploading an image via a form.

<!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>
Enter fullscreen mode Exit fullscreen mode

CSRF Protection is required for the form. A convenient way is to use the @csrf Blade directive to generate the hidden token input field:

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

As the web page is done, one more step is to add 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');
Enter fullscreen mode Exit fullscreen mode

Step 5: Run the PHP Laravel Barcode QR Code Reader

Now you can run the PHP Laravel project and visit http://127.0.0.1:8000/barcode_qr_reader in your browser.

php artisan serve
Enter fullscreen mode Exit fullscreen mode

PHP Laravel barcode QR code reader

Source Code

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

Top comments (0)