0

I have been doing some work with php, and I need a system that allows a particular file from /home/user/Desktop/myfile.txt to be copied to /home/user/Documents, but I do not want the file to override any other files named myfile.txt in the destination folder, but rather add a number to show the increment in which it was added, Ex: myfile(2).txt

Is there a way to do this in php and if so can you please help with an example, as I do not fully understand how the adding a number increasing in value would work. thank you

I have been trying to use a counter function to keep track of how many times the php script has been run and just add that number to the end of the file name, so I have included the code I have so far here (note: this script nearly does what I need, but I can't get the number added to the end of the name):

<?php
session_start();
$counter_name = "counter.txt";
$oldfile = "/home/user/Desktop/counter.txt";


 if (!file_exists($counter_name)) {
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}

$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);


if(!isset($_SESSION['hasVisited'])){
  $_SESSION['hasVisited']="yes";
  $counterVal++;
  $f = fopen($counter_name, "w");
 fwrite($f, $counterVal);
 fclose($f); 
}
copy($oldfile, '/home/user/Desktop/counter($counterVal).txt');

echo "This script has been run $counterVal times";
user890199
  • 153
  • 1
  • 1
  • 8

1 Answers1

0
<?php
session_start();
$counter_name = "counter.txt";
$oldfile = "/home/user/Desktop/counter.txt";


 if (!file_exists($counter_name)) {
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}

$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);


if(!isset($_SESSION['hasVisited'])){
  $_SESSION['hasVisited']="yes";
  $counterVal++;
  $f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f); 
}
copy($oldfile, "/home/user/Desktop/counter($counterVal).txt");

echo "This script has been run $counterVal times";

It may not be the most elegant way to do this, but this script paired with a similar script to remove 1 every time it is run by changing the ++ to -- will work fine for me.

user890199
  • 153
  • 1
  • 1
  • 8