【问题标题】:How can I overwrite a file, when the file I want to upload already exists?当我要上传的文件已经存在时,如何覆盖文件?
【发布时间】:2015-07-23 22:02:55
【问题描述】:

如果文件夹中已存在文件,我想覆盖该文件。这是我的代码:

index.php

<form action="check.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit" value="upload">Upload</button>
</form> 

检查.php

if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $target_file = 'files/'.basename($_FILES["file"]["name"]);
    if (file_exists($target_file)) {
        echo "File already exist";                  
        echo "<form action='overwrite.php' method='post'>
                <button type='submit'> Overwrite</button>
            </form>";
    } 
}

覆盖.php

move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo "The file is overwritten";

更新:我的问题有误。现在我改变了它。在 check.php 上应该只有语句“文件已经存在”和一个指向 overwrite.php 并覆盖文件的按钮。 (没有第二个输入字段)

【问题讨论】:

  • overwrite.php 中的全局变量$_FILES 为空。
  • 检查您的脚本是否有权覆盖该文件。或者,创建一个唯一的字符串作为文件名,以避免此问题。

标签: php


【解决方案1】:

当您再次创建表单时,您需要指定enctype="multipart/form-data"

 echo "<form action='overwrite.php' method='post' enctype='multipart/form-data'>
        <input type='file' name='file'>
        <button type='submit'> Overwrite</button>
    </form>";

没有enctype="multipart/form-data"它不会让你执行文件上传操作

除了那个名字不应该是一个值,它应该是静态的,所以你可以使用它

【讨论】:

  • 嗨,我按照你的建议改了,但还是不行
  • 将名称从$target_file改为静态file
  • 如果脚本没有权限这样做,这不会覆盖文件。
  • 我做到了。我的零钱:&lt;input type='file' name='file' enctype='multipart/form-data'&gt;。但还是不行
  • @jarla 哥们,你做错了,enctype='multipart/form-data' 应该添加到form 标签中,并保持你的输入名称为&lt;input type='file' name='file'&gt;。看到我的回答我还没有发布这样的东西
【解决方案2】:

您正在访问$_FILES["file"],但除非$target_file==="file",否则您什么也找不到。

将文件上传的name属性从$target_file改为file

        echo "<form action='overwrite.php' method='post'>
                <input type='file' name='file'>
                <button type='submit'> Overwrite</button>
            </form>";

【讨论】:

  • 你在使用var_dump($_FILES)时看到了什么?
  • 抱歉,我的问题有误。在 check.php 上不应该有一个新的输入字段,只有一个按钮说覆盖。所以在我的 check.php 上应该只有语句“文件已经存在”和一个指向 overwrite.php 并覆盖文件的按钮。
  • 你知道如何让代码在 check.php 上没有输入字段的情况下工作吗?
猜你喜欢
  • 2021-02-10
  • 2017-10-29
  • 2017-10-03
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2015-07-22
  • 1970-01-01
相关资源
最近更新 更多