© Gunnard Engebreth, Satej Kumar Sahu 2023
G. Engebreth, S. K. SahuPHP 8 Basicshttps://doi.org/10.1007/978-1-4842-8082-9_5

5. Form Data

Gunnard Engebreth1   and Satej Kumar Sahu2
(1)
Madison, WI, USA
(2)
Bangalore, India
 

In this chapter, you will learn how to create and manage forms in PHP using the POST and GET methods.

You will explore three superglobals: $_POST, $_GET, and $_REQUEST. $_POST and $_GET are the two most common ways of receiving user input in PHP. $_REQUEST is lesser used.

This chapter consists of the following sections:
  • PHP GET Form

  • PHP POST Form

We once asked a junior developer to explain the difference between POST and GET (in general). The answer he gave, while less than ideal, was not incorrect. He said that POST is used to send data and GET is used to retrieve data. This is not wrong. When using a restful API, one would POST data to be used by the server and GET data as a request for a database query (for example). This, however, is not the answer we were expecting–or that he even knew he was talking about. The differences we were looking for between POST and GET are the following:

POST sends data via the HTTP body to an awaiting server (API, specific PHP file, etc..).

GET appends form data to the URL in a name-value pair.

The next time you hit the Submit button on a form, look at the URL. If you see any of the information you just filled out, then it is using GET. If the URL is clean, then surely POST is being used.

You don’t even need to use a form to be using GET, to be honest. GET is a very useful way of persisting unique IDs, breadcrumbs, and miscellaneous data. They both have their function and use cases, but with both we need to keep security at the top. There was a TV show about a doctor who was famous for saying “Never trust a patient. They lie.” In our case, NEVER trust user input. Exposing your code to an open attack vector like a form is just that… an attack vector. It is not a matter of “if” someone attempts to hack through the form but indeed 100% “when.” If you look at your live server logs right now, you will see hundreds of requests coming in, scanning all files and directories that they can find. While they are attempting to find your exposed WordPress config file, they are also hitting the front end with bots to attempt SQL injections on your forms. Once you create a form, you have opened the door to the outside world and hackers will gladly walk in.

Now that I have scared you off completely from ever attempting to code again, this is manageable. There are tactics that can be employed that will slow down, deter, and even stop hackers from gaining access through code you have written. Having said all of that, THERE IS NO SUREFIRE WAY TO PROTECT AGAINST SQL INJECTIONS. There are many best practices that you can follow to feel as secure as possible, though, and you will learn about them after you get your own hacker red carpet, I mean form, set up.

PHP POST Form

Let’s see how the PHP POST form works. Let’s create a simple HTML form and see how $_POST receives data from the post request variable in the HTML page.

Here is a basic HTML form:
(basicForm.php)
<html>
<body>
<form action="functions.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
This form takes the user input of name and email and sends them via POST to functions.php. The “method” is set by the method setting and where you are sending these values is set at the action setting. If you open up functions.php, you can see what happens next.
<?php
echo "Thank you {$_POST['name']}. I will email you at {$_POST['email']}";
?>
<br />
<a href="basicForm.php">back</a>

This code takes (and assumes the validity of) the two POST variables sent from your form and prints them to the screen. You see name="name" and name="email" get sent over to functions.php and be retrieved with $_POST['name'] or $_POST['email']. If you change the name of email in the form page from name="email" to name="myEmail", then you would have to refer to it as $_POST['myEmail']. Let’s try something real quick.

Instead of putting your name in the “name” field, try typing
<h1>pants</h1>
Now Press Enter and look at the results shown in Figure 5-1.
Figure 5-1

Code result for the POST Form

This is not the result the developer (you) were thinking about when creating this form. As a developer, you must always be thinking of not only the exact use case for your code; the fringe, edge cases, and worst cases must be considered. Users are very dependable and will consistently use applications the “right” way but there are cases in which the previous example can happen. Hopefully this happens because of a one-off mistype, but the reality is that more and more often attackers use forms like the one you built to utilize the lack of security measures to gain entrance into your system. Security must be at the forefront of a developer’s mind, no matter where you work or how secure you think you may be.

Let’s start to mitigate this situation.

Open up functions.php and add these lines to make the code look like this:
<?php
$name = filter_var($_POST['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
echo "Thank you {$name}. I will email you at {$email}";
?>
<br />
<a href="basicForm.php">back</a>

Go back and try to send <h1>pants</h1> as “name” again. You will see a different result this time. You are now blocking the HTML elements from being rendered by the browser. This is a positive step in the right direction. Many exploits that are live today begin with simple HTML elements rendering on a page. Now, let’s see what you can do with the email address.

You are already sanitizing the email address to make sure that no sneaky characters get through, but you also want to validate that the address fits a certain format. You want to check if the email address they entered has a beginning part with letters and numbers and a few special characters like -. Then you want to check if there is an @ sign followed by more letters and numbers and then a period with a valid domain (.com, .org, .net, etc.). This can be done with the same filter_var function you used earlier but with the FILTER_VALIDATE_EMAIL option used. Open up functions.php again and add these lines of code to make it validate the email address:
<?php
$emailErr= null;
$name = filter_var($_POST['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format";
}
if (!$emailErr) {
  echo "Thank you {$name}. I will email you at {$email}";
  } else {
          echo $emailErr;
}
?>
<br />
<a href="basicForm.php">back</a>

Reload the form and enter in a very non-email-addressy email like pants one1@mail.$$$.

This will return “Invalid email format” because it is an invalid email format (see how that works;) This method, of course, is not fool-proof. Without actually sending and receiving back a response from the email server from the domain that they have entered, you can’t actually validate that this is a real and used email address. This is just to get you past the first check. Next would come a “Please check your email to validate you are a real user” step in order to make this more realistic.

Did you notice that after you received the “Invalid email format” message and clicked on the back button, your input was gone from the boxes? Your name and email were no longer there. Wouldn’t it be nice if you included those things back in the box just in case someone mistyped a letter and didn’t want to type everything again?

PHP GET Form

Let’s see how the PHP GET form works.

You can do the above functionality easily with $_GET. Open up functions.php again and add these lines to the “back” link at the bottom:
<?php
$emailErr= null;
$name = filter_var($_POST['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format";
}
  if (!$emailErr) {
  echo "Thank you {$name}. I will email you at {$email}";
  } else {
          echo $emailErr;
  }
  ?>
<br />
<a href="basicForm.php?name=<?= $name ?>&email=<?= $email?>">back</a>
Here you are adding the $name and $email variables to the URL so that you can use them when you get back to shortForm.php. What is with <?=, though? This is how you can use PHO with its short open option. Instead of typing <?php when you want to use PHP code within HTML to do something simple, you can use the short open <?= and the = means echo. So, with this in your toolbox, you can quickly put the $name and $email variables where you need to in the URL to use the $_GET variable back on the basicForm.php page. Go ahead and open that file up, too, and add these lines:
<?php
if (isset($_GET)) {
        if (isset($_GET['name'])) {
                $name = $_GET['name'];
        }
        if (isset($_GET['email']) {
                $email = $_GET['email'];
        }
}
$name != '' ? $name : '';
$email != '' ? $email : '';
?>
<html>
<body>
<form action="functions.php" method="post">
Name: <input type="text" name="name" value="<?= $name; ?>"><br>
E-mail: <input type="text" name="email" value="<?= $email; ?>"><br>
<input type="submit">
</form>
</body>
</html>
The form page will now check to see if there are any variables set within the $_GET super global. If there are, it checks if $_GET['name'] and $_GET['email'] are set. If there is anything in there, it sets them to $name and $email, respectively. Next, it checks if $name or $email have been set or not. This is a ternary if statement. Instead of typing
if ($name != "" ) {
      $name = $name;
} else {
      $name = "";
}
you can just say
(Conditional statement) ? (Statement_1) : (Statement_2);
So, what you want is
$name != "" ? $name : ""
If $name is not empty, then set it to $name otherwise set it to "".

In the input box you use the value setting to add the name or email you just received (or not) from $_GET via the URL. Now that you can get user information and pass it back to your own scripts, you can fully interact with users. Using the $_GET and $_POST superglobals gets you familiar with arrays, specifically associative arrays.

Summary

In this chapter, you learned about PHP form data handling. You learned how to create and use forms to get form data using PHP superglobals such as $_GET and $_POST.

In the next chapter, you will learn more and take a deeper look into arrays, which are used to hold in a single variable multiple values of a similar type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset