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
$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()
:
<?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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.