PC scan code upload PHP implementation

PHP中文网
Release: 2023-05-05 12:47:35
Original
167 people have browsed it

PC-side scan code upload is a hot topic in the development field in recent years. It can easily upload local files to the server, and uses the scan code method to replace the traditional upload method, which is more convenient and efficient. In this article, we will introduce how to use PHP to implement PC scanning and uploading.

For PC-side scanning and uploading, we first need to understand several concepts. The first is the principle of QR code generation and scanning, and the second is the technology of PHP to implement file upload.

QR code generation and scanning principle

QR code is a graphic code that can store a large amount of information. It can be used in a variety of situations, such as links, text, maps, contact details, and more. There are many ways to generate QR codes, the most commonly used of which is to use the JavaScript framework QRCode.js. Through this framework, we can generate corresponding QR codes from text, URL and other information.

When scanning the QR code, we can use the mobile phone scanning software to scan the QR code using the mobile phone camera, and obtain the information represented by the QR code through scanning. For the PC side, we can also use QR code scanning software such as Zbar to scan the QR code.

PHP implements file upload technology

PHP is a very popular server-side scripting language and plays an important role in the field of Web development. For file upload, PHP provides a very convenient file upload class-upload class.

When using the upload class to implement file upload, we only need to simply instantiate the class and use the corresponding method to upload the file. Among them, important methods include: upload(), getFileName(), getErrorMsg(), etc.

PHP implements PC scanning code uploading

With the above basic knowledge, we can start to implement the PC scanning code uploading function. Here we will divide it into two parts, namely background file processing and front-end file generation.

Background file processing

1. Upload file interface

First we need to implement an interface for uploading files, which is used to process the file stream transmitted from the front desk and the file we need to upload. File information. For different file types and file sizes, we need to perform special processing, such as limiting the size and type of uploaded images, etc.

Code example:

<code class="php"><?php
header('Content-type: application/json');
$FILE_BASE = './files/';
$MAX_SIZE = 10 * 1024 * 1024;//10M
$ALLOW_FILE_SUFFIX = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];//允许上传的文件类型
$max_size_POST = ini_get('post_max_size');
$max_size_UPLOAD = ini_get('upload_max_filesize');
$max_size = min($MAX_SIZE, getBytes($max_size_POST), getBytes($max_size_UPLOAD));

$filename = $_POST['filename'];

if (empty($filename)) {
    echo json_encode(['status' => 'error', 'msg' => 'filename is empty']);
    return;
}

if(empty($_FILES) || empty($_FILES['file'])){
    echo json_encode(['status' => 'error', 'msg' => 'file is empty']);
    return;
}

$file_size = $_FILES['file']['size'];

if($file_size > $max_size){
    echo json_encode(['status' => 'error', 'msg' => 'file size is too big']);
    return;
}

$file_type = strtolower(pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION));

if(!in_array($file_type, $ALLOW_FILE_SUFFIX)){
    echo json_encode(['status' => 'error', 'msg' => 'file type is not allowed']);
    return;
}

if(!is_dir($FILE_BASE)){
    mkdir($FILE_BASE, 0777, true);
}
$file_path = $FILE_BASE.$filename;
if(move_uploaded_file($_FILES["file"]["tmp_name"], $file_path)){
    echo json_encode(['status' => 'success', 'msg' => 'upload success']);
}else{
    echo json_encode(['status' => 'error', 'msg' => 'upload fail']);
}
function getBytes($val)
{
    $val = trim($val);
    $last = strtolower($val[strlen($val) - 1]);
    $val = preg_replace('/[^0-9]/', '', $val);
    switch ($last) {
        case 'g':
            $val *= 1024 * 1024 * 1024;
            break;
        case 'm':
            $val *= 1024 * 1024;
            break;
        case 'k':
            $val *= 1024;
            break;
    }
    return $val;
}
?></code>
Copy after login

2. Generate QR code

Generating QR code can be achieved using the QRCode.js framework. We need to convert the file name and related information to be uploaded into QR code information and then generate the corresponding QR code.

Code example:

<code class="php"><?php
$filename = $_POST['filename'];
$path = 'http://localhost/'; //服务器地址
$text = urlencode(json_encode(['filename' => $filename, 'path' => $path]));
$url = "http://qr.liantu.com/api.php?text=" . $text;
echo $url; //返回二维码地址
?></code>
Copy after login

Front-end file generation

In the front-end, we need to generate a QR code and display it in the preview box on the right. In addition, we also need to add operation buttons and corresponding prompts for uploading files.

Code example:

<code class="html"><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PC扫码上传</title>
    <style type="text/css">
        .upload {
            display: inline-block;
            background: #1B96F3;
            color: #fff;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            outline: none;
        }

        .upload:hover {
            background-color: #2A87CB;
        }

        .img-preview {
            width: 200px;
            height: 200px;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .img-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="qrcode-container">
            <div class="qrcode"></div>
        </div>
        <div class="upload-container">
            <input type="file" id="file" style="display:none" onchange="uploadFile(this)"/>
            <button class="upload" onclick="document.getElementById('file').click()">上传文件</button>
            <div class="alert"></div>
        </div>
        <div class="img-preview-container">
            <h4>预览</h4>
            <div class="img-preview"></div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <script type="text/javascript">
        function createQrcode(url) {
            var qrcode = new QRCode(document.querySelector('.qrcode'), {
                text: url,
                width: 200,
                height: 200,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        }

        function showPreview(file) {
            var fr = new FileReader();
            fr.onload = function () {
                $('<img>').attr('src', fr.result).appendTo('.img-preview');
            }
            fr.readAsDataURL(file);
        }

        function uploadFile(obj) {
            var file = obj.files[0];
            var fd = new FormData();
            fd.append('file', file);
            fd.append('filename', file.name);
            $.ajax({
                url: '/upload.php',
                type: 'POST',
                data: fd,
                processData: false,
                contentType: false,
                success: function (data) {
                    if (data.status == 'success') {
                        createQrcode(data.msg);
                        showPreview(file);
                        $('.alert').text('上传成功');
                    } else {
                        $('.alert').text('上传失败');
                    }
                },
                error: function () {
                    $('.alert').text('上传失败');
                }
            });
        }
    </script>
</body>
</html></code>
Copy after login

In summary, we have successfully completed the development of PC scan code upload. In this process, we learned the principles of QR code generation and scanning, as well as the technology of PHP to implement file upload, and combined the two to complete the implementation of the PC scan code upload function. For developers, this more convenient and efficient upload method will become a hot topic and demand in development.

The above is the detailed content of PC scan code upload PHP implementation. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template