Review Welcome to the ongoing PHP
programming course for PHP. So far we have reviewed strings, arrays (including
manually filling them and determining the size of them), using the
date function to make things happen based on what day it
is, randomization of numbers and events, how to blend PHP with
HTML, and we have created two useful scripts you are welcome to use on any/or
all of your websites: a pic of the day script and a random quote of the day
script. If you have never done any programming before and you have just
discovered this course tutorial first, you are encouraged to go back and go
through the other four tutorials before continuing with this week's tutorial
which is on forms. These tutorials build on concepts and functions learned in
the prior week's tutorials.
Demystifying
Forms
A lot of this tutorial is
going to focus on HTML, since most of the work involving forms is actually the
HTML which builds the form input. If you already understand how to build forms
using HTML, then you should probably skip down to the section below about how
to process form input using PHP. Once you understand the basic components of a
form you can set up very basic to very elaborate forms. Starting a form begins
with the HTML tag:
<FORM>
Within the <FORM> tag
you have several properties that you will need to define. The method,
and action (and in some cases the type) are the ones you will
need to concentrate on for your PHP scripts. Here is a list and a brief
description of them:
name -
different forms can have different names on an HTML page, this identifies the
entire form to a script
action - This is the place to send the information you
gather within the form after someone presses submit - I know it seems odd and
maybe a little backwards to be defining what happens at the end in the
beginning, but this tag modifier is not optional for PHP scripting. You can
also send information from the form to an email address to by using mailto. method - This will be either "GET" or "POST" - a GET is
more commonly used on the browser line or via a url with a question mark at the
end to send information to a script and has space limitations (this is often
known as using a query string). The POST method does not have these
restrictions and is the one you will use most often (more on this
below). enctype - If you are
going to be uploading files in your form, or sending text to email,
you will need to use this modifier.
There are two types of
methods: GET and POST. Without getting too technical here, you
really only need to understand at this point that the difference between GET
and POST is the size of the data that can be transferred to the server. If you
use the GET method you will be restricted to transferring a smaller amount of
data into your scripts. Therefore, I would recommend in general that you use
the POST method. Let's see how this looks:
<FORM
method="POST"
Note: capitalization in HTML
is not vital like it is in the UNIX world.
The action tag is
used to point to where the contents of the form will be sent. In our case it
will be to the PHP script. But if you were doing Perl programming you might
point this to a CGI script. You will use the relative or full path to the
script. Therefore if our script is located in the scripts directory on our
domain the FORM tag would look like this:
Either one of the above will
work, although the relative path is the preferred method. You could, of course,
substitute your domain for your domain's IP address and that would work also.
The main thing to remember is where the action points is where the
contents of the form will be sent for processing.
Assembling the form -
the components
I am going to give you a brief
overview of most of the input form components that you can use. This list is
not all-inclusive. You might notice that most of the input boxes are
similar in their construction. Let's review the basic modifiers:
type -
this is used to tell what type of input box we want to use, valid values
include text, password,
submit, button name - the name
that will identify to the script what it is or contains value - the default value that the input box will send to the
script if nothing is changed by the site visitor size
- horizontal (think left to right) size of the box
Probably the most common in
use is the text box. To make a text box you would use the
following HTML code:
<input
type="text" name="field_name" value="You can put a default
value in the box here" size="20">
<--- this is called a
text box. It is useful for getting a rather small piece of
typed information, such as an email address, a username, a real name, address,
etc.
To change to a password text
box just change the type as follows:
<input
type="password" name="field_name" value="You can put a default
value in the box here" size="10">
<--- this is a
password text box and anything you type in will result in
***** instead of the actual letters or digits. Use this type of box for
passwords or entering sensitive information you don't want other people to be
able to see as you type. Note that using this is still transferring the
information insecurely unless you are using a secure server. The only
thing this protects against is people seeing what you type into the box.
input
hidden tags - these convey important information to a script.
The name is kind of deceptive since they aren't truly hidden (surfers
can view the source of your HTML and see the hidden names and values, unless
you block them out some other way), but they are hidden from showing up inside
the form on the web page.
<input
type="hidden" name="field_name" value="you must define the
value in a hidden field">
For gathering larger pieces of
text, you will probably want to use a
textarea.
<--- this is
called a textarea This will allow up to 32,700
characters of input. Even I can get my point across in 32,700 characters
:)
<textarea
rows="2" name="field_name" cols="26" WRAP>default text
here</textarea>
TEXTAREA
Modifiers:
ROWS=x - where x
is the number of rows (think across) the size of the textarea will be COLS=y - where y is the number of columns (think up and
down) the size of the textarea will be WRAP - this will wrap the lines within the
margins as person types, also NOWRAP can force the
opposite
Allowing visitors to
select items from menus
<-- this is a
checkbox. Useful for menus where you want to allow multiple
items to be checked or unchecked. If it is
checked than the value sent to the script will be whatever is
in the value field.
<input type="checkbox" name="field_name"
value="value to send script if box is checked here">
yes
no <-- this is a
radio button. Useful for forcing only one selection
from a group of choices (like yes or no queries, for example)
Modifiers:
SELECTED will make a default option
MULTIPLE will allow users to make multiple choices
<--- this is a push
button it looks like a SUBMIT button, but it is not the same
thing, it will not submit the contents of a form to be processed, it
will indicate whether it is on or off (has been pushed or not pushed). This is
more useful for executing JavaScript then PHP code.
<-- You can use an image to submit a form
instead of those boring looking gray blocks. You should keep in mind though,
that some people expect to see those gray blocks to know what to push to
actually submit the form.
<input src="/path/to/image.jpg" name="field_name" width="62"
height="89" alt="image alt tag description"
type="image">
<--- this is called a submit
button - it will submit the contents of a form to a CGI script for processing
<input
type="submit" value="Submit">
<--- this is a reset button - it resets the contents of the
entire form to its default condition
<input type="reset"
value="Reset">
Common
reasons a form might not behave the way you want:
- Failure to
include the closing tag </form> </select>, etc. - The
action modifier is not defined or defined to the wrong path or
URL to the PHP script. - You are using a FrontPage designed form on a
website that doesn't support FrontPage extensions. Front Page adds a
--webbot code to the action
modifier. This must be removed and changed to point to your PHP script. -
When using radio buttons, the name must be
the same for each set so only one button can be pushed. If you want to
allow multiple choices, use a checkbox
instead.
Processing the results of a form using
PHP
Now that you have seen how the
form is assembled using HTML we can examine how PHP deals with form input. For
those familiar with Perl and other other languages you will be pleased to know
that PHP has a built-in parsing routine! It is easy to take the input from a
form and work with it because the input name becomes a $string variable. Let's
look at the following HTML code from above.
<input
type="text" name="field_name" value="You can put a default
value in the box here" size="20">
The PHP code to print the
results of this input field would be this:
<? echo($field_name);
?>
This would print the
$field_name variable which came from the form input to the browser (sans the
italics): You can put a default value in the box here
Now let's create a PHP script
which demonstrates taking input and processing it. It will test your knowledge
over the last 5 weeks with five somewhat easy questions. If you have been
paying even a little bit of attention you will score 100% :) We will name this
script forms_quiz.php3.
<HTML> <BODY>
<? $q =
array(2,0,1,2,2); $q1_bad = array("is a container for integers only",
"name can start with a number",
"can contain words, sentences, integers"); $q2_bad = array("a container for
strings",
"a mathematical approach to storing integers",
'$string[x]'); $q3_bad = array("CGI", "HTML", "PHP"); $q4_bad =
array("HTML & CGI", "PHP", "HTML & PHP"); $q5_bad = array("sint",
"intrand", "srand");
if ($action
== "true") { $right = 0; print("Thank you for taking the
PHP Quiz!");
if ($answer_1 == $q[0]) { $right++;
} if ($answer_2 == $q[1]) { $right++; }
if ($answer_3 == $q[2]) { $right++; }
if ($answer_4 == $q[3]) { $right++; } if ($answer_5 ==
$q[4]) { $right++; }
$percentage = ($right / 5) * 100;
print("<p>You scored <strong>$percentage %</strong> on the
quiz!</BODY></HTML>"); exit; } ?>
<FORM METHOD="POST"
ACTION="forms_quiz.php3"> <input type="hidden" name="action"
value="true"> Take the PHP Week 5 Quiz<p> Question 1: A string
is ... <br> <input type="radio" value="0"
name="answer_1"><?
echo($q1_bad[0]); ?> <input
type="radio" value="1" name="answer_1"><? echo($q1_bad[1]); ?> <input type="radio" value="2" name="answer_1"><? echo($q1_bad[2]);
?> <br>Question 2: An array
is ... <select name="answer_2"> <option selected
value="0"><?
echo($q2_bad[0]); ?></option>
<option value="1"><? echo($q2_bad[1]); ?></option> <option value="2"><? echo($q2_bad[2]);
?></option>
</select> <br>Question 3: Building a form primarily requires
... <input type="radio" value="0" checked
name="answer_3"><?
echo($q3_bad[0]); ?> <input
type="radio" value="1" name="answer_3"><? echo($q3_bad[1]); ?> <input type="radio" value="2" name="answer_3"><? echo($q3_bad[2]);
?> <br>Question 4: This
script is an example of ... <select name="answer_4"> <option
selected value="0"><?
echo($q4_bad[0]); ?></option>
<option value="1"><? echo($q4_bad[1]); ?></option> <option value="2"><? echo($q4_bad[2]);
?></option>
</select> <br>Question 5: Before generating random numbers you
use ... <input type="radio" value="0" name="answer_5"><? echo($q5_bad[0]);
?> <input type="radio" value="1"
name="answer_5"><?
echo($q5_bad[1]); ?> <input
type="radio" value="2" name="answer_5"><? echo($q5_bad[2]); ?> <p><center><input type="submit"
value="Submit"> <input type="reset"
value="Reset"></center>
</FORM> </BODY>
</HTML>
Notes: You will see that this
is one page/file, self contained, and will display the results of the quiz, or
the quiz questions if they haven't been answered yet, depending on the
existence of the hidden form tag named action. In blue is all the PHP
code and the HTML is in black. A separate HTML page could also be created that
calls this forms_quiz.php3 script if you didn't want to have
it all in one file. I was careful to use only concepts we've covered so far so
hopefully this will be in a more logical order. About the only thing that is
new here is the bolded blue line with the $percentage calculation. I would
wager that most of those in the audience are better at math than me. Since
there are only 5 questions, you would use the formula: $right answers divided
(/) by number of questions (5) and then multiply (*) that result by 100. We
could have also used the function printf to add the trailing
zeroes instead of multiplying the result by 100.
What about
Security?!?!
Similar to my first
date example back in the first week, I wanted to show you how
the code looks logically in a fatter coding example. Experienced programmers
will probably (and rightfully) point out that this code really doesn't take any
security precautions and loops could have been used to make the code
as written more efficient.
Using loops to prevent
repetitive code
There are various kinds of
loops but probably the most common ones you'll use are for() loops or a while()
loops. Let's take the select dropdown code above and make a for() loop to
modify the code above. Here's the syntax for a for() loop:
for($variable = value;
$variable COMPARED value; $variable DECREMENT/INCREMENT) { // while
condition is valid do what's inside here }
You can hopefully see how
instead of 3 lines we now have one which will do the same thing. Now let's use
a while() loop to do the same thing:
<? $i=0; //
assign the starting index value while($i<3) { print("
<input type=\"radio\" value=\"$i\"
name=\"answer_1\">$q1_bad[$i]>
"); $i++; }
?>
(basic) TO-DO
ASSIGNMENT: Write a script to submit a username and password to enter a page.
If the username and password does not match the variable hardcoded in the
script show the login form again with an error message. The password field
should be private so that as you type you'll see ****. This should all be
one self-contained script with NO include() or require() files. (advanced) TO-DO ASSIGNMENT: Write a script to
submit a username and password to enter a page. If the username and password
does not match the variable hardcoded in the script show the login form again
with an error message. The password field should be private so that as you type
you'll see ****. Upon correct login display a list of banners in an array from
a select box to display (you can use either a single or multi-dimensional
array). Upon choosing a banner and pressing submit, then have the script print
the banner to the browser. This will allow for an account of banners that only
a person with the correct username/password can get in and view by image path.
Use either a for() or while() loop to create the dropdown SELECT box with the
available banners in the array and hidden form tags to transfer the validated
password. This should all be one self-contained script with NO include() or
require() files.
Need help with your assignment or have
questions about the first week's course?
This concludes our fifth
course on PHP programming. In the next course we'll examine how to send mail
using PHP.
TDavid is co-owner, programmer and webmaster for several sites
devoted to programming including his own
http://www.tdscripts.com/ He has done custom programming
in various programming languages for companies all over the world. Every Friday
at 2pm PST you can catch his weekly radio show dedicated to the technical side
of webmastering and programming at
http://www.scriptschool.com/radio
Warning: require(/home/adultnetsurprise.com/public_html/multiforum/feedback.php) [function.require]: failed to open stream: No such file or directory in /home/adultnetsurprise.com/public_html/zones/learning/php/php_week_5.html on line 559
Fatal error: require() [function.require]: Failed opening required '/home/adultnetsurprise.com/public_html/multiforum/feedback.php' (include_path='.:/usr/local/lib/php') in /home/adultnetsurprise.com/public_html/zones/learning/php/php_week_5.html on line 559