【问题标题】:Replace spaces with an underscore in PHP while uploading file上传文件时在PHP中用下划线替换空格
【发布时间】:2017-11-17 01:17:40
【问题描述】:

我有一个允许用户上传图片的脚本。我正在研究从图像集合中抓取随机图像的东西,但是空格似乎与 url 搞砸了,这意味着我需要弄清楚如何用 _s 替换空格。

<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $target_file = str_replace(' ', '_', $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

正如您在此处看到的,我尝试添加 $target_file = str_replace(' ', '_', $target_file;) 来替换字符串,但是上传的图像仍然带有空格。我怎样才能使这项工作?

【问题讨论】:

  • 您在实际使用后更改 $target_file 字符串 -- 所以它不会起作用也就不足为奇了

标签: php


【解决方案1】:

因为你上传后替换了,你应该在上传前替换。

<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    $target_file = str_replace(' ', '_', $target_file);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

【讨论】:

    【解决方案2】:

    在您的代码中,仅替换文件名字符串的内容。

    它不会改变实际的文件名。

    你需要在move_uploaded_file之前使用str_replace

    【讨论】:

      【解决方案3】:

      你的代码应该是:

      <?php
      $target_dir = "images/";
      $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
      $uploadOk = 1;
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
      // Check if $uploadOk is set to 0 by an error
      if ($uploadOk == 0) {
          echo "Sorry, your file was not uploaded.";
          // if everything is ok, try to upload file
      } else {
          $target_file = str_replace(' ', '_', $target_file);
          if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],  $target_file)) {
              echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
          } else {
              echo "Sorry, there was an error uploading your file.";
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多