【问题标题】:Clearing content of text file using php使用php清除文本文件的内容
【发布时间】:2010-11-07 14:23:34
【问题描述】:

我有一个 filelist.txt 文件,我创建了一个名为 clear.php 的文件来清除 filelist 的内容。

我在 index.html 中放了一个按钮来调用 clear.php 来清除文件。

谁能帮我看看我应该在 clear.php 中写什么 PHP 代码?

如何编写一个按钮调用 clear.php 然后返回 index.html 显示它已被清除的结果?

【问题讨论】:

    标签: php html text-files


    【解决方案1】:
    @987654321@("filelist.txt", "");

    您可以使用header()函数修改Location头来重定向。

    【讨论】:

    • 请记住,由于 函数会返回写入文件的字节数,因此执行file_put_contents("filelist.txt", "") or die("Could not clear file!"); 将始终失败。
    【解决方案2】:

    这会截断文件:

    $fh = fopen( 'filelist.txt', 'w' );
    fclose($fh);
    

    在 clear.php 中,使用$_SERVER['HTTP_REFERER'] 值重定向到调用者页面。

    【讨论】:

    • 您的解决方案帮助了我,但我实施了 Andy E 的解决方案,您的解决方案也是 100% 正确的。谢谢你帮助我!!
    【解决方案3】:
    //create a file handler by opening the file
    $myTextFileHandler = @fopen("filelist.txt","r+");
    
    //truncate the file to zero
    //or you could have used the write method and written nothing to it
    @ftruncate($myTextFileHandler, 0);
    
    //use location header to go back to index.html
    header("Location:index.html");
    

    我不知道你想在哪里显示结果。

    【讨论】:

      【解决方案4】:

      要添加按钮,您可以使用jQuery 库或简单的Javascript 脚本,如下所示:

      HTML链接或按钮:

      <a href="#" onClick="goclear()" id="button">click event</a>
      

      Javascript:

      <script type="text/javascript">
      var btn = document.getElementById('button');
      function goclear() { 
      alert("Handler called. Page will redirect to clear.php");
      document.location.href = "clear.php";
      };
      </script>
      

      使用 PHP 清除文件内容。例如,您可以使用 fseek($fp, 0);ftruncate ( resource $file , int $size ) 如下:

      <?php
      //open file to write
      $fp = fopen("/tmp/file.txt", "r+");
      // clear content to 0 bits
      ftruncate($fp, 0);
      //close file
      fclose($fp);
      ?>
      

      重定向 PHP - 你可以使用 header ( string $string [, bool $replace = true [, int $http_response_code ]] )

      <?php
      header('Location: getbacktoindex.html');
      ?>
      

      希望对你有帮助。

      【讨论】:

        【解决方案5】:

        使用'w' 而不是'a'

        if (!$handle = fopen($file, 'w'))
        

        【讨论】:

          【解决方案6】:

          试试 fopen() http://www.php.net/manual/en/function.fopen.php

          w as 模式会截断文件。

          【讨论】:

            【解决方案7】:
             $fp = fopen("$address",'w+');
             if(!$fp)
                echo 'not Open';
                    //-----------------------------------
             while(!feof($fp))
                 {
                    fputs($fp,' ',999);                    
                 } 
            
             fclose($fp);
            

            【讨论】:

              猜你喜欢
              • 2011-02-11
              • 1970-01-01
              • 1970-01-01
              • 2014-03-14
              • 1970-01-01
              • 2014-09-02
              • 2015-04-03
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多