PHP Tutorials: Forms

PHP Forms

Hey! have you ever wonder! How the forms you fill online are submitted to the website administrator and how they process it.? The PHP beginners might be thinking about it. So, let me help you to get to that point where you will learn about PHP form.

Let us make it clear that a form gets designed and displayed as an HTML format. I assume here that you already know the basics of HTML. Let us create a form in HTML, to make very simple for you I am just going to create only 2 fields. Because you guys are smart enough to copy and paste. Aren’t you??

<form action="submit.php" method="post">
      <label>Your name</label>
      <input type="text" name="your_name"><br />
      <label> Your email</label>
      <input type="email" name="your_email"><br />
      <input type="submit" value="Submit">
</form>

About the code

I have written an HTML code above. What exactly it’s doing? It seems to be a simple form, how it’s going to submit the information to the website. It’s not the end yet, we have completed our first step. I stopped here to just explain the code. Here you have to give attention to 5 points.

  • The form tag is used to create an HTML form. It will help you input information.
  • The action attribute, it is the file the form tag will send the information to after you hit the submit button.
  • The method attribute will define the way form will transport the data. PHP supports 3 methods POST, GET, REQUEST
  • The input fields which will take your input.
  • The submit button, it will send the data to the server.

Handling form submit

After submitting the form the information will be sent to the action page. In our case, submit.php is the action page. We write the HTML and the PHP code in a single file. Because PHP needs HTML to display output. We can also have HTML in a different file and PHP code in another file which will have .php extension. There are 3 Superglobal variables which are used to access the submitted values.

  • $_GET: When the form method is “get” then the data get accessed through $_GET
  • $_POST: When the form method is “post” then the data get accessed through $_POST
  • $_REQUEST: It contains the value of $_GET, $_POST and $_COOKIES

Now its time to access the information we submitted through the form created above. It’s always advisable to validate the data before you display it. By validating data we can save our page from displaying warnings. Here is the code to access the information with validation.

<?php 
      //Check if form is submitted
      if( isset( $_POST) && isset( $_POST['submit'] ) ){
            echo "Hello Guys! My name is ".$_POST['your_name']."</br>";
            echo "My email is ".$_POST['your_email'];
      }
?>

One thought on “PHP Tutorials: Forms

Leave a Reply

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