<?php
require_once ( 'username.php' );

if (isset($_POST['textfield'])) {
    echo username();
    return;
}

echo '
<form name="form1" method="post" action="">
  <p>
    <label>
      <input type="text" name="textfield" id="textfield">
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="button" id="button" value="Submit">
    </label>
  </p>
</form>';
?>

You need to run the function in the page the form is sent to.

Answer from Jeremy L on Stack Overflow
Top answer
1 of 7
23
<?php
require_once ( 'username.php' );

if (isset($_POST['textfield'])) {
    echo username();
    return;
}

echo '
<form name="form1" method="post" action="">
  <p>
    <label>
      <input type="text" name="textfield" id="textfield">
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="button" id="button" value="Submit">
    </label>
  </p>
</form>';
?>

You need to run the function in the page the form is sent to.

2 of 7
17

In PHP functions will not be evaluated inside strings, because there are different rules for variables.

<?php
function name() {
  return 'Mark';
}

echo 'My name is: name()';   // Output: My name is name()
echo 'My name is: '. name(); // Output: My name is Mark

The action parameter to the tag in HTML should not reference the PHP function you want to run. Action should refer to a page on the web server that will process the form input and return new HTML to the user. This can be the same location as the PHP script that outputs the form, or some people prefer to make a separate PHP file to handle actions.

The basic process is the same either way:

  1. Generate HTML form to the user.
  2. User fills in the form, clicks submit.
  3. The form data is sent to the locations defined by action on the server.
  4. The script validates the data and does something with it.
  5. Usually a new HTML page is returned.

A simple example would be:

<?php
// $_POST is a magic PHP variable that will always contain
// any form data that was posted to this page.
// We check here to see if the textfield called 'name' had
// some data entered into it, if so we process it, if not we
// output the form.
if (isset($_POST['name'])) {
  print_name($_POST['name']);
}
else {
  print_form();
}

// In this function we print the name the user provided.
function print_name($name) {
  // $name should be validated and checked here depending on use.
  // In this case we just HTML escape it so nothing nasty should
  // be able to get through:
  echo 'Your name is: '. htmlentities($name);
}

// This function is called when no name was sent to us over HTTP.
function print_form() {
  echo '
    <form name="form1" method="post" action="">
    <p><label><input type="text" name="name" id="textfield"></label></p>
    <p><label><input type="submit" name="button" id="button" value="Submit"></label></p>
    </form>
  ';
}
?>

For future information I recommend reading the PHP tutorials: http://php.net/tut.php

There is even a section about Dealing with forms.

๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ tutorial.forms.php
PHP: Dealing with Forms - Manual
Here is an example HTML form: ... <form action="action.php" method="post"> <label for="name">Your name:</label> <input name="name" id="name" type="text"> <label for="age">Your age:</label> <input name="age" id="age" type="number"> <button type="submit">Submit</button> </form>
๐ŸŒ
BitDegree
bitdegree.org โ€บ learn โ€บ php-form-action
Main Tips on PHP Form Action: Learn PHP Post and PHP Get
August 8, 2017 - After the form is filled in and the submit button is clicked, all data is sent for processing to pet.php, defined in the PHP form action attribute. The method used to send the information is PHP POST. echo variable is used to display the submitted data. Let's see the code in the file: ... <html> <body> Your pet breed is: <?php echo $_POST["breed"]; ?><br> Color is: <?php echo $_POST["color"]; ?> </body> </html>
๐ŸŒ
HTML Form Guide
html.form.guide โ€บ php-form โ€บ php-form-action-self
Using PHP_SELF in the action field of a form | HTML Form Guide
PHP_SELF exploits can be avoided by using the htmlentities() function. For example, the form code should be like this to avoid the PHP_SELF exploits: <form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> The htmlentities() function encodes the HTML entities.
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ php_forms.asp
PHP Form Handling
Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET PHP RegEx PHP RegEx Functions ยท PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail PHP Form Complete
Top answer
1 of 3
2

