使用php清除文本文件的内容

问题描述 投票:46回答:7

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

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

任何人都可以帮我解决我应该在clear.php中编写的PHP代码吗?

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

php html text-files
7个回答
110
投票
file_put_contents("filelist.txt", "");

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


33
投票

这会截断文件:

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

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


16
投票
//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');
?>

我希望它有所帮助。


3
投票

使用'w'而不是'a'

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

2
投票

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

如模式将截断文件。


0
投票
 $fp = fopen("$address",'w+');
 if(!$fp)
    echo 'not Open';
        //-----------------------------------
 while(!feof($fp))
     {
        fputs($fp,' ',999);                    
     } 

 fclose($fp);
© www.soinside.com 2019 - 2024. All rights reserved.