February 8th 2007
(1) PHP Lesson 4
Educational, Programming, Tutorials
Previously we looked at some of the methods PHP offers to sort and manipulate strings and we specifically looked at str_replace() and encryption methods like md5() and sha1().
In this lesson, the final one before a big project, we’re going to take a look at how to capture inputs from form fields. Also I’m going to talk about the secure and insecure ways to transfer the data.
Lesson 4: Form Field Input
Getting the input from a form is pretty simple and in this lesson we are going to keep it that way by using two files: form.php and process.php. The first will contain the form we are going to create which a user will fill in. The latter file will take the input, process it and output it.
Here’s the sample form we’re going to use. In this case it’s just a simple username and password form. This form does not validate and is in no way conforming to accessibility either.
<form action="process.php" method="post">
Username: <input type="text" name="username" size="25" />
Password: <input type="password" name="password" size="25" />
<input type="submit" value="submit form" />
</form>
Once the user submits the information by the button they’ll be taken to process.php along with the values of the form fields. We use the $_POST global to take the form values. For example if we wanted to take the value of the username field and assign it to $username:
$username = $_POST['username'];
//getting the value of the form field with the name of ‘username’
The variable in between the square brackets refers to the name=”" part of the inputs in the form. So now we can create the process.php file from what we’ve learned.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
echo “You’re username is “.$username.” and your password is “.$password.”.”;
?>
So there is the simple way to collect and assign form variables sent over pages. The next lesson, lesson 5, is where we are going to put all we’ve learnt from lessons 1 to 4 into practise. You’ll use what you’ve learnt and some new stuff that will introduce you to lessons 6 to 9. Learn it!
/images/9r_leaf.png)
Nice series of articles; although I feel that similarly to most other tutorials you find on the website, this one doesn’t put enough emphasis on security. I don’t think you should publish the code as-above without a small mention of htmlentities() and XSS