Home Backend Development PHP Tutorial How to solve PHP Chinese garbled code? Introduction to three situations of Chinese garbled characters in PHP

How to solve PHP Chinese garbled code? Introduction to three situations of Chinese garbled characters in PHP

Jul 23, 2018 pm 04:44 PM

PHP Chinese garbled characters are a problem that can often be encountered in PHP development. For example: PHP Chinese garbled characters sometimes occur on the web page itself, some occur during the interaction with MySQL, and sometimes are related to the operating system. So, how to solve the Chinese garbled code in PHP? Next, let’s take a look at these three situations in detail.

Recommended manual:php complete self-study manual

1. The first is the encoding of the PHP web page

1. The encoding of the PHP file itself and the encoding of the web page should match

a. If you want to use gb2312 encoding, then PHP must output the header: header( "Content-Type: text/html; charset=gb2312"), add to the static page, and the encoding format of all files is ANSI, you can open it with Notepad, save as and select the encoding as ANSI, and overwrite the source file.

b. If you want to use utf-8 encoding, then php should output the header: header("Content-Type: text/html; charset=utf-8"), and add , the encoding format of all files is utf-8. Saving as utf-8 may be a bit troublesome. Generally, utf-8 files will have BOM at the beginning. If you use session, there will be problems. You can use editplus to save. In editplus, go to Tools->Parameter Selection->File-> UTF-8 signature, select Always delete, then save to remove the BOM information.

2. PHP itself is not Unicode, all functions such as substr must be changed to mb_substr (mbstring extension needs to be installed); or iconv can be used to transcode.

two. Data interaction between PHP and Mysql

The encoding of PHP and the database should be consistent

1. Modify the mysql configuration file my.ini or my.cnf. It is best to use utf8 encoding for mysql

[mysql]
default-character-set=utf8
[mysqld]
default-character-set=utf8
default-storage-engine=MyISAM
在[mysqld]下加入:
default-collation=utf8_bin
init_connect='SET NAMES utf8'
Copy after login

2. Add mysql_query("set names before the PHP program that needs to perform database operations 'Encoding'");, the encoding is consistent with the PHP encoding. If the PHP encoding is gb2312, then the mysql encoding is gb2312. If it is utf-8, then the mysql encoding is utf8, so that there will be no garbled characters when inserting or retrieving data

3. PHP is related to the operating system

The encoding of Windows and Linux is different. In the Windows environment, when calling PHP functions, if the parameters are utf-8 encoding, an error will occur, such as move_uploaded_file(), filesize(), readfile(), etc. These functions are often used when processing uploads and downloads. The following may occur when calling. The above error:

Warning: move_uploaded_file()[function.move-uploaded-file]:failed to open stream: Invalid argument in ...
Warning: move_uploaded_file()[function.move-uploaded-file]:Unable to move '' to '' in ...
Warning: filesize() [function.filesize]: stat failed for ... in ...
Warning: readfile() [function.readfile]: failed to open stream: Invalid argument in ..
Copy after login

Although these errors will not occur when using gb2312 encoding in a Linux environment, the saved file name will be garbled and the file cannot be read. In this case, the parameters can be converted to operating system recognition first. editor code, encoding conversion can use mb_convert_encoding (string, new encoding, original encoding) or iconv (original encoding, new encoding, string), so that the file name saved after processing is There will be no garbled characters, files can be read normally, and files with Chinese names can be uploaded and downloaded.

In fact, there is a better solution, which is to completely separate from the system, so there is no need to consider the encoding of the system. You can generate a sequence of only letters and numbers as the file name, and save the original name with Chinese characters in In the database, there will be no problem when calling move_uploaded_file(). When downloading, you only need to change the file name to the original name with Chinese characters.

The code to implement downloading is as follows

header("Pragma: public");
header("Expires: 0");
header("Cache-Component: must-revalidate, post-check=0, pre-check=0");
header("Content-type: $file_type");
header("Content-Length: $file_size");
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Content-Transfer-Encoding: binary");
readfile($file_path);
Copy after login

$file_type is the type of file, $file_name is the original name, and $file_path is the address of the file saved on the service.

Four. Let’s summarize why garbled characters appear

