- slide 1 of 1
PHP forms can be used for all types of things on a web page. They can request something as simple as the user's name. Or the PHP form can be more detailed and include all of a user's information and a file field. By gathering this information from the user using these PHP forms, we are better able to give the user the experience they are looking for while visiting our website.
Because PHP handles form data so well, there are many things we don't need to worry about when creating forms using PHP. PHP does not require you to specify get or post on the form. It does this automatically. Also the name elements of the form are converted to variables. Without any sort of variable declaration. This is great when you don't know exactly what the data will be when it’s processed.
Below is a simple web page that has a form on it.
It’s a pretty simple HTML page with just one form element on it. We'll look at the code and go over what each part does. First on line 9 we are declaring that we have a form and its attributes are method is going to be POST, and its action is going to be page2.php. Page2.php is where we'll send the results of the form. Now line 10 brings the text form element onto the screen with the name 'user'. This part of the form is where the user will enter their name and we'll print it back to them later in the second page. Line 11 simply shows the submit button and line 12 closes the form tag.
We could have many other fields on this form and other elements such as radio buttons, check boxes, etc... There are no limit to how many elements you put on your form, however putting loads of questions on your page may scare your user away so be mindful of the amount.
Now we'll need to process the data that was gathered in the form. Review the next screen shot of page2.php:
It looks like a pretty simple html page at first glance. But if you look closer you'll see how we used the form element to change the page and make it more user friendly and dynamic. Lines 1-8 are basically the same as the initial page1.php where our PHP form was located. However we've added a bit of PHP code to this page on lines 9-13. Line 9 is our PHP opening tag (<?) and line 13 is our PHP closing tag (?>). The only statement we're using is line 11. Line 11 uses the echo statement to print $_POST['user'] to the screen. $_POST['user'] is the variable that holds the value that was entered into the PHP form on page1.php (line 10). Now if we would have entered Joe on the form. The following results would be shown on page2.php
Hello Joe! Welcome to our website.
By using PHP forms, we can collect data from users. Either personal data such as user details in a membership system or simply their favorite color to change part of the webpage to suit them. The possibilities are endless when using PHP forms.