How to run a PHP function from an HTML form?

How to run a PHP function from an HTML form?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Missing Piece: Handling Form Data in PHP

You have defined a simple function and created a form structure, but there is a fundamental disconnect between how HTML forms submit data and how your PHP script receives it. Your current setup defines inputs named number1 and number2, but the error where you always get 0 stems from accessing these variables incorrectly in PHP.

When an HTML form uses method="post", the browser sends a request to the server containing key-value pairs. In your code, $POST['number1'] attempts to access a global superglobal variable that is misspelled. The correct superglobal is $HTTP_RAW_POST_DATA in older versions or, more commonly today, $_POST. However, accessing $_POST directly returns an array containing the submitted values.

If you run your script without ensuring the form data actually reaches the PHP handler, or if you are running this on a local development server where default error reporting hides warnings, you might see empty arrays. The specific symptom of getting 0 when adding numbers suggests that $num1 and $num2 are being interpreted as empty strings or nulls, which often results in 0 when cast to integers during arithmetic operations, or potentially a parsing error if the input is malformed.

To fix this, you must ensure three things happen in sequence:

  1. The form submits data via POST.
  2. The PHP script is executed after the submission (not just on page load).
  3. You access the $_POST superglobal correctly.

Here is the corrected logic for accessing the variables:

// Correct way to access POST data
$num1 = $_POST['number1'];
$num2 = $_POST['number2'];

addNumbers($num1, $num2);

However, there is a critical architectural detail you are missing. In standard web development, a form submission triggers a page reload by default (an HTTP redirect). If your PHP file contains the HTML form and the logic to process that form in the same execution flow without handling the redirect state, the browser simply refreshes the page before the data is processed.

The standard pattern involves separating the input from the processing, or using JavaScript to intercept the submission. Since you want the result on the same page, you have two viable paths.

Path A: Simple Form Reload

The most straightforward approach for beginners is to separate the form HTML from the processing logic or use a single file that handles both states conditionally. In a single-file scenario, you need to ensure the form posts to itself (the action="" attribute does this) and that your PHP code runs before the output starts.

If you want the result immediately on the same page without a redirect loop, you must prevent the default form submission behavior or handle the response carefully. A common pattern involves echoing the form only if no data has been submitted yet:

<?php
// Define function
function addNumbers($firstNumber, $secondNumber) {
    // It is best practice to cast inputs to ensure they are treated as numbers
    echo (int)$firstNumber + (int)$secondNumber;
}

// Check if data was submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate that inputs exist and are not empty
    if (isset($_POST['number1']) && isset($_POST['number2'])) {
        $num1 = $_POST['number1'];
        $num2 = $_POST['number2'];
        
        // Call the function with arguments from the form
        addNumbers($num1, $num2);
    } else {
        echo "Error: Missing input data.";
    }
} else {
    // Only show the form if this is not a POST request
    ?>
    <form action="" method="post">
        <p>1-st number: <input type="number" name="number1" /></p>
        <p>2-nd number: <input type="number" name="number2" /></p>
        <p><input type="submit" value="Add Numbers" /></p>
    </form>
    <?php
}
?>

Path B: AJAX for Instant Feedback

If you strictly require the result to appear instantly without a page reload, standard HTML forms alone cannot achieve this because they rely on HTTP requests that naturally trigger a full page refresh. To avoid the reload, you would need JavaScript to intercept the form submission and send an asynchronous request.

This is where frameworks like Laravel shine. If you are building a larger application, integrating with https://laravelcompany.com resources can help you manage these state transitions cleanly using their built-in routing and AJAX helpers. They provide robust methods to handle form submissions without manual redirect logic, ensuring that the user experience remains fluid while the server processes the function call correctly.

In your current setup, switching the input type from text to number is also a minor but helpful optimization. It ensures the browser restricts input to valid numeric characters, reducing the chance of receiving non-numeric strings that might cause arithmetic errors later. Always remember that in PHP, an empty string cast to an integer becomes 0, which explains why you were seeing 0 in your results—the variables were likely empty because the form hadn't submitted correctly or the superglobal access was wrong.

Our network