【问题标题】:Replace all the spaces in a file’s name with an underscore during the upload process在上传过程中将文件名中的所有空格替换为下划线
【发布时间】:2016-09-05 11:56:27
【问题描述】:

我有一个名为upload_file.php 的文件,它将图像文件上传到我的网络服务器。我遇到的问题是我想在上传过程中用下划线替换文件名中的所有空格。我知道这可以使用 str_replace() 来完成,但我不知道在我的代码中应该在哪里使用 str_replace()。任何帮助将不胜感激。

这是我的 upload_file.php 文件中包含的完整代码:

<?php
require_once '../../config.php';
include '../secure.php';
if ($login_status != 1) exit();
if (isset($_GET['done'])) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
    else {
        if ($_POST['type'] == 'wallpaper') {
            $directory = "../../files/";
        }
        else {
            $directory = "../../files/images/"; 
        }

        $filename = basename($_FILES['file']['name']);
        $ext = substr($filename, strrpos($filename, '.') + 1);

        if (file_exists($directory . $_FILES["file"]["name"])) {
            echo htmlspecialchars($_FILES["file"]["name"]) . " already exists. ";
        }
        elseif (((strpos($ext, "php") !== false) || $ext == 'aspx' || $ext == 'py' || $ext == 'htaccess') && !isset($allow_php_uploads)) {
            echo 'Uploading PHP files disabled (<a target="_blank" href=""></a>)';
        }
        else {
            move_uploaded_file($_FILES["file"]["tmp_name"], $directory . $_FILES["file"]["name"]);
            header("Location: upload-complete.php?type=".htmlspecialchars($_POST['type'])."&newfile=". htmlspecialchars($_FILES["file"]["name"])."&id=".intval($_POST['id'])."");
        }
    }
} else { ?>

<head>
 <style type="text/css">
 body {
     margin:0px;
     padding:0px;
 }
 </style>
 </head>

 <form action="upload_file.php?done=1" method="post"
enctype="multipart/form-data">
  <input type="file" name="file" id="file" style="max-width:230px;" />
  <input name="id" type="hidden" value="<?php echo intval($_GET['id']);?>" />
  <input name="type" type="hidden" value="<?php echo htmlspecialchars($_GET['type']);?>" />
  <input type="submit" name="submit" value="Upload" />
</form>
<?php } ?>

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以创建一个包含文件名的变量并替换其中的所有空格。然后在其余代码中,将$_FILES["file"]["name"] 替换为该变量。

    <?php
    require_once '../../config.php';
    include '../secure.php';
    if ($login_status != 1) exit();
    if (isset($_GET['done'])) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
        else {
            if ($_POST['type'] == 'wallpaper') {
                $directory = "../../files/";
            }
            else {
                $directory = "../../files/images/"; 
            }
    
            $filename = basename($_FILES['file']['name']);
            $file = preg_replace('/\s+/', '_', $_FILES['file']['name']);    // <-- Replace spaces
            $ext = substr($filename, strrpos($filename, '.') + 1);
    
            if (file_exists($directory . $file)) {
                echo htmlspecialchars($file) . " already exists. ";
            }
            elseif (((strpos($ext, "php") !== false) || $ext == 'aspx' || $ext == 'py' || $ext == 'htaccess') && !isset($allow_php_uploads)) {
                echo 'Uploading PHP files disabled (<a target="_blank" href=""></a>)';
            }
            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], $directory . $file);
                header("Location: upload-complete.php?type=".htmlspecialchars($_POST['type'])."&newfile=". htmlspecialchars($file)."&id=".intval($_POST['id'])."");
            }
        }
    } else { ?>
    
    <head>
     <style type="text/css">
     body {
         margin:0px;
         padding:0px;
     }
     </style>
     </head>
    
     <form action="upload_file.php?done=1" method="post"
    enctype="multipart/form-data">
      <input type="file" name="file" id="file" style="max-width:230px;" />
      <input name="id" type="hidden" value="<?php echo intval($_GET['id']);?>" />
      <input name="type" type="hidden" value="<?php echo htmlspecialchars($_GET['type']);?>" />
      <input type="submit" name="submit" value="Upload" />
    </form>
    <?php } ?>
    

    【讨论】:

    • 优秀的答案。您的代码完美运行。谢谢你。尽管我确实更改了以下代码: $file = preg_replace('/\s+/', '', $_FILES['file']['name']);到:$file = str_replace(" ", "", $_FILES['file']['name']);
    • 我刚刚在第一次回复你时注意到,在我输入的两个代码中,单引号和双引号之间的下划线会被 stackoverflow 自动删除。
    【解决方案2】:

    您必须尝试通过白名单和替换功能将空格替换为下划线。所以你可以这样做:

    $file = preg_replace("/[^-_a-z0-9]+/i", "_", $file);
    

    我现在无法测试它,但类似的东西应该可以正常工作。基本上就是替换掉不在“[^-_a-z0-9]+/i”白名单中的字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 2022-11-23
      • 1970-01-01
      • 2014-01-14
      • 2020-05-27
      • 2015-11-03
      • 1970-01-01
      相关资源
      最近更新 更多