Take content from one text file and put it in another with PHP?
i need help with this one , is there any ways when i amend file1.txt
to send the old information to file2.txt
and so on. I have 4 files like this and i want to swap the content inside them when file1.txt
is changed .
Like this when content in first one changed send old content in the chain file1.txt
--> file2.txt
--> file3.txt
--> file4.txt
thats my php file
$myfile = fopen("file1.txt", "w") or die("Unable to open file!");
fwrite($myfile, "Today we had 11 people");
fclose($myfile);
my idea is to send This content of strings "Today we had 11 people"
to second file , when content in file1.txt
is changed to lets say "Today we had 23 people"
Easy/pragmatic way to do that would be copy the files in the chain.
function copyFiles(string $newLine): void
{
exec("cp path/to/file3.txt path/to/file4.txt");
exec("cp path/to/file2.txt path/to/file3.txt");
exec("cp path/to/file1.txt path/to/file2.txt");
exec("echo $newLine >> path/to/file1.txt");
}
Note: For this approach, you may need to talk to your host to see if it is allowed at all. not every host allows cp
commands via php exec.
suggestion from @Will
You can also use the rename() function instead of exec() for this.
rename("/test/file1.txt","/home/docs/my_file.txt");
Thank you to @Maik Lowrey for the answer , how he noted cp
is not allowed on my host. Instead of that i used the idea of @Will and worked perfectly ! THANK YOU BOTH :)
function copyFiles(string $newLine): void
{
rename( "file3.txt", "file4.txt");
rename("file2.txt", "file3.txt");
rename("file1.txt", "file2.txt");
exec("echo $newLine >> file1.txt");
}