You can't call PHP functions directly. However, if the php file is formatted how you displayed here with only two functions you could pass a flag in as a POST field and have a logic block determine which function call based on that flag. It's not ideal but it would work for your purposes. However, this would force the page to refresh and you would probably have to load a different page after the function returns so you may want to simply implement this as an ajax call to avoid the page refresh.

Edit based on your comment (Using jQuery Ajax):

I am using the .ajax() jQuery function. My intentions create one php file that contains multiple functions for different html forms. โ€“ tmhenson

Well in this case, you can have your file contain the logic block to "route" the request to the right function and finally return the result.

I'll try to provide an option for what you want to do based on some simple jQuery. Say you have something like this:

Java Script:

$("#button1").click(function(e){ 
    e.preventDefault(); // prevents submit event if button is a submit
    ajax_route('ap'); 
}); 
$("#button2").click(function(e){ 
    e.preventDefault(); // prevents submit event if button is a submit
    ajax_route('se'); 
});

function ajax_route(action_requested){ 
    $.post("ajax_handler.php", {action : action_requested}, function(data){
        if (data.length>0){ 
            alert("Hoorah! Completed the action requested: "+action_requested); 
        } 
    })
}

PHP (inside ajax_handler.php)

<?php
// make sure u have an action to take
if(isset($_POST['action']) 
    switch($_POST['action']){
        case 'ap': addPerson(); break;
        case 'se': sendEmail(); break;
        default: break;
    }
}

function addPerson() {
    //do stuff here 
}

function sendEmail() {
    //do some stuff here 
}
?>
2 of 3
0

You CAN'T. PHP runs on the server only. You can use a javascript AJAX call to invoke a php script on the server, or use a regular form submission, but directly invoking a particular PHP function from client-side html? not possible.

๐ŸŒ
Home and Learn
homeandlearn.co.uk โ€บ php โ€บ php4p8.html
The HTML ACTION attribute and PHP
<html> <head> <title>A BASIC HTML FORM</title> </head> <body> <Form name ="form1" Method ="POST" Action ="submitForm.php">
Find elsewhere
๐ŸŒ
Stack Exchange
wordpress.stackexchange.com โ€บ questions โ€บ 396962 โ€บ how-a-html-form-can-trigger-a-php-function
How a HTML form can trigger a PHP function? - WordPress Development Stack Exchange
October 15, 2021 - If you're comfortable with JavaScript, one way to approach what I think you're trying to do here would be to enqueue a JavaScript version of your function and then just call it from the form as an onSubmit attribute. So along the lines of: Enter name: and you've enqueued myFunction either in function.php or in a plugin: function load_my_script() { wp_enqueue_script( 'myFunction', get_template_directory_uri() . '/js/myFunction.js'); } add_action( 'wp_enqueue_scripts', 'load_my_script' );
๐ŸŒ
W3Docs
w3docs.com โ€บ php
How to run a PHP function from an HTML form?
To run a PHP function from an HTML form, you will need to create an HTML form with the desired inputs, such as text fields and submit buttons. Then, you will need to create a PHP script that handles the form submission and runs the desired function.
Top answer
1 of 7
28

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:

  1. Server outputs the page with the form. No server-side processing needs to happen.
  2. Browser loads that page and displays the form.
  3. User types data into the form.
  4. User presses submit button, an HTTP request is made to your server with the data.
  5. 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 PHP if 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.
2 of 7
5

Try This.

  <?php 
            function addNumbers($firstNumber, $secondNumber)
            {
            if (isset($_POST['number1']) && isset($_POST['number2']))
            {
                $firstNumber = $_POST['number1'];
                $secondNumber = $_POST['number2'];
                $result = $firstNumber + $secondNumber;
                    echo $result;
            }

            }
    ?>

            <form action="urphpfilename.php" method="post">
            <p>1-st number: <input type="text" name="number1" /></p>
            <p>2-nd number: <input type="text" name="number2" /></p>
            <?php addNumbers($firstNumber, $secondNumber);?>
            <p><?php echo $result; ?></p>
            <p><input type="submit"/></p>
