简体   繁体   English

使用非英文文件名上传图片

[英]Upload image with file name that not in english

I have the following PHP code: 我有以下PHP代码:

$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 此代码适用于名称为英文的文件(如'Example.jpg')但对于名称不是英文的文件,保存文件的名称为:''•'''•_'' ¡_1.jpg

Why and how can I fix it? 为什么以及如何解决它? Thanks! 谢谢!

In the php files the "receive" files, try to add: 在php文件中“接收”文件,尝试添加:

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

If you are working on apache, remember to check the value of AddDefaultCharset 如果您正在处理Apache,请记住检查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. 但正如某人的建议,我认为更好(避免上传具有相同名称的文件)以使用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. 您可以随时对该名称进行urlencode ,然后在显示或下载时进行urldecode

It's a bad idea to just pass raw data to a filesystem IMHO. 将原始数据传递给文件系统IMHO是个坏主意。 Over the years, we've seen hacks using filenames to enable remote execution, so I would urlencode it as a safety precaution anyway. 多年来,我们已经看到黑客使用文件名来启用远程执行,因此无论如何我都会将其作为安全预防措施进行urlencode

If you app is only accessible via a web interface, it's trivial to urldecode it before display. 如果您的应用只能通过网络界面访问,那么在显示之前对其进行urldecode是微不足道的。 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. 编辑:托马斯P的答案是可以的,但有人改变形式并导致各种问题是微不足道的。 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. 在收到帖子的文件(此处为send.php )上,应该正确接收所有内容。 You can check whether the sent name is correct using var_dump($_FILES) . 您可以使用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. 如果情况并非如此,那么您的表单可能不包含正确的编码声明(这意味着您没有包含<meta>标记,或者标题可能会覆盖<meta>标记。在这种情况下,包含<?php header('Content-type: text/html; charset=utf-8'); ?>处理上传表单的文件的开头。

You may look at this link to work with php and database like mysql using different languages. 您可以使用不同语言查看此链接以使用php和数据库(如mysql)。 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 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: 查看链接“Common Character Encodings”底部的常见编码类型,并选择适合您需求的类型:

http://en.wikipedia.org/wiki/Character_encoding 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. 使用mb_string允许不同的字符集你也可以尝试iconv到ASCII // TRANSLIT在保存之前在文件名上尝试其中一个。

HTH HTH

Try this 尝试这个

  1. Get the extension of file first; 首先获取文件的扩展名;
  2. Rename the file, like time().random(1,1000).$extension; 重命名文件,如time().random(1,1000).$extension;
  3. Recommendation: Use english file name, because it will be shown well at browser. 建议:使用英文文件名,因为它会在浏览器中很好地显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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