Difference between revisions of "PHP more forms"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "==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 use...")
(No difference)

Revision as of 10:29, 20 December 2017

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>