You may want to generate a QR code for various reasons. QR codes are easy to share with someone. For this tutorial, I am taking a scenario where to see the user’s information one needs to scan the QR code. I am taking a few details like full name, email and picture which will be displayed on scanning a QR code. To build this flow the steps would be as follows.

  • Create HTML Form to enter full name, email and picture.
  • On form submission, the Ajax request will be sent to a server-side.
  • Generate a QR code on the server-side and store form details into the database.
  • Print the QR code on the webpage.
  • Optionally give an option to download QR code into a PDF.
  • On a scan, one will receive an URL where they can see the information of a user.

I’ll use a few libraries to achieve our task.

  • chillerlan/php-qrcode : This library is used to generate a QR code in PHP.
  • html2canvas and jspdf : These libraries used to generate a PDF containing QR code.

Having said that, let’s start writing a code to generate a QR code.

Database Configuration

To show the information after scanning a QR code, we need a database to store details of a user against the unique id. This unique id will be appended on the URL(appear after scanning). With this id we’ll fetch details from the database.

Create the users table by running the below SQL.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `qrcode_id` varchar(255) DEFAULT NULL,
  `fullname` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `picture` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Next, I’ll write the code for database connection, insert and fetch the user into the class-db.php file.

<?php
class DB {
    private $dbHost     = "DB_HOST";
    private $dbUsername = "DB_USERNAME";
    private $dbPassword = "DB_PASSWORD";
    private $dbName     = "DB_NAME";
 
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
 
    public function get_user($id) {
        $sql = $this->db->query("SELECT * FROM users WHERE qrcode_id = '$id'");
        return $sql->fetch_assoc();
    }
 
    public function insert_user($arr_data = array()) {
        $qrcode_id = $arr_data['qrcode_id'];
        $name = $arr_data['fullname'];
        $email = $arr_data['email'];
        $picture = $arr_data['picture'];
 
        $this->db->query("INSERT INTO users(qrcode_id, fullname, email, picture) VALUES('$qrcode_id', '$name', '$email', '$picture')");
    }
}

Create HTML Form

In the HTML file, let’s create a form to enter the details. I am also going to include libraries – html2canvas and jspdf. For the sake of a tutorial, I am adding them via CDN.

<form method="post" enctype="multipart/form-data" id="frmQRCode" onsubmit="generateQRCode();return false;">
    <p>
        <input type="text" name="fullname" placeholder="Full Name" required />
    </p>
    <p>
        <input type="email" name="email" placeholder="Email" required />
    </p>
    <p>
        <input type="file" name="picture" id="picture" required />
    </p>
    <input type="submit" name="submit" value="Submit" />
</form>
<!-- QR Code will appear here -->
<div class="qrcode-image" style="display:none;">
    <div id="content"></div>
    <button onclick="save_qrcode_to_pdf();">Save to PDF</button>
</div>

<script src="custom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

Here, you may have noticed 2 methods – generateQRCode() and save_qrcode_to_pdf(). These methods are self-explanatory. We’ll define these functions into the custom.js file which is already included in the above HTML.

JavaScript Code (custom.js)

With the help of JavaScript, we collect the form data, send data to the server-side script via Ajax and print the response in the HTML. A QR code will be appended inside the div having id ‘content’.

To create a PDF, it’ll get the HTML of this div(having a QR code), build the PDF and send it to the browser.

function generateQRCode() {
    var form_data = new FormData(document.getElementById("frmQRCode"));

    picture = document.getElementById('picture').files[0];
    form_data.append('picture', picture);

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "generate-qrcode.php", true);
    xhttp.onload = function(event) {
        if (xhttp.status == 200) {
            if('success' == JSON.parse(this.response).code) {
                document.querySelector('#content').innerHTML = JSON.parse(this.response).content;
                document.querySelector(".qrcode-image").style.display = "block";
            } else {
                alert(JSON.parse(this.response).content);
            }
        } else {
            alert("Error " + xhttp.status + " occurred when trying to upload your documents.");
        }
    }

    xhttp.send(form_data);
}

function save_qrcode_to_pdf() {
    window.jsPDF = window.jspdf.jsPDF;

    var doc = new jsPDF();
        
    // Source HTMLElement or a string containing HTML.
    var elementHTML = document.querySelector("#content");

    doc.html(elementHTML, {
        callback: function(doc) {
            // Save the PDF
            doc.save('qrcode.pdf');
        },
        x: 15,
        y: 15,
        width: 170, //target width in the PDF document
        windowWidth: 650 //window width in CSS pixels
    });
}

In the above code, I am posting data to the generate-qrcode.php file. This file will be responsible for storing details into the database and generating a QR code.

Generate a QR Code (generate-qrcode.php)

Before writing a code to this file, first install the QR code generator library with the following composer command.

composer require chillerlan/php-qrcode

In the generate-qrcode.php file, we have to include the environment of chillerlan/php-qrcode library and database class file.

<?php
require_once "vendor/autoload.php";
require_once "class-db.php";

use chillerlanQRCodeQRCode;
use chillerlanQRCodeQROptions;

$qrcode_id = time().uniqid();

if ( !file_exists('uploads') ) {
    mkdir('uploads', 0755);
}

$filename = time().$_FILES['picture']['name'];
move_uploaded_file($_FILES['picture']['tmp_name'], 'uploads/'.$filename);

$data = array(
    'qrcode_id' => $qrcode_id,
    'fullname' => $_POST['fullname'],
    'email' => $_POST['email'],
    'picture' => $filename,
);
$db = new DB();
$db->insert_user($data);

$url = "SITE_URL/reader.php?id=".$qrcode_id;
$qr_image = (new QRCode)->render($url);
echo json_encode(array('code' => 'success', 'content' => '<img src="'. $qr_image .'" alt="QR Code" />'));
die;

From this file, I am returning a JSON response which will be handled by our JavaScript code. It’ll print the QR code on our webpage.

Now, upon scanning this QR code, the URL will appear something like SITE_URL/reader.php?id=some_unique_id .

When this URL hits the browser, we have to display the information related to this unique id.

Print Information (reader.php)

Finally, print the user’s information with the help of the following code.

<?php
require_once "class-db.php";

$id = $_GET['id'];

$db = new DB();
$data = $db->get_user($id);
?>

<div class="info">
    <img src="<?php echo "SITE_URL/uploads/".$data['picture']; ?>" width="200" alt="picture">
    <p>Fullname: <?php echo $data['fullname']; ?></p>
    <p>Email: <?php echo $data['email']; ?></p>
</div>

That’s it! You may now test the flow we built. It should allow you to generate a QR code and get details upon scanning it.

I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

The post Dynamically Generate QR Code using PHP, JavaScript, and Ajax appeared first on Artisans Web.