How to apply a php function with a button
I realized that the script I wrote is attempting to use both javascript and php, and this doesn't work. Can anyone tell me how I might go about achieve what I'm looking to do? What I want to do is have a button that when clicked, it will write to file on the server. Here;s the code i wrote:
<html>
<head>
<?php
function change_html(){
$myFile = "testFile.html";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Hello\n";
fwrite($fh, $stringData);
$stringData = "World!\n";
fwrite($fh, $stringData);
fclose($fh);
}
?>
</head>
<body>
<input type="button" onclick="change_html()"开发者_StackOverflow中文版 Value="Continue">
</body>
</html>
Thanks in advance!!
Can't do that. PHP is server side and JavaScript is client side. You have two options:
Use JS on the client to fire an AJAX call that hits a page which runs your script.
Have the button submit a form that runs your script.
You have to understand what PHP and Javascript actually are: a server-side and client-side language. PHP only works on the server and can only communicate with the client through HTTP requests (so the browser or Ajax). Javascript on the other hand is a client-side language and can only works in the browsers windows, which means it can only modify the page. It can however, communicate with the server through Ajax requests.
You should read more about what PHP and Javascript actually are. Not to mention that your HTML-code absolutely doesn't validate.
When you understand what you are actually doing you should either create an Ajax request to a PHP script that modified the file or, you should add the input button the a form (which is actually mandatory) and point the form to a PHP script that modifies the file. I think the latter is the better way.
<html>
<head>
<?php
if(isset($_GET['change_html'])) change_html();
function change_html(){
$myFile = "testFile.html";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Hello\n";
fwrite($fh, $stringData);
$stringData = "World!\n";
fwrite($fh, $stringData);
fclose($fh);
}
?>
</head>
<body>
<form action="?change_html=true" method="GET">
<input type="submit" Value="Continue">
</form>
</body>
</html>
If you want to do this in PHP, then you have your button submit a form and the PHP script it points to does the work.
<form action="writefile.php" method="post">
<input type="submit" value="Continue" />
</form>
-
<?php
//writefile.php
file_put_contents("testFile.html", "Hello\nWorld!\n");
?>
That script can redirect back to the form if you want:
<?php
//writefile.php
file_put_contents("testFile.html", "Hello\nWorld!\n");
header("Location: yourpage.php");
?>
精彩评论