How to Upload Vietnamese Files with UTF-8 Encoded Filenames in PHP?

Linda Hamilton
Release: 2024-10-31 13:17:01
Original
929 people have browsed it

How to Upload Vietnamese Files with UTF-8 Encoded Filenames in PHP?

PHP - Encoding UTF-8 Filenames While Uploading

Vietnamese characters infilenames can pose an issue during upload when using PHP. Let's explore a solution to ensure proper handling of UTF-8 filenames.

Consider the following code:

<code class="php">$base_dir = "D:/";
$fn = $_FILES["upload"]["name"];
$fn2 = $base_dir . $fn;
move_uploaded_file($_FILES["upload"]["tmp_name"], $fn2);</code>
Copy after login

This code retrieves the uploaded filename, appends it to a base directory, and moves the file to the specified location. However, the resulting filename on the local computer may appear corrupted with accented characters replaced by character codes.

To fix this, we need to convert the filename from UTF-8 to a code page that is compatible with the local operating system. Windows systems typically use a code page that is specific to the region or language settings. The code page can be determined using the chcp command in the command prompt.

Solution 1: Convert Filename to System Code Page

Using the iconv function, we can convert the filename to the appropriate code page. For example, if the system code page is 1258, we can use the following code:

<code class="php">$fn2 = iconv("UTF-8", "cp1258", $base_dir . $fn);</code>
Copy after login

Solution 2: Change System Code Page

An alternative solution is to change the system code page to the target code page, typically a UTF-8 compatible one. This can be done by navigating to the Control Panel, selecting "Region," and changing the "Administrative" tab to the appropriate locale, such as Vietnamese (Vietnam).

Once the system code page has been changed, the uploaded filename will be handled correctly and will display with the UTF-8 characters intact. However, it's important to note that this solution may affect other system functions that rely on the code page, such as printing and viewing text files.

The above is the detailed content of How to Upload Vietnamese Files with UTF-8 Encoded Filenames in PHP?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template