381
Chapter 12: Building a Members Only Web Site
<h3>If you already have an account, log in.</h3>
<h3>If you do not have an account, register now.</h3>
</div> ➝75
<div id=”reg”>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]?>”
method=”post”>
<fieldset><legend>Registration Form</legend>
<?php
if(isset($message_2)) ➝82
{
echo “<p class=’errors’>$message_2</p>\n”;
}
foreach($fields_2 as $field => $value) ➝86
{
if($field == “state”) ➝88
{
echo “<div id=’field’>
<label for=’$field’>$value</label>
<select name=’state’ id=’state’>”;
$stateName=getStateName();
$stateCode=getStateCode();
for($n=1;$n<=50;$n++)
{
$state=$stateName[$n];
$scode=$stateCode[$n];
echo “<option value=’$scode’”;
if(isset($_POST[‘state’]))
<label for=’$field’>$value</label>
<input id=’$field’ name=’$field’
type=’$type’ value=’”.@$$field.”’
size=’40’ maxlength=’65’ /></
div>\n”;
} //end else
} // end foreach field
?>
<input type=”submit” name=”Button”
style=’margin-left: 45%; margin-bottom: .5em’
value=”Register” />
</fieldset>
</form>
</div> ➝137
</div></body></html>
The following numbers refer to the line numbers in Listing 12-3:
➝7 Creates the array that contains the fields in the login form.
➝9 Creates the array that contains the fields in the registration form.
➝21 Includes a file that contains the functions used in this program.
The file contains the functions getStateName() and getState
Code() that are used later in the program.
➝22 Ends the opening PHP section.
➝46 Opens the <div> that contains the login form.
➝50 Opens a new PHP section.
➝51 Begins an if statement that checks whether an error message
exists for the login form. If the message exists, the message is
displayed.
➝55 Starts a foreach statement that loops through the array of fields
for the login form and echoes the fields for the form.
➝75 Closes the <div> that contains the login form.
{
$stateName = array(1=> “Alabama”,
“Alaska”,
“Arizona”,
...
“Wyoming” );
return $stateName;
}
A for loop then creates 50 options for the select list, using the
two state arrays. An if statement starting on line 100 determines
which option tag should be selected, so that it will be the selected
option when the drop-down list is displayed. The if statement
checks whether a state has been selected, which means that the
customer submitted the form. If a state is found in the $_POST
array, the state is selected. If no state is found in the $_POST
array, the first state, AL, is selected.
➝118 Begins an else statement that executes if the field is not the state
field. The else block displays a text field for all the fields other
than the state field.
➝137 Closes the <div> for the registration form.
After running Login.php, if the user is successful with a login, the first page
of the Members Only section of the Web site is shown. If the user success-
fully obtains a new user account, the New_member.php program runs.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
384
Part IV: Applications
Writing New_member
The New Member Welcome page greets new members by name and provides
information about their accounts. Members then have the choice of entering
the Members Only section or returning to the main page. Listing 12-4 shows
<p>Your new Member Account lets you enter the Members
Only section of our web site. You’ll find special
discounts and bargains, a huge database of animal facts
and stories, advice from experts, advance notification
of new pets for sale, a message board where you can talk
to other Members, and much more.</p>
<p>Your new Member ID and password were emailed to you.
Store them carefully for future use.</p>
<div style=”text-align: center”>
<p style=”margin-top: .5in; font-weight: bold”>
Glad you could join us!</p>
<form action=”member_page.php” method=”post”> ➝40
<input type=”submit”
value=”Enter the Members Only Section”>
</form>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
385
Chapter 12: Building a Members Only Web Site
<form action=”PetShopFrontMembers.php” method=”post”> ➝44
<input type=”submit” value=”Go to Pet Store Main Page”>
</form>
</div>
</body></html>
Notice the following points about New_member.php:
✓ A session starts on line 7. This makes the session variables stored in
Login.php available to this program.
✓ The program checks whether the customer is logged in, starting on
line 9. When the customer successfully logs in or creates a new account
in Login.php, $auth is set to yes and stored in the $_SESSION array.
When session_start executes, PHP checks for an existing session. If one
exists, it sets up the session variables. When a user logs in, $_SESSION[auth]
is set to yes. Therefore, if $_SESSION[auth] is not set to yes, the user is not
logged in, and the program takes the user to the login page.
Planning for Growth
The original plan for an application usually includes every wonderful thing
that the user might want it to do. Realistically, it’s usually important to make
the application available to the users as quickly as possible. Consequently,
applications usually go public with a subset of the planned functionality.
More functionality is added later. That’s why it’s important to write your
application with growth in mind.
Looking at the login application in this chapter, I’m sure you can see many
things that could be added to it. Here are some possibilities:
✓ E-mail a forgotten password. Users often forget their passwords. Many
login applications have a link that users can click to have their pass-
words e-mailed to them.
✓ Change the password. Members might want to change their password.
The application could offer a form for password changes.
✓ Update information. A member might move or change his phone
number or e-mail address. The application could provide a way for mem-
bers to change their own information.
✓ Create a member list. You might want to output a nicely formatted list
of all members in the database. This probably is something you want to
make available only for yourself. In some situations, however, you might
want to make the list available to all members.
You can easily add any of these abilities to the application. For instance, you
can add to the login form a Forgot my password button that, when clicked,
e-mails the password to the e-mail address in the database. The button can
run the login program with a section for e-mailing the password or run a dif-
ferent program that e-mails the password. In the same manner, you can add
PHP has many functions designed specifically for interacting with MySQL. I
describe the following MySQL functions thoroughly in this book:
mysqli_connect(); mysqli_fetch_assoc()
mysqli_num_rows(); mysqli_query()
The following functions could be useful, but I either don’t discuss them or
discuss them only briefly:
✓ mysqli_insert_id($cxn): For use with an AUTO-INCREMENT MySQL
column. This function gets the last number inserted into the column.
✓ mysqli_select_db($cxn,$database): Selects a database. The cur-
rently selected database is changed to the specified database. All suc-
ceeding queries are executed on the selected database.
✓ mysqli_fetch_row($result): Gets one row from the temporary
results location. The row is put into an array with numbers as keys.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
390
Part V: The Part of Tens
✓ mysqli_affected_rows($result): Returns the number of rows that
were affected by a query — for instance, the number of rows deleted or
updated.
✓ mysqli_num_fields($result): Returns the number of fields in a result.
✓ mysqli_field_name($result, N): Returns the name of the row indi-
cated by N. For instance, mysqli_field_name($result,1) returns
the name of the second column in the result. The first column is 0.
Send E-Mail
PHP provides a function that sends e-mail from your PHP program. The
format is
mail(address,subject,message,headers);
These are the values that you need to fill in:
✓ address: The e-mail address that will receive the message.
✓ subject: A string that goes on the subject line of the e-mail message.
; For Win32 only.
sendmail_from =
The first setting is where you put the name of your outgoing mail server.
However you send e-mail — using a LAN at work, a cable modem at home, an
ISP via a modem — you send your mail with an SMTP server, which has an
address that you need to know.
If you send directly from your computer, you should be able to find the name
of the outgoing mail server in your e-mail software. For instance, in Microsoft
Outlook Express, choose Tools➪Accounts➪Properties and then click the
Servers tab. If you can’t find the name of your outgoing mail server, ask your
e-mail administrator for the name. If you use an ISP, you can ask the ISP. The
name is likely to be in a format similar to the following:
mail.ispname.net
The second setting is the return address sent with all your e-mail. Change the
setting to the e-mail address that you want to use for your return address, as
follows:
sendmail_from =
If you’re using Unix or Linux, looking for these lines in your php.ini file:
; For Unix only.
;sendmail_path =
This default is usually correct. If it doesn’t work, talk to your system
administrator about the correct path to your outgoing mail server.
Don’t forget to remove the semicolon at the beginning of the lines. The
semicolon makes the line into a comment, so the setting isn’t active until
you remove the semicolon.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
392
Part V: The Part of Tens
Use PHP Sessions
The functions to open or close a session follow. I explain these functions in
(“ “,$string) creates an array in which each word in $string is a
separate value. This is similar to split in Perl.
✓ implode(“glue”,$array): Creates a string containing all the values in
$array with glue between them. For instance, implode(“, “,$array)
creates a string: value1, value2, value3, and so on. This is similar to
the join function in Perl.
Many more useful array functions are available. PHP can do almost anything
with an array.
Check for Variables
Sometimes you just need to know whether a variable exists. You can use the
following functions to test whether a variable is currently set:
isset($varname); // true if variable is set
!isset($varname); // true if variable is not set
empty($varname); // true if value is 0 or is not set
Format Values
Sometimes you need to format the values in variables. In Chapter 6, I explain
how to put numbers into dollar format by using number_format() and
sprintf(). In Chapter 6, I also discuss unset(), which removes the
values from a variable. In this section, I describe additional capabilities of
sprintf().
The function sprintf() allows you to format any string or number,
including variable values. The general format is
$newvar = sprintf(“format”,$varname1,$varname2,...);
where format gives instructions for the format and $varname contains the
value(s) to be formatted. format can contain both literals and instructions
for formatting the values in $varname. In addition, a format containing only
literals is valid, such as the following statement:
$newvar = sprintf(“I have a pet”);
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
394
Kitten.............. 30.00
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
395
Chapter 13: Ten Things You Might Want to Do Using PHP Functions
Compare Strings to Patterns
In earlier chapters in this book, I use regular expressions as patterns to match
strings. (I explain regular expressions in Chapter 6.) The following functions
use regular expressions to find and sometimes replace patterns in strings:
✓ preg_match(“pattern”,$varname): Checks whether the pattern is
found in $varname.
✓ preg_replace(“pattern”,”string”,$varname): Searches for
pattern in $varname and replaces it with string.
Find Out about Strings
Sometimes you need to know things about a string, such as its length or
whether the first character is an uppercase O. PHP offers many functions for
checking out your strings:
✓ strlen($varname): Returns the length of the string.
✓ strpos(“string”,”substring”): Returns the position in string
where substring begins. For instance, strpos(“hello”,”el”)
returns 1. Remember that the first position for PHP is 0. strrpos()
finds the last position in string where substring begins.
✓ substr(“string”,n1,n2): Returns the substring from
string that begins at n1 and is n2 characters long. For instance,
substr(“hello”,2,2) returns ll.
✓ strtr($varname,”str1”,”str2”): Searches through the string
$varname for str1 and replaces it with str2 every place that it’s
found.
✓ strrev($varname): Returns the string with the characters reversed.
Many more string functions exist. See the documentation at www.php.net.
PHP’s confusion results from an error earlier in the program.
Missing Semicolons
Every PHP statement ends with a semicolon (;). PHP doesn’t stop reading a
statement until it reaches a semicolon. If you leave out the semicolon at the
end of a line, PHP continues reading the statement on the following line. For
instance, consider the following statement:
$test = 1
echo $test;
Of course, the statement doesn’t make sense to PHP when it reads the two
lines as one statement, so it complains with an error message, such as the
annoying
Parse error: parse error in c:\test.php on line 2
Before you know it, you’ll be writing your home address with semicolons at
the end of each line.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
398
Part V: The Part of Tens
Not Enough Equal Signs
When you ask whether two values are equal in a comparison statement,
you need two equal signs (==). Using one equal sign is a common mistake.
It’s perfectly reasonable because you’ve been using one equal sign to mean
equal since the first grade, when you discovered that 2 + 2 = 4. This is a dif-
ficult mistake to recognize because it doesn’t cause an error message. It just
makes your program do odd things, like infinite loops or if blocks that never
execute. I’m continually amazed at how long I can stare at
$test = 0;
while ( $test = 0 )
{
$test++;
}
$test = “<table width=\”100%\”>”;
You have too few quotes when you forget to end a quoted string, such as
$test = “<table width=’100%’>;
PHP continues reading the lines as part of the quoted string until it encoun-
ters another double quote (“), which might not occur for several lines. This
is one occasion when the parse error pointing to where PHP got confused is
not pointing to the actual error. The error occurred some lines previously,
when you forgot to end the string.
You have the wrong kind of quotes when you use a single quote (’) when you
meant a double quote (“) or vice versa. The difference between single and
double quotes is sometimes important, as I explain in Chapter 6.
Invisible Output
Some statements, such as the header statement, must execute before the
program produces any output. If you try to use such statements after sending
output, they fail. The following statements will fail because the header mes-
sage isn’t the first output:
<html>
<?php
header(“Location: ”);
?>
<html> is not in a PHP section and is therefore sent as HTML output. The
following statements will work:
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
400
Part V: The Part of Tens
<?php
header(“Location: ”);
?>
<html>
The following statements will fail