How to get HTML form data in PHP variable?

By Faruque Ahamed Mollick

HTML form used to get input from users on web pages. In most of the times, it is necessary to take the form data in a PHP variable.

Today in this post I am going to tell you how you can get the form data in PHP variable so that you can use it later for a purpose.

The form data can be sent to PHP variable by using the unique name that is provided in each HTML form fields of an HTML form. Suppose you have an HTML form which contains a form field to take users email. After a user enters his/her email you need to take the email address in a PHP variable.

So how to do it?

HTML form

Below is the HTML form which contains the email field:

<form method="post" action="index.php">  
    E-mail: <input type="text" name="email">
   <input type="submit" name="submit" value="Submit">  

I have named it index.php and in the form action I have set the same URL index.php. Also, you can see that the email field has a unique name that is called “email” and also the submit button has a name “submit”. We

PHP code to get HTML form data in a variable

Now I am going to show you how to get the form data of the above HTML form into PHP variable.

To check if the form is submitted or not, use this PHP if condition given below:

if (isset($_POST["submit"])) {
  // Required code will be goes here

Notice the above code. You will see that I am using the submit button name “submit” in the code $_POST[“submit”].

Now how to get the email in PHP variable? You have to use $_POST[“email”] to take the value in PHP variable. But before you do it just check the code that is given below:

if (isset($_POST["submit"])) {
  echo $POST["email"];

It will show the email entered by the user on the same web page. So to take it inside PHP variable you simply need to write the code;

$email = $_POST["email"];

Give the variable name anything you want.

Now see the complete PHP code:

if (isset($_POST["submit"])) {
  $email = $POST["email"];
  echo $email;

<form method="post" action="index.php">  
    E-mail: <input type="text" name="email">
   <input type="submit" name="submit" value="Submit">  

Run the above code on your test server and you will see that after you submit an email it will show you the email you entered in the form.

First, your entered email has taken inside the variable $email and then using echo it will be seen on the web page after you submit the email.

So was that helpful? Now you can use that variable to insert the value inside MySQL database or you can use for any other purposes.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *