User_T
User_T

Reputation: 267

PHP file upload wrong file name encoding

Im doing a webpage and have a problem with file upload, that changes the file name umlauts into a weird name.

For example when i upload a file called "töö.docx" and look at the name in the uploaded folder, it shows me this "tƶƶ.docx".

When i call out the name of the file in index.php it shows me the correct name "töö.docx".

But after i go into the upload folder and change the name "tƶƶ.docx" manually into "töö.docx" and than call out the name of the file in index.php, it shows me "t��.docx" which is wrong.

Here is the code for upload in index.php:

<form method="post" enctype="multipart/form-data">
  <strong>File upload:</strong>
  <small>(max 8 Mb)</small>
  <input type="file" name="fileToUpload" required>
  <input type="submit" value="Upload" name="submit">
</form>

And here is the upload controller code:

$doc_list = array();
   foreach (new DirectoryIterator('uploads/') as $file)
{
   if ($file->isDot() || !$file->isFile()) continue;
   $doc_list[] = $file->getFilename();
}

$target_dir = "uploads/";
$target_file = $target_dir . basename( isset($_FILES["fileToUpload"]["name"]) ? $_FILES["fileToUpload"]["name"] : "");
$file = isset($_FILES["fileToUpload"]) ? $_FILES["fileToUpload"] : "";
$up_this = isset($_FILES["fileToUpload"]["tmp_name"]) ? $_FILES["fileToUpload"]["tmp_name"] : "";
$file_name = isset($_FILES["fileToUpload"]["name"]) ? $_FILES["fileToUpload"]["name"] : "";

if (!empty($file)) {
    if(isset($_POST["submit"])) {
        if (file_exists($file_name)) {
            echo "File already exists.";
            exit;
        } else {
            $upload =  move_uploaded_file($up_this, $target_file);
            if ($upload) {
                echo "File ". '"' . basename($file_name). '"' . " has been uploaded";
            } else if (!$upload) {
                echo "Could not upload file";
                exit;
            }
        }
    }
}

I use the variable $doc_list to call out the names of the documents in folder in index.php:

<div>
    <?php if (!empty($doc_list)) foreach ($doc_list as $doc_name) { ?>
        <tr>
            <td><?= $doc_name ?></td>
        </tr>
    <?php } ?>
</div>

I've set the website charset into utf-8. and i still don't know why it's not displaying the correct file name with umlauts.

Upvotes: 0

Views: 1780

Answers (2)

Enes Kalajac
Enes Kalajac

Reputation: 1

Try to add accept-charset="ISO-8859-1" instead "UTF-8":

<form method="post" enctype="multipart/form-data" accept-charset="ISO-8859-1">

Upvotes: 0

Michal Przybylowicz
Michal Przybylowicz

Reputation: 1668

Try to add accept-charset="UTF-8" like this:

<form method="post" enctype="multipart/form-data" accept-charset="UTF-8">

Upvotes: 1

Related Questions