PHP Form Input
PHP Form Input
Importance
A web application receives input from the user via form input Handling form input is the cornerstone of a successful web application everything else builds on it
Overview
The browser interprets the HTML source for a particular page
Result is a combination of text, images, and entry fields Each entry field has a specific name
User fills in these fields, (with potentially some client-side input checking via JavaScript) and then selects a submission button The browser reads the input fields, and creates a message that is sent to the server
A series of name, value pairs
INPUT
Defines a specific input field
TEXTAREA
Creates a free-form text fill-in box
SELECT
Creates a menu OPTION defines options within the menu
FORM
FORM attributes
action
URL of the resource that receives the filled-in form This is the URL of your PHP code that receives the input
method
Choices are get or post you should choose post
enctype
MIME type used to send results. By default is application/xww-form-urlencoded Would use multipart/form-data if submitting a file (INPUT, type=file)
INPUT
INPUT attributes
type: the kind of user input control name: the name of the control
This gets passed through to the handling code In PHP: $_POST[name]
value: initial value of the control size: initial width of the control
in pixels, except for text and password controls
maxlength: for text/password, maximum number of characters allowed checked: for radio/checkbox, specifies that button is on src: for image types, specifies location of image used to decorate input button
File upload
file: creates a file upload control
Example
From HTML 4.1 specification
<FORM action="http://people.ucsc.edu/~ejw/m yhandler.php" method="post"> <P> First name: <INPUT type="text" name="firstname"><BR> Last name: <INPUT type="text" name="lastname"><BR> email: <INPUT type="text" name="email"><BR> <INPUT type="radio" name="sex" value="Male"> Male<BR> <INPUT type="radio" name="sex" value="Female"> Female<BR> <INPUT type="submit" value="Send"> <INPUT type="reset"> </P> </FORM>
The array indicies are the names of the form variables (INPUT name=) The array value is the user entry data
Validating Data
All web applications must validate user input data
Ensure the data is syntactically correct, and meets input constraints
Ideally want one PHP page to create form, validate input, and handle correct input
This is a little tricky
Else
Handle the input (typically by writing it to a database) Proceed to next screen in the web application
All-in-one structure
Functions for input validation Function(s) that creates form
Default values set from contents of _POST[]
HTML preamble Create initial form Validate input Recreate form Code to handle valid input HTML end
Libraries
There are many libraries that exist for handling input, and performing validation These libraries can also create client-side Javascript for client-side value checking PEAR HTML_quickform is one example