Skip to content

Calling a PHP function by onclick event

To call a PHP function using an onclick event, you will need to use a little bit of JavaScript. Here's an example of how you can do it:

Example of calling a PHP function by onclick event

html
<button onclick="callPHPFunction()">Click me</button>

<script>
function callPHPFunction() {
  fetch("yourPHPFile.php?functionToCall=yourFunction")
    .then(response => response.text())
    .then(data => console.log(data));
}
</script>

In this example, the callPHPFunction function is called when the button is clicked. This function sends an HTTP GET request to yourPHPFile.php, with a query parameter functionToCall set to yourFunction.

Then, in yourPHPFile.php, you can use the following code to call the specified function:

Example of calling a PHP function using onclick event of JavaScript

php
<?php
$allowedFunctions = ['yourFunction'];
if (isset($_GET['functionToCall']) && in_array($_GET['functionToCall'], $allowedFunctions)) {
  call_user_func($_GET['functionToCall']);
}

function yourFunction()
{
  // function code goes here
}
?>

This code checks if the functionToCall parameter is set and matches a predefined whitelist of allowed functions. If the condition is met, it calls the function using call_user_func. Note: Always validate or whitelist user input before executing server-side functions to prevent arbitrary code execution.

Keep in mind that this is just one way to call a PHP function using an onclick event. There are other ways to do it, such as using a form with a submit button, or using the fetch API to send asynchronous requests.

Dual-run preview — compare with live Symfony routes.