Home > Software engineering >  Save QR-Code as an Image on Server-Side with JS/PHP
Save QR-Code as an Image on Server-Side with JS/PHP

Time:08-24

I am working on a Project and I want to generate a QR-Code, so I used the this Lib to generate it with JS. It works, but I want to save the QR-Code on the Server. I don't want to Download it on Client-Side.

I don't want to use NodeJs in my Project.

I tried many ways like sending the SVG-Tag Data to PHP and generating an Image, but it didn't work for me.

Here are my files:
index.php

<?php
// https://github.com/oblakstudio/qr-code-styling?
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QR Code Styling</title>
    <script
              src="https://code.jquery.com/jquery-3.6.0.min.js"
              integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
              crossorigin="anonymous"></script>
    <script type="text/javascript" src="node_modules/qr-code-styling/lib/qr-code-styling.js"></script>
</head>
<body>
<div id="canvas"></div>
<script>
        const qrCode = new QRCodeStyling({
        width: 300,
        height: 300,
        type: "svg",
        data: "https://www.facebook.com/",
        image: "test.png",
        margin:0,
        qrOptions:{
            typeNumber:0,
            errorCorrectionLevel:'H'
        },
        dotsOptions: {
            color: "#00437A",
            type: "classy",

        },
        cornersSquareOptions:{
            color:'#1a79a5',
            type:'rounded',

        },
        cornersDotOptions:{
            color:'#1a79a5',    
            type:'dot',
        },
        backgroundOptions: {
            color: "#fff",
        },
        imageOptions: {
            crossOrigin: "anonymous",
            margin: 0
        }
    });

    qrCode.append(document.getElementById("canvas"));
    const svg = document.querySelector('svg');
    $.ajax('ajax.php',{
        'data': svg.outerHTML,
        'type': 'POST',
        'processData': false,
        'contentType': 'image/svg xml'
    });
</script>
</body>
</html>

ajax.php

<?php
$svg = file_get_contents('php://input');
$myfile = fopen("testfile.svg", "w");
fwrite($myfile, $svg);
?>

CodePudding user response:

use this code

var svgBlob  = qrCode.getRawData('svg');
svgBlob.then(value => value.text().then(value => sendAjax(value)));

function sendAjax(svgString) {
    $.ajax('ajax.php',{
        'data': svgString, //canvas.innerHTML,
        'type': 'POST',
        'processData': false,
        'contentType': 'image/svg xml'
    });
}
  • Related