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

Sub*_*der 53 html php text-files

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

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

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

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

And*_*y E 113

file_put_contents("filelist.txt", "");
Run Code Online (Sandbox Code Playgroud)

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


Ala*_*avi 33

这会截断文件:

$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);
Run Code Online (Sandbox Code Playgroud)

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

  • 您的解决方案帮助了我,但我实施了Andy E的解决方案,您的解决方案也是100%正确的.谢谢你帮助我! (4认同)

小智 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");
Run Code Online (Sandbox Code Playgroud)

我不知道你想在哪里展示结果.


Dar*_*z J 5

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

HTML链接或按钮:

<a href="#" onClick="goclear()" id="button">click event</a>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

使用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);
?>
Run Code Online (Sandbox Code Playgroud)

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

<?php
header('Location: getbacktoindex.html');
?>
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助。