Table of Contents

PHP Forms

Using a PHP Form, we can easily create a form on our web page, and we can have a submit button, and the user can submit the form data to another file.

So let's create our form right now. First, we need to give our form an action. Let's make our action equal to welcome.php. Then we have to add another attribute, which is called method, and we need to specify whether this is going to be a POST or a GET.

<!DOCTYPE html>
<html>
<head>
  <title>My First PHP App</titile>
</head>
<body>

  <form action="welcome.php" method="POST">

  </form>

</body>
</html>

Lets put two inputs inside this form, and a submit button:

<!DOCTYPE html>
<html>
<head>
  <title>My First PHP App</titile>
</head>
<body>
  <p>Add your name and email below:</p>

  <form action="welcome.php" method="POST">
      
      <input type="text" name="name" placeholder="Name">
      <input type="email" name="email" placeholder="Email`">
      <input type="submit" value="submit">

  </form>

</body>
</html>

What we are doing now is submitting to the welcome.php file. So when you add your name and email address, it will send you to the welcome.php file. That's cool and all, but it didn't actually capture any of the data that we submitted from our form. So we need to capture that from inside of our welcome.php.

So to do that, we can use two globals $_GET and $_POST, which are always just available to us in PHP. If we echo out $_POST['name'], we should expect to get the name that was posted in the form to the welcome.php file.

Let's echo out the name and email.

Hello <?php echo $_POST['name']; ?>,

Your eamil is <?php echo $_POST['email']; ?>

Let's change our POST method to a GET method. A GET request is going to post the data as a GET request, and it's going to add them as URL parameters.

<!DOCTYPE html>
<html>
<head>
   <title>My First PHP App</titile>
</head>
<body>
   <p>Add your name and email below:</p>

   <form action="welcome.php" method="GET">
       
       <input type="text" name="name" placeholder="Name">
       <input type="email" name="email" placeholder="Email`">
       <input type="submit" value="submit">

   </form>

</body>
</html>

Then we need to change our welcome.php global to $_GET.

Hello <?php echo $_GET['name']; ?>,

Your eamil is <?php echo $_GET['email']; ?>

We will get the same results as the POST request, but it will add our values that we put in the form up in the URL.