Working with PHP forms (Get/Post) – FREE PHP TUTORIALS #2
We are back with our next tutorial as promised and today we’ll throw some light on how to build forms in HTML and get data through get and post method in php. The HTML <form> element is used to collect user input. Form makes use of different tags like <input> , <select> , <textarea> ,etc
READ MORE : Introduction to Web Development with PHP
Getting started with PHP Forms
Action attribute specifies where to send the form data. Keep it blank for now. A form can constitute one or more of the following:
Enter some text :<br>
<input type="text" name="sometext" placeholder="Type in here">
<input type="checkbox" name="c" value="checked"> Checked! <br>
<input type="checkbox" name="c" value="unchecked"> Unchecked
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female
<input type="submit" value="Submit">
On clicking the submit button, the form send the data to the page specified in action attribute. Make sure you close the form tag
The type attribute specifies the type of <input> tag to display. The default type is: text. There are more than 20 type attribute values for the <input> tag.
- Appends form-data into the URL (specified in action) in name=value pairs
- The length of a URL is limited about 3k characters.
- It must not be used to send important data as the data will be visible in the URL.
- Appends form-data inside the body of the HTTP request (data is not shown is in URL)
- It has no size limitations.
- It is more secured.
Now begins the php part. The PHP superglobals $_GET and $_POST are used to collect form-data using get and post method respectively. Superglobals are those variables, which have a global scope i.e. they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special. When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file mentioned in the action attribute. As we had kept it blank, so the form-data will be submitted to the same file.(php form )
Include the following code at the beginning of the file.
$text_entered = $_POST["sometext"];
echo 'You wrote : ' $text_entered.'<br />';
The output could be something like this:
$_GET & $_POST takes the name of input type as its parameter and it is case sensitive.
$c = $_POST['c'];
$n = "";
foreach($c as $i)
$g = $_POST['gender'];
If you get stuck anywhere, you can always use
to debug the code.