Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
653,7 KB
Nội dung
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’])) { if($_POST[‘state’] == $scode) { echo “ selected=’selected’”; } } else { if($n < 2) { echo “ selected=’selected’”; } } echo “>$state\n</option>”; } echo “</select></div>”; } else ➝118 { if(preg_match(“/pass/i”,$field)) $type = “password”; (continued) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 382 Part IV: Applications Listing 12-3: (continued) else $type = “text”; echo “<div id=’field’> <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. ➝77 Opens the <div> that contains the registration form. ➝82 Begins an if statement that checks whether an error message exists for the registration form. If the message exists, the message is displayed. ➝86 Starts a foreach statement that loops through the array of fields for the login form and echoes the fields for the form. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 383 Chapter 12: Building a Members Only Web Site ➝88 Begins an if statement that checks whether the field is state. If it is, a drop-down list is created for the customer to select a state. Note that lines 93 and 94 call functions. These functions — my functions, not PHP functions — are included in the program on line 21. The functions create arrays from a list of state names and a list of two-letter state codes. The functions eliminate the need to include the two 50-state lists in the program. The functions can be used repeatedly for many programs. The function12.inc file contains the two functions, as follows: <?php function getStateCode() { $stateCode = array(1=> “AL” , “AK” , “AZ” , . “WY” ); return $stateCode; } function getStateName() { $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 the program that displays the page that new members see. Listing 12-4: Welcoming New Members <?php /* Program: New_member.php * Desc: Displays the new member welcome page. Greets member by name and gives a choice to enter * restricted section or go back to main page. */ session_start(); ➝7 if (@$_SESSION[‘auth’] != “yes”) ➝9 { header(“Location: login.php”); exit(); } include(“dogs.inc”); ➝14 $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die (“Couldn’t connect to server.”); ➝16 $sql = “SELECT firstName,lastName FROM Member ➝17 WHERE loginName=’{$_SESSION[‘logname’]}’”; $result = mysqli_query($cxn,$sql) or die(“Couldn’t execute query”); $row = mysqli_fetch_assoc($result); extract($row); echo “<html> <head><title>New Member Welcome</title></head> <body> <h2 style=’margin-top: .7in; text-align: center’> Welcome $firstName $lastName</h2>\n”; ?> ➝28 <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. Therefore, if $auth doesn’t equal yes, the customer isn’t logged in. If a customer tries to run the New_member.php program without running the Login.php program first, $_SESSION[auth] won’t equal yes, and the user is sent to the login page. ✓ The program gets the customer’s first and last names from the database, beginning with the database connection statement on line 15. ✓ The query is created, on line 17–18, by using $_SESSION[logname] to search for the member’s information. The session variable logname that contains the Member ID was set in the login program. ✓ The PHP section ends on line 28. The remainder of the program is HTML. ✓ The program uses two different forms to provide two different submit buttons. The form statements on lines 40 and 44 start different programs. The customer controls what happens next. If the customer clicks the button to return to the main page, the PetShopFront.php program runs. If the cus- tomer clicks the Members Only Section submit button, the first page of the Members Only section of your Web site is shown. Writing the Members Only section The Web pages in the Members Only section are no different than any other Web pages. You just want to restrict them to members who are logged in. To do this, you start a session and check whether they’re logged in at the top of every page. The statements for the top of each program are session_start(); if(@$_SESSION[‘auth’] != “yes”) { header(“Location: Login.php”); exit(); } Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 386 Part IV: Applications 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 buttons for changing the password or updating customer information. You don’t need to wait until an application has all its bells and whistles to let your customers use it. You can write it one step at a time. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part V The Part of Tens Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. In this part . . . T he chapters in this part contain hints, tips, and warnings based on my experience. Perhaps they can serve as a shortcut for you on your journey to becoming a confident Web developer. I sincerely hope so. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 13 Ten Things You Might Want to Do Using PHP Functions In This Chapter ▶ Finding out about many useful functions ▶ Understanding what functions can do O ne of the strongest aspects of PHP is its many built-in functions. In this chapter, I list the PHP functions that I use most often. Some of them I describe elsewhere in this book, some I mention only in passing, and some I don’t mention at all. The PHP language has many hundreds of functions. For a complete list of PHP functions, see the PHP documentation at www.php. net/manual/en/funcref.php. Communicate with MySQLPHP 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. ✓ message: The content that goes inside the e-mail message. ✓ headers: A string that sets values for headers. For instance, you might have a headers string as follows: “From: member-desk@petstore.com\r\nbcc: mom@hercompany.com” The header would set the From header to the given e-mail address, plus send a blind copy of the e-mail message to mom. The following is an example of PHP statements that you can use in your script to set up and send an e-mail message: $to = “me@test1.com”; $subj = “Test”; $mess = “This is a test of the mail function”; $headers = bcc:techsupport@mycompany.com\r\n $mailsend = mail($to,$subj,$mess,$headers); Sometimes you might have a problem with your e-mail. PHP has a configuration setting that must be correct before the mail function can connect to your system e-mail software. Your Web host has the correct settings. On other computers, the default is usually correct, but if your e-mail doesn’t seem to be getting to its destination, check the PHP configuration mail setting by looking for the following in the output of phpinfo(): Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... instructions for installing and configuring the Web software on your computer Appendix A provides instructions for installing Apache, PHP, and MySQL with the XAMPP installer Appendix B provides instructions for configuring PHP on your computer Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Appendix A Installing PHP, MySQL, and Apache from XAMPP Y ou can install PHP, MySQL, and... PHP program You can find a table that shows where PHP settings can be changed at www .php. net/manual/en/ini.list .php One column in the table is labeled Changeable The codes in that column define where the setting can be changed, as follows: ✓ PHP_ INI_ALL: Can be changed anywhere ✓ PHP_ INI_PERDIR: Can be changed in the htaccess file ✓ PHP_ INI_USER: Can be changed temporarily in the PHP program ✓ PHP_ INI_SYSTEM:... configuration settings are stored in a text file named php. ini PHP looks for the file php. ini when it begins and uses the settings it finds If PHP can’t find the file, it uses a set of default settings All PHP settings can be changed in the php. ini file Some settings should always be changed, and some should be changed only in specific circumstances For example, magic quotes should always be turned off... 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... access to the php. ini file and can change the settings yourself However, a Web host isn’t going to allow you access to the general php. ini file, because it controls the settings for all the users on the computer, not just for your site So, you change any PHP settings on your Web hosting account with a different procedure: ✓ A local php. ini file: Some Web hosts allow you to have a local php ini file... local php ini file that controls: PHP s behavior for your Web site only If so, you can make any needed changes in this local php. ini file ✓ An htaccess file You can add directives to your htaccess file that change PHP settings Only some settings can be changed this way ✓ A statement in the PHP program: You can add a statement to a PHP program that changes the settings for that program The new settings... the figure, Apache and MySQL are shown as not running, with a red background on the icon For your development environment to be ready for work, both must be running 9 If Apache and/or MySQL are not running, click Start for each package that isn’t running The icon changes to say “Running” with a green background When both Apache and MySQL are running, your environment is ready for work You can now close... only in the php. ini file Throughout this book, I discuss various settings in context When I discuss a setting, I discuss how to change it For example, when I discuss error handling in PHP programs, I discuss the various settings that apply to error handling and how to change them Changing Settings in php. ini You can change all your PHP settings in the php. ini file You can always edit your own php. ini file... allows you a local php. ini on your Web site, you can edit that also with an editor In the general php. ini file Because php. ini is a text file, you can edit it with any text editor Follow these steps to do so: 1 Locate the php. ini file that is currently in effect As explained in Chapter 2, you can see that path to this file in the output from the phpinfo() statement in a PHP program 2 Open php. ini in your... on www.verypdf.com to remove this watermark Appendix B Configuring PHP T his appendix assumes that you have the Web software installed PHP has many configuration settings that determine how it behaves I talk about PHP settings at various places throughout the book For instance, I talk about the PHP error settings when I explain how PHP errors work in Chapter 6 I explain the settings and when they need . id=”reg”> <form action=”< ?php echo $_SERVER[ PHP_ SELF’]?>” method=”post”> <fieldset><legend>Registration Form</legend> < ?php. margin-bottom: .5em’ value=”Register” /> </fieldset> </form> </div> ➝137 </div></body></html> The following numbers refer