Top answer
1 of 10
26

This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.

test.php

<form action="javascript:void(0);" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" />
</form>

<script type="text/javascript">
    $("form").submit(function(){
        var str = $(this).serialize();
        $.ajax('getResult.php', str, function(result){
            alert(result); // The result variable will contain any text echoed by getResult.php
        }
        return(false);
    });
</script>

It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.

getResult.php

<?php
    echo "The name you typed is: " . $_REQUEST['user'];
?>

NOTE

This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.

2 of 10
10

You have a big misunderstanding of how the web works.

Basically, things happen this way:

  • User (well, the browser) requests test.php from your server
  • On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
  • The browser displays the form, the user can interact with it.
  • The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.

You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.

If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).

๐ŸŒ
Meera Academy
meeraacademy.com โ€บ home โ€บ html action attribute and php
HTML Action attribute and PHP
February 14, 2020 - When run above script the page send textbox information to same page as we write the same page name in action attribute. If we wan to handle the data which is submitted to form then we have to do some PHP programming. <html> <head> <title>My First HTML web page</title> <?php echo $_GET["name"]; ?> </head> <body> <FORM name="form1" action="firstexample.php" method="GET"> Name : <input type="text" name="name"><br> Password : <input type="text" name="city"><br> <input type="submit" name="Submit1" value="Login"> </FORM> </body> </html>
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ php โ€บ php_form_handling.htm
PHP - Form Handling
To keep things safe and secure, PHP employs the htmlspecialchars() function, which helps to block any potentially harmful code. After processing everything, PHP then shows you the information you've entered right on the webpage. <html> <body> <form method = "post" action = "<?php echo ...
๐ŸŒ
HTML Form Guide
html.form.guide โ€บ php-form โ€บ php-form-post
Using the POST method in a PHP form | HTML Form Guide
You can use this function on the $_POST array to determine if the variable was posted or not. This is often applied to the submit button value, but can be applied to any variable. ... <?php if(isset($_POST['submit']) { echo("First name: " . $_POST['firstname'] . "<br />\\n"); echo("Last name: " . $_POST['lastname'] . "<br />\\n"); } ?> <form action="myform5.php" method="post"> <p>First name: <input type="text" name="firstname" /></p> <p>Last name: <input type="text" name="firstname" /></p> <input type="submit" name="submit" value="Submit" /> </form>
๐ŸŒ
Envato Forums
forums.envato.com โ€บ envato authors โ€บ code authors
Exectue php function on submit button - Envato Forums
February 16, 2011 - Okay.. i have searched the internet for over an hour and i still can't do this the right way :( I have a simple button in a php page and i want it to run a php function when pressed. I tried using <form action="<?pโ€ฆ
๐ŸŒ
The Art of Web
the-art-of-web.com โ€บ php โ€บ form-handler
Basic Form Handling in PHP < PHP | The Art of Web
For more advanced validation methods, including a CAPTCHA, or presenting the feedback form in a modal window, you can check out some of the related articles below. In the previous example we made a faux pas in polluting the global variable space. We can avoid this, and make our code more modular and reusable, by calling it as a function: <?PHP // PHP form handler function validateFeedbackForm($arr) { extract($arr); // name, email, subject, message if(!isset($name, $email, $subject, $message)) { return FALSE; } if(!trim($name)) { return "Please enter your Name"; } if(!preg_match("/^\S+@\S+$/", $email)) { return "Please enter a valid Email address"; } if(!trim($subject)) { $subject = "Contact from website"; } if(!trim($message)) { return "Please enter your comment in the Message box"; } // send email and redirect $to = "feedback@example.com"; $headers = "From: webmaster@example.com" .