How to run a PHP function from an HTML form?
You need to gather the values from the $_POST
variable and pass them into the function.
if ($_POST) {
$number_1 = (int) $_POST['number1'];
$number_2 = (int) $_POST['number2'];
echo addNumbers($number_1, $number_2);
}
Be advised, however, that you shouldn't trust user input and thus need to validate and sanitize your input.
The "function" you have is server-side. Server-side code runs before and only before data is returned to your browser (typically, displayed as a page, but also could be an ajax request).
The form you have is client-side. This form is rendered by your browser and is not "connected" to your server, but can submit data to the server for processing.
Therefore, to run the function, the following flow has to happen:
- Server outputs the page with the form. No server-side processing needs to happen.
- Browser loads that page and displays the form.
- User types data into the form.
- User presses submit button, an HTTP request is made to your server with the data.
- The page handling the request (could be the same as the first request) takes the data from the request, runs your function, and outputs the result into an HTML page.
Here is a sample PHP script which does all of this:
<?php
function addNumbers($firstNumber, $secondNumber) {
return $firstNumber + $secondNumber;
}
if (isset($_POST['number1']) && isset($_POST['number2'])) {
$result = addNumbers(intval($_POST['number1']), intval($_POST['number2']));
}
?>
<html>
<body>
<?php if (isset($result)) { ?>
<h1> Result: <?php echo $result ?></h1>
<?php } ?>
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
</body>
</html>
Please note:
- Even though this "page" contains both PHP and HTML code, your browser never knows what the PHP code was. All it sees is the HTML output that resulted. Everything inside
<?php ... ?>
is executed by the server (and in this case,echo
creates the only output from this execution), while everything outside the PHP tags — specifically, the HTML code — is output to the HTTP Response directly. - You'll notice that the
<h1>Result:...
HTML code is inside a PHPif
statement. This means that this line will not be output on the first pass, because there is no$result
. - Because the form
action
has no value, the form submits to the same page (URL) that the browser is already on.