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?
file_put_contents("filelist.txt", "");
You can redirect by using the header() function to modify the Location header.
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.
//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");
I don't exactly know where u want to show the result.
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.
Use 'w'
and not, 'a'
.
if (!$handle = fopen($file, 'w'))
Try fopen()
http://www.php.net/manual/en/function.fopen.php
w as mode will truncate the file.
$fp = fopen("$address",'w+');
if(!$fp)
echo 'not Open';
//-----------------------------------
while(!feof($fp))
{
fputs($fp,' ',999);
}
fclose($fp);