PHP Tutorial: Getting user input in PHP using HTML form

There are basically three ways in PHP to get user input. They are
  • Using HTML Form
  • Using URL values links
  • Using COOKIES
In this tutorial, I shall talk how to use HTML Form to get user input and retrieve that values from a web server. Form is simple HTML form start with <form> tag and end with </form>. The form is posted to the server using POST method and each data user has entered is stored in a PHP super global variable $_POST. $_POST is an associative array that stores variables in key => value format. Let us take an example of simple HTML form with two fields: username and password.

<html>
    <head>
        <title> Simple Form </title>
    </head>
    <body>
        <form action="retrieve.php" method="post">
            Username: <input type="text" name="username" value="" />
            Password: <input type="password" name="password" value= "" />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

The name of the field username is ‘username’ and field password is ‘password’. The name actually stores an index in the $_POST array and we can retrieve the value using this name a the index of the array. For example, to retrieve the value of username, we can print $_POST[‘username’] and similar is the case for password. So let’s make another file retrieve.php to print the values of username and password.

<?php
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";
    echo "Username : {$_POST['username']}<br>";
    echo "Password : {$_POST['password']}";
?>
Now this retrieves the value of username and password. print_r is used in php to print the whole array. When above codes are run in the browser and input is given as ‘Bibek’ for username and ‘Subedi’ for password, then the output of retrieve.php will be like this
SHARE PHP Tutorial: Getting user input in PHP using HTML form

You may also like...

2 Responses

  1. Rimas says:

    Hi! I'm doing a project in which I need user input through php post and use that input to c++ cin. The whole idea is there will be a webpage form to fill up by the user and hit the submit button. After that one of the filled up data goes to c++ cin as any type lets say integer. Using that data the program is compiled and run and the result is sent back to the php webpage. Can you help me? or do you have any idea how to do that?
    Thank you.

    Samir Paudel

  2. I am sorry i have no idea about that. You may ask this question on http://stackoverflow.com and you may get the answer.

Leave a Reply

Your email address will not be published.

Share