Forum Moderators: coopster

Message Too Old, No Replies

Wanting to execute a function after echoing on screen

To delete the file content after echoing on screen

         

fredfletcher

6:53 pm on Mar 22, 2012 (gmt 0)

10+ Year Member



Hello, I am hoping someone can shed a bit of light on this.

I would like to echo a random entry on screen from inside a flatfile database (.txt) and then, show a button or link to optionally delete the contents.

What I have below is not working for me, can someone tell me why that is please?


<?php


$r_array=file('/home/user/folder/file.txt');


shuffle($r_array);
echo "<b>Random entry in database:</b><br>";
echo $r_array[0];

function doit() {

// this will delete the entire contents
$fh = fopen( '/home/user/folder/file.txt', 'w' );
echo "<br><br>The database has been emptied.";
fclose($fh);

}

?>

<body>

<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']?>" name="form1" id="form1">

<input type="submit" name="submit" value="- delete -" id="submitbutton" onClick="return doit();" />

</form>

httpwebwitch

7:15 pm on Mar 22, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



you're confusing client-side JavaScript with server-side PHP

fredfletcher

7:32 pm on Mar 22, 2012 (gmt 0)

10+ Year Member



How can I achieve what I would like to do?

eelixduppy

8:29 pm on Mar 22, 2012 (gmt 0)



Here's my default place to redirect people to get a start: [news.php.net...]

You need to learn how AJAX (essentially just JavaScript) can work asynchronously with a server-side script (such as that written by PHP).

rocknbil

12:19 am on Mar 23, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Nah you don't need Javascript. :-) Look at the logic of something like this. If you've submitted the form by clicking the button, if matches the if condition and deletes, otherwise it displays the file contents and form. No sense in displaying the form if there's nothing to delete. :-)


<html><head><title>Test</title></head>
<?php
$output=null;
if (isset($_POST['submitButton']) and ($_POST['submitButton']=='- delete -')) {
// previous must match button value EXACTLY
$fh = fopen( '/home/user/folder/file.txt', 'w' ) or die("cannot open file");
$output = "<p>The database has been emptied.</p>";
fclose($fh);
}
else {
$r_array=file('/home/user/folder/file.txt');
shuffle($r_array);
$output = "<p><b>Random entry in database:</b></p>" .
$r_array[0] .
"<form method=\"post\" action=\"" . $_SERVER['SCRIPT_NAME'] . "\" name=\"form1\" id=\"form1\">
<p><input type=\"submit\" name=\"submitButton\" value=\"- delete -\" id=\"submitbutton\"></p>
</form>
";
}
echo "<body>$output</body></html>";
?>


I think you might need to write an empty string to it to actually delete the contents though. Look up fwrite . . .

fredfletcher

4:02 am on Mar 23, 2012 (gmt 0)

10+ Year Member



Thanks rocknbil, worked beautifully. I appreciate it very much, cheers!