【问题标题】:PHP - move_uploaded_file replace spaces with %20PHP - move_uploaded_file 用 %20 替换空格
【发布时间】:2019-10-02 21:51:35
【问题描述】:

我正在使用 move_uploaded_file 上传文件,但是当我上传带有空格的文件时,它不会替换为 %20,然后我被带空格的文件名卡住了,我该如何解决这个问题?

这是我的代码:

$target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["logoHeader"]["name"]);
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));


        if(isset($_POST["submit"])) {
            $check = getimagesize($_FILES["logoHeader"]["tmp_name"]);
            if($check === false) {

                $error = 'File is not an image.';

                include('views/logos/index.php');

                break;

            }
        }

        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {

            $error = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.';

            include('views/logos/index.php');

            break;

        }

        if (move_uploaded_file($_FILES["logoHeader"]["tmp_name"], $target_file)) {

            $error = 'Image has been uploaded.';

        }
        else
        {
            $error = 'Sorry, there was an error uploading your file.';

            include('views/logos/index.php');

            break;
        }

【问题讨论】:

  • %20 只是浏览器与服务器通信过程中 URL 编码的一部分,不应保留在应用程序中。
  • 后记 我将文件路径保存在数据库中,我应该在那里做吗?
  • 不,它只用于浏览器到服务器的通信,其他任何地方都不需要。
  • 它是来自客户的请求......
  • 您可以按照@Barmar 的建议进行操作,或者用下划线替换所有空格并将其保存为文件名。这样它就会对文件和数据库友好。

标签: php file-upload spaces


【解决方案1】:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["logoHeader"]["name"]);
//new line
$target_file = checkName($target_file);
//end new line
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//your code

并添加checkName函数

function checkName($name){
    if(preg_match("`^[-0-9A-Z_\.]+$`i",$name)){
        return $name;
    }else{
        $name = str_replace(' ', '%20', $name);
        return $name;
    }

但你仍然不能幸免于其他“难以理解”的角色。如果文件名包含 URL 不允许的字符,您将如何提供该文件? 例如:ÆÞΔΦÜЩЫž.jpg

尝试查找有关 URL slug 的更多信息;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2012-03-03
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    相关资源
    最近更新 更多