質問

i'm new to PHP. I want to use a (html) input type = button to make the content of a html empty. I searched the web, if i use fopen(file.html,w+), it will clear the files content " "w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)". Source: http://www.w3schools.com/php/func_filesystem_fopen.asp

My problem is that there is probably a bit of code missing or syntax mistakes. because when i press the button nothing happends.

i really don't know and couldn't find anything on the world wide web, it's probably really simple.. sorry in advance if i wrote the question wrong.

HTML code

 <input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">

PHP code:

<?php

    // clear log
if(isset($_POST['clearlog']))
    {
        function cleartlog()
        {
            $fp = fopen("log.html", 'w+');
            fwrite($fp, "");
            fclose($fp);            
        }
    }
?>

the PHP code is in an external file, but is required it in my index.php

PS: is it better to use the "ftruncate" function?

Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp

役に立ちましたか?

解決

What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.

Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.

The logic is simple:

Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run. jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.

他のヒント

You should use a form which will connect to the server and the PHP should clear the log.html file.

<form action="wipeFileContents.php">

<input type="submit" value="Clear Log File">

</form>

It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.

you could try the following:

HTML

<form action='myfile.php'>
  <input type="submit" value="clear">
</form>

PHP

if(isset($_POST['clear']))
{
  file_put_contents("log.html", "");
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top