1
<!DOCTYPE html>
<html>
<title>
Test page
</title>

<?php
$uri=$_SERVER['REQUEST_URI'];
?>
<a href='#' onclick='<?php file_put_contents('feedback.txt',$uri.' ST'.'I understand this'.PHP_EOL , FILE_APPEND | LOCK_EX)?>'>I understand this </a>
<button onclick='<?php file_put_contents('feedback.txt',$uri.' ST'.'I don\'t understand this'.PHP_EOL , FILE_APPEND | LOCK_EX)?>'>I don't understand this </button>

In the above html/php code, I have both a button and a link that should write to a file when clicked. When I was experimenting with it, however, I found that the code ran every time I refreshed the page, is there any way to prevent this?

  • 2
    You can not trigger PHP via onlick that way(nesting PHP code inside the onclick). You would need to write a JS function that executes on the onclick which then AJAX calls a seperate PHP file to execute the file_put_contents. – Andrew Coder Dec 14 '15 at 18:28
  • I think you are consued or I didn'd understand your question. The php code is executed on the server side so, everytime you load the page it's executed. If you want to run it only on `onclick` event then you should use something like `Ajax` – Gonzalo Dec 14 '15 at 18:29
  • The `PHP` is firing, you'll need to call a function that triggers a script to fire (probably `AJAX` is best). – camelCase Dec 14 '15 at 18:29
  • Php scripts run in the server. Javascript is executed by the browser. Php scripts are executed by the server when the page loads. So php script wouldn't be executed again unless the page is reloaded. Use a javascript function to achieve your requirement or use Ajax. – Mathews Mathai Dec 14 '15 at 18:37

0 Answers0