PHP and HTML Forms
Data can be passed from the client to the server via either HTML forms or HTML links.
HTML form example
Save the following code in a file named index.html. Notice that the form tag has two attributes which determine how the data is sent to the server:
- action - indicates which file the browser should request from the server when the user hits the submit button
- method - indicates how the data from the form should be sent to the server along with that request.
- there are two varieties of HTTP requests: GET and POST.
- GET is the default request method used by web browsers, unless another is specified in the code.
<!doctype html> <html> <head> <title>Form Action Example</title> <meta charset="utf-8" /> </head> <body> <div class="container"> <h1>Form Action Example</h1> <p>Note that the form action tells the browser what page to request once the user clicks submit. Note also that the method of that request will be GET.</p > <form action="process_form.php" method="GET"> <label>Please enter a search term:</label> <input type="text" name="q" /> <input type="submit" value="Go!" /> </form> </div> </body> </html>
The script that processes data from the form
Save the following code in a file named process_form.php. When a user submits the form on the index.html page, the data from that form will be sent along with the request for this file. Notice that, since the HTML form indicated it was using the GET request type, this script looks for the data sent along with the request in a built-in PHP variable called $_GET that just so happens to automatically be populated by PHP with the data that was sent along with the request.
<!doctype html> <html> <head> <title>Process Form Input</title> <meta charset="utf-8" /> </head> <body> <div class="container"> <h1>Process Form Input</h1> <p>This page shows you what the user entered in the form on the previous page.</p> <h2>What is stored in PHP's built-in $_GET variable:</h2> <pre><?php print_r($_GET); ?></pre> <h2>What the user entered in the form:</h2> <pre><?php print($_GET['q']); ?></pre> <h2>Why we care?</h2> <p> It might be useful for you to know what the user entered in the previous form if this page has different behavior depending upon what they entered. For example, if a user is supposed to use the form to log in, then you could check what they entered to see whether it is a valid login/password, and redirect them to two different pages depending on whether their login was valid or not. </p> </div> </body> </html>