PHP 创建具有特定名称的文件

PHP create file with specific name

此创建新文件的代码运行良好:

<?php
$myfile = fopen("LMS-NUMBER.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

我想创建名称如下的文件:LMS-001.txt、LMS-002.txt、LMS-003.txt 等。 或 LMS-1.txt、LMS-2.txt、LMS-3.txt。我更喜欢这种格式:LMS-001

谢谢


我想通过提交一个表单来创建更多文件。所以在重新点击提交按钮后,将创建如下文件:

1st click = LMS-1.txt;
2nd click = LMS-2.txt;
3rd click = LMS-3.txt;

尽管正如评论中指出的那样,您的问题不清楚,但我想我明白您想做什么,尽管如前所述,您应该编辑问题以使其更清楚。

如果我是对的,你问的是如何创建一个数字后缀比以前的文件大一的新文件,以防止覆盖。一种简单的方法是使用 for() 循环检查核心文件名 + 计数是否已经存在,并继续直到找到一个不存在的文件。然后,您可以将文件名存储在文件不存在的循环迭代中,最后写入具有该名称的新文件。举个例子;

<?php
    /* Here you can set the core filename (from your question, "LMS"),
    as well as the number of maximum files. */
    $coreFileName   = "LMS";
    $maxFilesNum    = 100;

    // Will store the filename for fopen()
    $filename = "";

    for($i = 0; $i < $maxFilesNum; $i++)
    {
        // File name structure, taken from question context
        $checkFileName = $coreFileName . "-" . str_pad($i, 3, 0, STR_PAD_LEFT) . ".txt";

        // If the file does not exist, store it in $filename for writing
        if(!file_exists($checkFileName))
        {
            $filename = $checkFileName;
            break;
        }
    }

    $fd = fopen($filename, "w");
    fwrite($fd, "Jane Doe"); // Change string literal to the name to write to file from either input or string literal
    fclose($fd); // Free the file descriptor

我已经对其进行了测试并且它有效,因此每次刷新页面时都会创建一个新文件,其数字后缀比先前创建的文件高 1。我已经这样做了,所以它最多只能创建 100 个文件,您可以使用顶部附近的 $maxFilesNum 变量随意调整它,但是我建议设置一个限制,以便您的文件系统在本地或远程服务器不会被文件淹没。

编辑: 现在包括 001、002 ... 100 的填充