search
HomeBackend DevelopmentPHP TutorialDetailed explanation of phpqrcode class to generate QR code

This time I will bring you a detailed explanation of the QR code generated by the phpqrcode class. What are the precautions for generating the QR code by the phpqrcode class. The following is a practical case, let's take a look.

The example in this article describes how PHP generates QR codes based on the phpqrcode class. Share it with everyone for your reference, the details are as follows:

It is quite difficult to use PHP language to generate QR codes. Of course, the interface for generating QR code images is called (for example: Liantu.com http://www .liantu.com/ interface), if you write the code to generate it yourself, you really have no way to start. However, we can use phpqrcode, a ready-made class file, PHP QR code generation class library, which can easily generate QR codes.

Preliminary preparation:

1.phpqrcode classFile download, download address: https://sourceforge.net /projects/phpqrcode/
2. The PHP environment must enable GD2 extension library support (usually enabled)

Interpretation of method:

The downloaded class file is a compressed package, which contains many files and demonstration programs. We only need the phpqrcode.php file inside to generate the QR code. It is a collection file of multiple classes. We need to use the png() method (line 3090) of the QRcode class (line 2963) inside:

public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
{
  $enc = QRencode::factory($level, $size, $margin);
  return $enc->encodePNG($text, $outfile, $saveandprint=false);
}

The first parameter$text : The content contained in the QR code can be links, text, json strings, etc.;
The second parameter $outfile: The default is false, no file is generated, and only the second parameter is The QR code image is returned as output; otherwise, the file name and path to store the generated QR code image need to be given;
The third parameter$level: The default is L, the values ​​that can be passed by this parameter are L(QR_ECLEVEL_L, 7%), M(QR_ECLEVEL_M, 15%), Q(QR_ECLEVEL_Q, 25%), H(QR_ECLEVEL_H, 30%), this parameter controls the error tolerance rate of the QR code. Different parameters indicate that the QR code can be The percentage of the area covered, that is, the covered area can still be identified;
The fourth parameter$size: Controls the size of the generated image, the default is 4;
The fifth parameter$margin: Control the size of the blank area for generating QR codes;
The sixth parameter $saveandprint: Save the QR code image and display it, $outfile must pass the image path;

Usage example:

1. Generate QR code (generate image file)

// 1. 生成原始的二维码(生成图片文件)
function scerweima($url=''){
  require_once 'phpqrcode.php';
  $value = $url;         //二维码内容
  $errorCorrectionLevel = 'L';  //容错级别
  $matrixPointSize = 5;      //生成图片大小
  //生成二维码图片
  $filename = 'qrcode/'.microtime().'.png';
  QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
  $QR = $filename;        //已经生成的原始二维码图片文件
  $QR = imagecreatefromstring(file_get_contents($QR));
  //输出图片
  imagepng($QR, 'qrcode.png');
  imagedestroy($QR);
  return '<img  src="/static/imghwm/default1.png" data-src="qrcode.png" class="lazy" alt="Detailed explanation of phpqrcode class to generate QR code" >';
}
//调用查看结果
echo scerweima('https://www.baidu.com');

2. Add logo to the generated QR code (generate image file)

//2. 在生成的二维码中加上logo(生成图片文件)
function scerweima1($url=''){
  require_once 'phpqrcode.php';
  $value = $url;         //二维码内容
  $errorCorrectionLevel = 'H';  //容错级别
  $matrixPointSize = 6;      //生成图片大小
  //生成二维码图片
  $filename = 'qrcode/'.microtime().'.png';
  QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
  $logo = 'qrcode/logo.jpg'; //准备好的logo图片
  $QR = $filename;      //已经生成的原始二维码图
  if (file_exists($logo)) {
    $QR = imagecreatefromstring(file_get_contents($QR));    //目标图象连接资源。
    $logo = imagecreatefromstring(file_get_contents($logo));  //源图象连接资源。
    $QR_width = imagesx($QR);      //二维码图片宽度
    $QR_height = imagesy($QR);     //二维码图片高度
    $logo_width = imagesx($logo);    //logo图片宽度
    $logo_height = imagesy($logo);   //logo图片高度
    $logo_qr_width = $QR_width / 4;   //组合之后logo的宽度(占二维码的1/5)
    $scale = $logo_width/$logo_qr_width;  //logo的宽度缩放比(本身宽度/组合后的宽度)
    $logo_qr_height = $logo_height/$scale; //组合之后logo的高度
    $from_width = ($QR_width - $logo_qr_width) / 2;  //组合之后logo左上角所在坐标点
    //重新组合图片并调整大小
    /*
     * imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
     */
    imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
  }
  //输出图片
  imagepng($QR, 'qrcode.png');
  imagedestroy($QR);
  imagedestroy($logo);
  return '<img  src="/static/imghwm/default1.png" data-src="qrcode.png" class="lazy" alt="Detailed explanation of phpqrcode class to generate QR code" >';
}
//调用查看结果
echo scerweima1('https://www.baidu.com');

3. Generate QR code (do not generate image file)

//3. 生成原始的二维码(不生成图片文件)
function scerweima2($url=''){
  require_once 'phpqrcode.php';
  $value = $url;         //二维码内容
  $errorCorrectionLevel = 'L';  //容错级别
  $matrixPointSize = 5;      //生成图片大小
  //生成二维码图片
  $QR = QRcode::png($value,false,$errorCorrectionLevel, $matrixPointSize, 2);
}
//调用查看结果
scerweima2('https://www.baidu.com');

The first two methods will generate a QR code image locally every time they are called. The third method will directly output the QR code to the browser without generating a file.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Mysqld_multi deployment stand-alone detailed explanation

Summary of some MySQL traps

How to operate tables in Bootstrap

The above is the detailed content of Detailed explanation of phpqrcode class to generate QR code. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.