Home Backend Development PHP Tutorial Summary and analysis of solutions to Chinese garbled characters in PHP_PHP tutorial

Summary and analysis of solutions to Chinese garbled characters in PHP_PHP tutorial

Jul 21, 2016 pm 03:44 PM
php one and Chinese Garbled characters analyze Method match Summarize document of coding Web page solve

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 should output the header: header(“Content-Type: text /html; charset=gb2312″), add to the static page. The encoding format of all files is ANSI and can be opened with Notepad. , save as and select encoding as ANSI, overwriting 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 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, errors will occur, such as move_uploaded_file(), filesize() , readfile(), etc. These functions are often used when processing uploads and downloads. The following error may occur when calling:
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 ..
Although these errors will not occur when using gb2312 encoding in a Linux environment, the file name after saving will be garbled. As a result, the file cannot be read. In this case, you can first convert the parameters into the encoding recognized by the operating system. For encoding conversion, you can use mb_convert_encoding (string, new encoding, original encoding) or iconv (original encoding, new encoding, string). After processing, The saved file name will not be garbled, and the file can be read normally, allowing uploading and downloading of files with Chinese names.
In fact, there is a better solution, which is to completely disconnect 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 the database. In this way, 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. Chinese name. 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);
$file_type is the type of file, $file_name is the original name, $file_path is the address of the file saved on the service.
4. Let’s summarize why garbled characters appear
Generally speaking, there are two reasons for the occurrence of garbled characters. The first is due to the incorrect encoding (charset) setting, which causes the browser to parse with the wrong encoding, resulting in a messy screen. The second is that the file is opened in the wrong encoding and then saved. For example, a text file was originally encoded in GB2312, but was opened in UTF-8 encoding and then saved. To solve the above garbled code problem, you first need to know which aspects of development involve encoding:
1. File encoding: refers to the encoding in which the page file (.html, .php, etc.) itself is saved. Notepad and Dreamweaver will automatically recognize the file encoding when opening the page, so there will be less problems. However, ZendStudio does not automatically recognize the encoding. It will only open the file in a certain encoding according to the configuration of the preferences. If you accidentally open the file with the wrong encoding while working, and save it after making the modification, garbled characters will appear ( I feel it deeply).
2. Page declaration encoding: In the HTML code HEAD, you can use to tell the browser that the web page uses What encoding is used? 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. This is required here. Be careful not to confuse it with the encoding of the database itself. For example, MySQL's internal default encoding is latin1 encoding, which means that Mysql stores data in latin1 encoding. Data transmitted to Mysql in other encodings will be converted into latin1 encoding.
Know. After understanding where encoding is involved in WEB development, we also know the reason for the garbled code: the above three encoding settings are inconsistent. Since most of the various encodings are compatible with ASCII, English symbols will not appear, and Chinese characters will be unlucky.
5. Fight some common error situations and solutions:
1. The database uses UTF8 encoding, and the page declaration encoding is GB2312. This is the most common cause of garbled characters at this time. The direct SELECT data in the PHP script is 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 GB2312 extension). 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 by the page is consistent with the internal encoding of the database. It is not necessary to set the connection encoding.
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, which are default - in [client]. character-set and default-character-set in [mysqld] respectively set the encoding used by the client connection and the database internally. The encoding we specified above is actually the command line parameter character_set_client when the MYSQL client connects to the server. To tell the MYSQL server what encoding the client data received is used 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, the artist will create the page. What you see in the browser is garbled characters. Most of the time it is caused by fixing some minor bugs after publishing, opening the page in the wrong encoding and then saving it. Or you use some FTP software to directly modify files online, such as CuteFTP. Due to incorrect software encoding configuration, the wrong encoding is converted.
3. Some friends who rent virtual hosts still have garbled codes even though the above three encodings are set correctly. For example, if the web page is encoded in GB2312, it is always recognized as UTF-8 when opened by browsers such as IE. The HEAD of the web page has already stated that it is GB2312. After manually changing the browser encoding to GB2312, the page displays normally. The reason is that the server Apache sets the global default encoding of the server and adds AddDefaultCharset UTF-8 in httpd.conf. 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. Administrators should add AddDefaultCharset GB2312 to the configuration file of their own virtual machine to override the global configuration, or configure it in .htaccess in their own directory.

Summary: In a word, the best and fastest way to solve the Chinese garbled code in PHP is to make the coding declared by the page consistent with the internal coding of the database. If the page number applied for the page is inconsistent with the internal coding of the database, set Set the connection code, mysql_query("SET NAMES XXX"); XXX is the connection code. This will definitely solve the problem of garbled characters.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320460.htmlTechArticle1. 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 should output the header: header(“Content-Type: text/html;...
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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 do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles