php复制文件并在文件存在时添加数字

时间:2018-06-09 07:03:57

标签: php file directory copy

我一直在用php做一些工作,我需要一个允许将/home/user/Desktop/myfile.txt中的特定文件复制到/ home / user / Documents的系统,但我不想要文件覆盖目标文件夹中名为myfile.txt的任何其他文件,而是添加一个数字以显示添加它的增量,例如:myfile(2).txt

有没有办法在php中执行此操作,如果是这样,请您帮助一个示例,因为我不完全了解添加数值增加的数字是如何工作的。谢谢

我一直在尝试使用计数器功能来跟踪php脚本运行了多少次,只是将该数字添加到文件名的末尾,所以我已经包含了我到目前为止的代码(注意:这个脚本几乎可以满足我的需求,但是我无法将这个数字添加到名称的末尾):

<?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";

1 个答案:

答案 0 :(得分: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";

这可能不是最优雅的方式,但是这个脚本与一个类似的脚本配对,每次运行时通过将++更改为 - 来删除1将对我有用。