【问题标题】:Make a textbox generate text files like t1.txt t2.txt t3.txt, and so on使文本框生成文本文件,如 t1.txt t2.txt t3.txt 等
【发布时间】:2013-08-31 17:30:37
【问题描述】:

我的网站上有这段代码:

        <form name="form" method="post">
            <input type="text" name="text_box" size="50"/>
            <input type="submit" id="search-submit" value="submit" />
        </form>
<?php
    if(isset($_POST['text_box'])) { //only do file operations when appropriate
        $a = $_POST['text_box'];
        $myFile = "t.txt";
        $fh = fopen($myFile, 'w') or die("can't open file");
        fwrite($fh, $a);
        fclose($fh);
    }
?>

我想做的事情是,当已经有一个 t.txt 时,它会创建一个 t2.txt,然后是 t3.txt 等等,所以它不会覆盖文本上一个 t.txt。

【问题讨论】:

    标签: php forms post text methods


    【解决方案1】:

    对于非递归解决方案:

    $count = 0;
    while (true)
    {
        if (!file_exists("t".++$count.".txt") 
        {
            write to file here...
            break;
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以创建一个检查文件是否存在的函数..

      function checkFile($x) {
      
      
        $file = "t".$x.".txt";
      
        if (file_exists($file) {
      
          checkFile(($x+1));
      
        } else {
      
          //make a file
      
        }
      
      }
      

      编辑:

       if(isset($_POST['text_box'])) {
      
        $a = $_POST['text_box']; 
        $myFile = "t.txt";
      
        if (!file_exists($myFile)) {
      
          $fh = fopen($myFile, 'w') or die("can't open file"); 
          fwrite($fh, $a); 
          fclose($fh);
      
        } else {
      
          checkFile(1,$a);
      
        }
      
      }
      
      function checkFile($x,$a) {
      
      
        $file = "t".$x.".txt";
      
        if (file_exists($file)) {
      
          checkFile(($x+1),$a);
      
        } else {
      
          $fh = fopen($file, 'w') or die("can't open file"); 
          fwrite($fh, $a); 
          fclose($fh);
      
        }
      
      }
      

      【讨论】:

      • 你能帮我把我的代码加进去吗?当我这样做时,我的页面不会加载。
      • 我的网页仍然无法加载。在谷歌浏览器中,它说它可能配置错误。 ://
      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多