Generally speaking, there are two reasons for the appearance of garbled characters. The first is due to encoding (charset) Setting errors cause the browser to parse with the wrong encoding, resulting in a screen full of messy "heavenly books". Secondly, the file is opened with the wrong encoding and then saved. For example, a text file was originally It is encoded in GB2312, but it is opened and saved in UTF-8 encoding. To solve the above garbled code problem, you first need to know which aspects of development involve encoding:

1. File encoding:

refers to the page file (.html, .php, etc.) itself. What encoding is used to save it.

Notepad and Dreamweaver The file encoding will be automatically recognized when the page is opened, so there will be no problems. However, ZendStudio does not automatically recognize the encoding. It will only open the file in a certain encoding based on the configuration of the preferences. I accidentally opened the file with the wrong encoding while working, and after making the modifications, as soon as I saved it, garbled characters appeared (I know this very well).

2. Page declaration encoding:

In the HTML code HEAD, you can use To tell the browser what encoding is used for the web page. Currently, XXX mainly uses GB2312 and UTF-8 in Chinese website development.

3. Database connection encoding:

refers to which encoding is used to transmit data to the database when performing database operations. It should be noted here that it should not be confused with the encoding of the database itself, such as MySQL’s internal default It is latin1 encoding, which means that Mysql stores data in latin1 encoding, and data transmitted to Mysql in other encodings will be converted into latin1 encoding.

Knowing where coding is involved in WEB development, you also know the cause of garbled codes: the above three coding settings are inconsistent. Since most of the various codings are ASCII compatible, English The symbols won't appear, and Chinese is out of luck.

five. Some common error situations and solutions:

1. The database uses UTF8 encoding, and the page declaration encoding is GB2312 , which is the most common cause of garbled characters.

At this time, the direct SELECT data in the PHP script will be garbled. You need to use it before querying: mysql_query("SET NAMES GBK"); to set the MYSQL connection encoding and ensure that the page declaration encoding is consistent with the connection encoding set here (GBK is an extension of GB2312 ).

If the page is UTF-8 encoded, you can use: mysql_query("SET NAMES UTF8");
Note that it is UTF8 instead of the commonly used UTF-8.

If the encoding declared on the page is consistent with the internal encoding of the database, the connection encoding does not need to be set.

Note:

In fact, the data input and output of MYSQL is more complicated than what is mentioned above. There are 2 default encodings defined in the MYSQL configuration file my.ini, respectively. It’s in [client] default-character-set and default-character-set in [mysqld] To set the encoding used by default for client connections and internal databases respectively.

The encoding we specified above is actually the command line parameter when the MYSQL client connects to the server. character_set_client, to tell the MYSQL server what encoding the client data received is, instead of using the default encoding.

2. The page declaration encoding is inconsistent with the encoding of the file itself. This rarely happens because if the encoding is inconsistent, what the artist sees in the browser when creating the page will be garbled. More often than not, it is modified after publishing. Some minor bugs are caused by opening the page in the wrong encoding and then saving it.

Or you may use some FTP software to directly modify files online, such as CuteFTP. Due to incorrect software encoding configuration, the wrong encoding may result in conversion. code.

3. Some friends who rent virtual hosts still have garbled codes even though the above three encodings are set correctly. For example, the web page is GB2312 Encoded, IE and other browsers always recognize it as UTF-8 when opened. The page HEAD has stated that it is GB2312. Manually modify the browser encoding to GB2312. The subsequent page displays normally.

The reason is that the server Apache sets the global default encoding of the server and adds AddDefaultCharset in httpd.conf UTF-8 . At this time, the server will first send the HTTP header to the browser, and its priority is higher than the encoding declared in the page. Naturally, the browser will recognize it incorrectly.

There are two solutions. Please add the administrator to the configuration file of your virtual machine. AddDefaultCharset GB2312 to override the global configuration, or configure it in .htaccess in your own directory.

Summary:

In a word, the best and fastest way to solve PHP Chinese garbled code is that the encoding declared by the page is consistent with the internal encoding of the database. If the page The requested page number is inconsistent with the internal coding of the database , set the connection encoding, mysql_query("SET NAMES XXX ");

1.
Chinese garbled characters on the php page
Related video recommendations: 1.
Dugu Jiujian (4)_PHP video tutorial

The above is the detailed content of How to solve PHP Chinese garbled code? Introduction to three situations of Chinese garbled characters in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles