PHP more forms

From TRCCompSci - AQA Computer Science
Revision as of 11:30, 20 December 2017 by Admin (talk | contribs) (Testing form inputs)
Jump to: navigation, search

Testing form inputs

Imagine the example below, it contains a form with two text input boxes. If this form is used correctly then very little can go wrong. However some users will try to add code into these boxes so when we echo the input the code might run:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
<form action="" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

We could create a function which will take the data inputted, clean it and remove any dangerous code, and then return it back:

<?php
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }
?>

Now we can change the example to:

<html>
<body>
Welcome <?php echo test_input($_POST["name"]); ?><br>
Your email address is: <?php echo test_input($_POST["email"]); ?>
<form action="" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>