Home > Article > Backend Development > How to Upload Vietnamese Files with UTF-8 Encoded Filenames in PHP?
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>
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>
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!