简体   繁体   English

防止文件覆盖php

[英]Preventing file overwriting php

im creating a website where there is two textboxes.我正在创建一个有两个文本框的网站。 One for the file name and one for the content.一种用于文件名,一种用于内容。 When you hit submit it will create a file in a specific folder based on what you wrote.当您点击提交时,它将根据您编写的内容在特定文件夹中创建一个文件。 This all works well, but if you write the same file name and different content it will overwrite the file.这一切都很好,但是如果您编写相同的文件名和不同的内容,它将覆盖该文件。 I just want the file to be closed for writing after submitting so no one can mess with others files.我只想在提交后关闭文件以进行写入,这样就没有人可以弄乱其他文件。 Heres my php code:继承人我的PHP代码:

    <?php
$filnavn=$_POST["filnavn"];
$innhold=$_POST["innhold"];

if($filnavn!=""){
    $myfile = fopen(dirname(__FILE__)."/lekser/".$filnavn.".txt", "w") or die("Feil! Klarer ikke å skrive filen. Prøv igjen.");
    fwrite($myfile, $innhold);
    fclose($myfile);
}
?>

Add a condition that checks whether or not the file already exists using file_exists() :添加使用file_exists()检查文件是否已存在的条件:

<?php
$filnavn = $_POST["filnavn"];
$innhold = $_POST["innhold"];
$path = dirname(__FILE__) . "/lekser/" . $filnavn . ".txt";

if ($filnavn != "" && file_exists($path))
{
    $myfile = fopen($path, "w") or die("Feil! Klarer ikke å skrive filen. Prøv igjen.");
    fwrite($myfile, $innhold);
    fclose($myfile);
}

?>

I'm not sure what is the expected result, so I give a totally different answer:我不确定预期的结果是什么,所以我给出了一个完全不同的答案:

if you use fopen($path, "a") instead of fopen($path, "w") , you'll append the content to the existing file instead of replacing it.如果您使用fopen($path, "a")而不是fopen($path, "w") ,您会将内容附加到现有文件而不是替换它。

Try this::尝试这个::

$filnavn = $_POST["filnavn"];
$innhold = $_POST["innhold"];
$path = dirname(__FILE__) . "/lekser/" . $filnavn . ".txt";

If file not exists then create a new file::如果文件不存在则创建一个新文件::

if ($filnavn != "" && !file_exists($path))
{
    $myfile = fopen($path, "w") or die("Feil! Klarer ikke å skrive filen. Prøv igjen.");
    fwrite($myfile, $innhold);
    fclose($myfile);
}

If file exist, append new content at bottom of existing file contents:如果文件存在,则在现有文件内容的底部追加新内容:

if ($filnavn != "" && file_exists($path))
    {
        $myfile = fopen($path, "a") or die("Feil! Klarer ikke å skrive filen. Prøv igjen.");
        fwrite($myfile, $innhold);
        fclose($myfile);
    }

If not want to make any change in existing file then create new file with adding number with file name如果不想对现有文件进行任何更改,则创建新文件,并在文件名中添加编号

  if ($filnavn != "" && file_exists($path))
            {   // just add number with file name, for versioning
               $path = dirname(__FILE__) . "/lekser/" . $filnavn . "1.txt";
                $myfile = fopen($path, "w") or die("Feil! Klarer ikke å skrive filen. Prøv igjen.");
                fwrite($myfile, $innhold);
                fclose($myfile);
            }

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

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