Recently, when developing a web application based on front-end and back-end separation, I encountered a rather difficult problem: after the front-end uses JavaScript to base64 encode the image, it is transmitted to the back-end PHP program for decoding, and the result is garbled code.
After many attempts and research, I have summarized some solutions and share them for your reference.
First, let’s understand the basic principles of base64 encoding and decoding. Base64 is a method of using 64 characters to represent binary data. The data is classified into groups of 6 bits. The corresponding characters are found in the predefined character set based on the 6-bit value to replace the bytecode in the original binary data. In this way, any data can be converted into printable ASCII characters for easy transmission and storage.
In JavaScript, you can generate a base64-encoded string containing image data by calling the toDataURL() function of the canvas object:
var canvas = document.createElement('canvas'); canvas.width = 400; canvas.height = 300; var ctx = canvas.getContext('2d'); ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, 400, 300); var img = new Image(); img.src = './test.jpg'; img.onload = function() { ctx.drawImage(img, 0, 0, 400, 300); var dataURL = canvas.toDataURL('image/jpeg', 0.8); // 传输dataURL给后端进行base64解码 };
In PHP, you can use the base64_decode() function to convert base64 to The encoded string is decoded into raw binary data for further manipulation.
However, during actual operation, we found that sometimes garbled characters appear. Why is this?
The reasons for garbled characters are as follows:
- The base64 string contains prefixes such as data:image/jpeg;base64 and delimiters, which need to be removed first.
- The base64 string contains URL-encoded characters, such as , /, etc., which need to be decoded before decoding.
- The magic_quotes_gpc option is turned on in the php configuration, which causes characters such as single quotes and double quotes to be escaped, causing problems during decoding.
- During the transmission process, due to various reasons (such as Chinese encoding problems, etc.), part of the data is modified, which in turn affects base64 decoding.
The solution is as follows:
- Remove the prefix and delimiter
You can replace data:image/jpeg with string replacement ;base64, remove prefixes and delimiters, and directly use base64 strings for decoding.
$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/…'; // base64编码的图片数据 $data = str_replace('data:image/jpeg;base64,', '', $data); $data = str_replace(' ', '+', $data); // 如果出现URL编码中的+,需要替换成空格。 $data = base64_decode($data);
- Decoding URL encoded characters
Use the urldecode() function to decode URL-encoded characters, and then use base64_decode() for base64 decoding.
$data = 'data:image/jpeg;base64,%2F9j%2F4AAQSk...'; // base64编码的图片数据 $data = urldecode($data); $data = base64_decode($data);
- Disable magic_quotes_gpc option
Search for magic_quotes in php.ini, set it to Off, and then restart php to take effect.
magic_quotes_gpc = Off
- Data integrity check
When transmitting data at the front and back ends, the data can be integrity checked to ensure that the data has not been modified. For example, you can use md5() to digest the original data and transmit it to the backend. The backend then digests the received binary data and compares the two digest values. If they are the same, the data has not been modified and the decoding operation can be performed.
Summary:
The above are some solutions I summarized when solving the problem of garbled characters in php base64 decoding. You can choose and try according to your actual situation. When doing web development, don't be afraid when you encounter problems. Try more and consult more information. I believe you will always find a solution.
The above is the detailed content of What to do if php base64 encoding is garbled. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version
