Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 QR Code Generator Tutorial

Last Updated on August 9, 2024 by

simplesoftwareio qrcode is a popular library for creating QR code in PHP and its frameworks like codeIgniter, laravel, yii, etc.

Here are steps to generate qr codes in codeIgniter application:

Step 1: Install the simplesoftwareio/simple-qrcode Package

Run the following command install PHP package simplesoftwareio/simple-qrcode for qr code generator:

composer require simplesoftwareio/simple-qrcode

Step 2: Create a Controller

Go to app/controllers directory and create a controller file named QrCodeController.php file, and then create a methods in it to generate qr codes:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QrCodeController extends Controller
{
    public function generate()
    {
        // Generate the QR code
        $qrCode = base64_encode(QrCode::format('png')
            ->size(300)
            ->generate('https://yourwebsite.com'));
    
        // Pass the QR code to the view
        return view('qr_code', ['qrCode' => $qrCode]);
    }


    public function download()
    {
        // Generate the QR code and save it to a file
        QrCode::format('png')
            ->size(300)
            ->generate('https://yourwebsite.com', WRITEPATH . 'uploads/qr-code.png');

        // Return the file as a response
        return $this->response->download(WRITEPATH . 'uploads/qr-code.png', null);
    }
}

Step 3: Create Routes for QR Code Generation

Edit the app/Config/Routes.php file and add the following routes in it:

$routes->get('/generate-qr', 'QrCodeController::generate');
$routes->get('/download-qr', 'QrCodeController::download');

Step 4: Create a View

Go to app/views directory and create qr_code.php file, then add the following code in it to display qr code on views:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Code Generator - itcodstuff.com</title>
</head>
<body>
    <h1>QR Code</h1>
    <img src="data:image/png;base64,<?= $qrCode ?>" alt="QR Code">
</body>
</html>

Step 5: Test the QR Code Generator

Run the following command to start application server:

php spark serve
  • Visit http://localhost:8080/generate-qr in your browser to see the QR code directly.
  • Visit http://localhost:8080/download-qr to download the QR code as a PNG file.

Step 6: Customizing the QR Code (Optional)

In simple-qrcode package you can easily change size, color, format and text data:

  • ->size(300)
  • ->color(r, g, b)
  • ->format(‘png’)
  • ->generate(‘https://yourwebsite.com’)

Leave a Comment