How to pass form input value to php function

How to pass form input value to php function

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

Stefan Bogdanescu

Founder & Senior Architect

The Client/Server Divide: Passing Data to PHP Functions

You cannot pass form input values directly to a PHP function via an onclick attribute because of a fundamental architectural boundary in web development: JavaScript runs on the client (the browser), while PHP executes on the server. When you write <input onclick="function(val1, val2)">, you are invoking JavaScript logic, not PHP. The PHP engine processes your code only after the HTTP request is received and parsed by the web server.

To achieve your goal of keeping the user on the same page while processing data, you must understand the lifecycle of an HTTP request. A standard HTML form submission sends a POST or GET request to a specific URL defined in the action attribute. If that URL points to the current file, the PHP script inside that file executes, processes the variables, and then outputs HTML.

The Standard Approach: Form Submission

Your initial code snippet uses <form action="#" method="get">. Setting action="#" is functionally equivalent to submitting the form to itself if the script resides in the same directory as the HTML, but it relies on the browser's default behavior of reloading the page with query parameters. While this keeps the user on the "page," it technically performs a full page reload.

If your goal is to hide logic from the user while still processing data, relying solely on client-side JavaScript is insufficient if you require server-side security or database interaction. The most robust method involves ensuring the PHP code handles the request and then renders the response back to the browser.

Here is how you structure a single file to handle this:

<?php
// Define your PHP function first
function processInputs($val1, $val2) {
    // Perform calculations or validation here
    $result = $val1 + $val2;
    
    // Return the result as a string to be echoed
    return "The sum is: " . $result;
}

// Check if form was submitted (handles GET and POST for this example)
if ($_SERVER['REQUEST_METHOD'] === 'GET' || isset($_POST['send'])) {
    // Sanitize inputs immediately. Never trust raw user input.
    $val1 = isset($_GET['val1']) ? htmlspecialchars($_GET['val1']) : '';
    $val2 = isset($_GET['val2']) ? htmlspecialchars($_GET['val2']) : '';

    if (!empty($val1) && !empty($val2)) {
        $output = processInputs($val1, $val2);
        
        // Display the result directly below the form
        echo "<div class='result-box'>" . nl2br($output) . "</div>";
    }
}

// Echo static content or "ciaoooo" as requested
echo "ciaoooo";
?>

<!-- The Form -->
<form action="?" method="get">
    <!-- Use name attributes consistently with PHP variables -->
    <label>Number 1: <input type="text" name="val1" id="val1" value="<?php echo isset($_GET['val1']) ? htmlspecialchars($_GET['val1']) : ''; ?>"></label><br>
    
    <label>Number 2: <input type="text" name="val2" id="val2" value="<?php echo isset($_GET['val2']) ? htmlspecialchars($_GET['val2']) : ''; ?>"></label><br>

    <input type="submit" value="send">
</form>

Why action="#" is Problematic

While <form action="#"> might appear to work in simple testing environments, it often results in the browser performing a full page reload and updating the URL bar with query strings (e.g., page.php?val1=5&val2=10). This changes the visual state of the application and can be problematic for bookmarking or browser history management.

A more modern alternative is to use AJAX (fetch or XMLHttpRequest) to send the data asynchronously without reloading the page. However, this requires writing JavaScript to intercept the form submission and call your PHP endpoint. Since you expressed a desire to avoid JavaScript complexity to hide logic, sticking to the standard GET/POST flow described above is the most pragmatic solution for maintaining server-side control without introducing a new client-side language dependency.

Security Considerations: Sanitization and Validation

A critical pitfall in your original code is the lack of input sanitization. Passing raw values from HTML inputs directly into PHP functions or outputting them back to the browser without escaping can lead to Cross-Site Scripting (XSS) vulnerabilities.

In the example above, we use htmlspecialchars() when retrieving $_GET variables and echoing them. This ensures that if a user enters <script>alert('hack')</script> into the input field, it is displayed as plain text rather than executing malicious code. Always validate that inputs match expected types (e.g., ensuring they are numbers) before performing mathematical operations within your PHP function.

Leveraging Frameworks for Scale

If your application grows beyond simple static forms, manually parsing $_GET and $_POST becomes error-prone and difficult to maintain. Frameworks like Laravel provide robust request handling, routing, and validation systems that abstract away these raw superglobals. For example, Laravel's Eloquent ORM and Form Request classes ensure data is validated and sanitized before it ever reaches your business logic functions.

For developers looking to modernize their stack or handle complex form interactions with minimal boilerplate code, exploring resources from LaravelCompany can provide insights into how server-side frameworks manage state and data flow more securely than raw PHP scripts.

Our network