【问题标题】:php copy file and add number to end if file exists [duplicate]如果文件存在,php复制文件并添加数字到结尾[重复]
【发布时间】:2018-11-19 04:07:25
【问题描述】:

我一直在使用 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";

【问题讨论】:

  • 您能否将您的代码添加到问题中,因为修改它可能比编写新内容更容易。
  • 我在中添加了代码
  • 当你使用单引号时,变量替换不起作用,所以将'/home/user/Desktop/counter($counterVal).txt'的引号改为双引号。
  • 是的,我在发布后立即意识到,谢谢你并在下面添加了我要处理的内容
  • 只是一个建议,file_get_contentsfile_put_contents 会稍微整理一下您的代码。

标签: php file directory copy


【解决方案1】:
<?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 通过将 ++ 更改为 -- 对我来说很好。

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 2013-11-25
    • 1970-01-01
    • 2014-01-04
    • 2012-11-03
    • 2014-07-04
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多