简体   繁体   中英

Upload image with file name that not in english

I have the following PHP code:

$allowedExts = array("gif", "jpeg", "jpg", "png", "PNG", "JPG", "JPEG", "GIF");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
     || ($_FILES["file"]["type"] == "image/jpeg")
     || ($_FILES["file"]["type"] == "image/jpg")
     || ($_FILES["file"]["type"] == "image/pjpeg")
     || ($_FILES["file"]["type"] == "image/x-png")
     || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 2000000)
    && in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $file_name = "images/".$_FILES["file"]["name"];
        if (file_exists("../images/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
        } else {
            move_uploaded_file(
                $_FILES["file"]["tmp_name"],
                "../images/" . $_FILES["file"]["name"]
            );
            echo "Stored in: " . "../images/" . $_FILES["file"]["name"];
        }
    }
} else {
    echo "Invalid file";
}

This code works fine for files that their name is in English (like 'Example.jpg') But for files that their names are not in english the name of the saved file is Gibberish like : ׳׳•׳'׳•_׳׳¡_1.jpg

Why and how can I fix it? Thanks!

In the php files the "receive" files, try to add:

 <?php header('Content-type: text/html; charset=utf-8');

If you are working on apache, remember to check the value of AddDefaultCharset

AddDefaultCharset Off

This could solve your naming files. But as suggestet by someone, I think is better (avoiding uploading of files with same name) to save file names in file system with hashvalue.

$tmpFile = $_FILES["file"]["tmp_name"];
$fileName = $_FILES["file"]["name"];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$newFileName = "../images/" . md5(time() . $fileName) . ;
move_uploaded_file($tmpFile, $newFileName);
echo "Stored in: " . "../images/" . newFileName;

I always save in database original name, and hashed name. This, because I want to keep saved original name even if I upload hundred files with same name, but I do not want to override file system files. There are a lot of trick to avoid this kind of name collision ...

You could always just urlencode the name, then urldecode on display or download.

It's a bad idea to just pass raw data to a filesystem IMHO. Over the years, we've seen hacks using filenames to enable remote execution, so I would urlencode it as a safety precaution anyway.

If you app is only accessible via a web interface, it's trivial to urldecode it before display. If there is some local access to the filesystem, then you would probably want to retain the real filename.

Edit: Thomas P's answer is OK, but it's trivial for someone to change the form and cause all kinds of issues. In general, it's much safer to handle exceptions & formatting server side and to always assume a user will input garbage data.

Your code is absolutely working. You just need some adjustments about encoding.

In order to make sure the filename is encoded correctly when the browser sends it (so that the server receives it correctly, you must define a correct encoding but on the page that includes the upload form.

Indeed, once a browser sends a request, it cannot change it, even if the response (as other responses suggest it), defines an encoding. This means that, if you want to get a clean filename, you must set properly encoding on the upload form page.

Here is a working example :

<!DOCTYPE html>
<html>
<head>
     <title>My awesome form</title>
     <meta charset="utf-8" /><!-- This is the important tag -->
</head>
<body>
    <form action="send.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit" />
    </form>
</body>
</html>

On the file that receives the post (here send.php ), everything should be received correctly. You can check whether the sent name is correct using var_dump($_FILES) . If that's not the case, then your form probably doesn't include a proper encoding declaration (which means you didn't include the <meta> tag, or an header is maybe overwriting the <meta> tag. In that case, include <?php header('Content-type: text/html; charset=utf-8'); ?> at the beginning of the file handling the upload form.

You may look at this link to work with php and database like mysql using different languages. I hope it helps you.

As they said in this link you may try:

<meta http-equiv="Content-Type" content="text/html; 
charset=UTF-8" />

http://www.9lessons.info/2011/08/foreign-languages-using-mysql-and-php.html

Update

Look at the common encoding types at the bottom of the link "Common Character Encodings" and choice what suits your needs:

http://en.wikipedia.org/wiki/Character_encoding

I would read the following forum read this . You should rename the file i guess so that you don't get Gibberish names. If you want the real name of the file the forum i provided you with provides a solution.

use mb_string to allow different charsets You may also try the iconv to ASCII//TRANSLIT Try one of these on the filename prior to save.

HTH

Try this

  1. Get the extension of file first;
  2. Rename the file, like time().random(1,1000).$extension;
  3. Recommendation: Use english file name, because it will be shown well at browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM