Clearing content of text file using php
Solution 1
file_put_contents("filelist.txt", "");
You can redirect by using the header() function to modify the Location header.
Solution 2
This would truncate the file:
$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);
In clear.php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER']
value.
Solution 3
To add button you may use either jQuery libraries or simple Javascript script as shown below:
HTML link or button:
<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>
Use PHP to clear a file content. For instance you can use the fseek($fp, 0); or ftruncate ( resource $file , int $size ) as below:
<?php
//open file to write
$fp = fopen("/tmp/file.txt", "r+");
// clear content to 0 bits
ftruncate($fp, 0);
//close file
fclose($fp);
?>
Redirect PHP - you can use header ( string $string [, bool $replace = true [, int $http_response_code ]] )
<?php
header('Location: getbacktoindex.html');
?>
I hope it's help.
Solution 4
Try fopen() http://www.php.net/manual/en/function.fopen.php
w as mode will truncate the file.
Subho Halder
I'm a Security Researcher, Web Developer, Programmer, and a Human after all. I have co-founded Appknox, Android Framework for Exploitation(AFE) and many other initiatives and also worked as a freelancer in Scriptlance. Find me at Apple Security Researcher List, Microsoft Security Researcher's List and also at Google Hall of Fame, Under Honourable mention. Currently I am the Co Founder of Appknox a Mobile Security Startup. I have completed my Bachelors in Electronic and Telecommunication from KIIT University. You can read my blogs at http://subho.me A budding programmer, hacker and a Party Harder kind of guy :)
Updated on July 08, 2022Comments
-
Subho Halder almost 2 years
I have a filelist.txt file and I created a file called clear.php to clear the content of filelist.
I put a button in index.html to call clear.php to clear the file.
Can anyone help me out regarding what PHP code I should write in clear.php?
How to code a button to call clear.php and then return back to index.html showing the result that it has been cleared?
-
Cyrille over 3 yearsKeep in mind that as the function returns the number of bytes that were written to the file, doing
file_put_contents("filelist.txt", "") or die("Could not clear file!");
will always die.