Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 30 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
30
Dung lượng
692,52 KB
Nội dung
Chapter 2: Creating PHP Pages Using PHP6 31 How It Works By defining the constant known as FAVMOVIE , you have set the value as “ The Life of Brian, ” which can be recalled and displayed later on. Although this constant can ’ t be changed or reset throughout your script, it is available for use by any part of your script. Overview of Variables Unlike constants, variables are obviously meant to be variable — they are meant to change or be changed at some point in your program. Variables do not need to be defined or declared and can simply be assigned when needed. They act as a container that stores information for later use in your scripts, and the contents of them can be changed. Variables are denoted with a dollar sign ( $ ) and are case - sensitive (in other words, $dateEntered and $DateEntered are treated as different variables). The first letter of the variable name must be an underscore or letter, and cannot be a number. Try It Out Using Variables In this exercise, you ’ ll add variables to your existing script. 1. Open your text editor, and make the following changes to your moviesite.php file (noted in highlighted lines): < html > < head > < title > My Movie Site < /title > < /head > < body > < ?php define(‘FAVMOVIE’, ‘The Life of Brian’); echo ‘My favorite movie is ‘; echo FAVMOVIE; echo ‘ < br/ > ’; $movierate = 5; echo ‘My movie rating for this movie is: ‘; echo $movierate; ? > < /body > < /html > 2. Save the changes, and access the file in your browser. Your screen should now look like the one in Figure 2 - 5 . c02.indd 31c02.indd 31 12/10/08 5:46:36 PM12/10/08 5:46:36 PM 32 Part I: Movie Review Web Site How It Works The value 5 is assigned to the variable movierate . Numbers do not need to be quoted as strings do. In fact, the following would cause PHP to see the value of movierate as a string containing the character 5: $movierate = ‘5’; Keeping this value as an integer makes it much easier to perform mathematical calculations on it later on, such as giving the viewer the average movie rate. For example: < ?php $bobsmovierate = 5; $joesmovierate = 7; $grahamsmovierate = 2; $zabbysmovierate = 1; $avgmovierate = (($bobsmovierate + $joesmovierate + $grahamsmovierate + $zabbysmovierate) / 4); echo ‘The average movie rating for this movie is: ‘; echo $avgmovierate; ? > Figure 2-5 c02.indd 32c02.indd 32 12/10/08 5:46:36 PM12/10/08 5:46:36 PM Chapter 2: Creating PHP Pages Using PHP6 33 PHP also has numerous built - in mathematical functions that you can use on variables that contain numbers, such as: rand([$min, $max]) : Returns a random number. ceil($value) : Returns the next highest integer by rounding the value upwards. floor($value) : Returns the next lowest integer by rounding the value downwards. number_format($number[,$decimal_places[,$decimal_point, $thousands_sep]]) : Formats the number based on the chosen number of decimal places, using the designated decimal point and thousands separator if they are provided. By default, PHP uses a period for the decimal point and a comma for the thousands separator, so if that ’ s acceptable for you, you can leave off the optional parameters, as noted by the brackets above. If you would like to take out the comma, for example, you could type the following code: $price = 12345.67; number_format($price); //returns 12,345.67 number_format($price, 2, ‘.’, ‘’); //returns 12345.67 max($value1[, $value2[, $ ]]) : Returns the largest value found in the set of supplied arguments. min($value1[, $value2[, $ ]]) : Returns the smallest value found in the set of supplied arguments. For a listing of more useful functions that are available to you in PHP, please refer to Appendix C . Passing Variables between Pages Suppose your web site allows viewers to enter their name on the front page. You ’ d like to be able to greet the user by name on each page in your web site, but to do so you need some way to pass the value of the name variable from page to page. There are basically four ways to accomplish this task: pass the variables in the URL, through a session, via a cookie, or with an HTML form. The method you choose is based on the situation and what best fits your needs at the time. Passing Variables through a URL The first method of passing variables between pages is through the page ’ s URL. You ’ ve undoubtedly seen URLs such as this: http://www.mydomain.com/news/articles/showart.php?id=12345 This is an example of passing variable values through the URL. It requests that the article with the ID number of “ 12345 ” be chosen for the showart.php program. The text after the URL is called the query string . ❑ ❑ ❑ ❑ ❑ ❑ c02.indd 33c02.indd 33 12/10/08 5:46:37 PM12/10/08 5:46:37 PM 34 Part I: Movie Review Web Site You can also combine variables in a URL by using an ampersand ( & ), as in this example: http://www.mydomain.com/news/articles/showart.php?id=12345 & lang=en This asks to retrieve the file with an ID of “ 12345 ” and the language presumably equal to “ en, ” for English. There are a few disadvantages to passing variables through a URL: Everyone can see the values of the variables, so passing sensitive information isn ’ t really very secure using this method. The user can arbitrarily change the variable value in the URL and try different combinations, leaving your web site potentially open to showing something you ’ d rather not show. A user might also pull up inaccurate or old information using a saved URL with older variables embedded in it (from a bookmark, for example). Variables that you pass around in this way are accessible in your PHP code through the special $_GET array. The variable name that appears in the URL is used as a key, so to retrieve the value of id you would reference $_GET[‘id’] , or to retrieve the value of lang you would reference $_GET[‘lang’] . Try It Out Using URL Variables In this exercise, you ’ ll modify your program to show the URL variables in action. 1. Modify your moviesite.php file as follows (changes are highlighted): < html > < head > < title > My Movie Site - < ?php echo $_GET[‘favmovie’]; ? > < /title > < /head > < body > < ?php //delete this line: define(‘FAVMOVIE’, ‘The Life of Brian’); echo ‘My favorite movie is ‘; echo $_GET[‘favmovie’]; echo ‘ < br/ > ’; $movierate = 5; echo ‘My movie rating for this movie is: ‘; echo $movierate; ? > < /body > < /html > 2. Save your moviesite.php file, and start a new document in your text editor. ❑ ❑ ❑ c02.indd 34c02.indd 34 12/10/08 5:46:37 PM12/10/08 5:46:37 PM Chapter 2: Creating PHP Pages Using PHP6 35 3. Type the following code: < html > < head > < title > Find my Favorite Movie! < /title > < /head > < body > < ?php echo ‘ < a href=”moviesite.php?favmovie=Stripes” > ’; echo ‘Click here to see information about my favorite movie!’; echo ‘ < /a > ’; ? > < /body > < /html > 4. Save this file as movie1.php , and open it in your browser. Your screen should look like the one in Figure 2 - 6 . Figure 2-6 5. Now click the link and see what you get (see Figure 2 - 7 ). c02.indd 35c02.indd 35 12/10/08 5:46:37 PM12/10/08 5:46:37 PM 36 Part I: Movie Review Web Site You see the value for $favmovie as “ Stripes ” in the URL, as shown in Figure 2 - 7 , but it is also made available in the rest of the script by $_GET[‘favmovie’] and shows in the page ’ s title and body text. How It Works Here are a few points to note about your program: As you can see from the “ Title ” section of your program, PHP code can be inserted in a straight line in the midst of your HTML code. This is helpful when you just need to insert one tidbit of information grabbed from PHP. You can also insert PHP information anywhere in your HTML program, including the title. If you do not reference the favmovie value using $_GET , but instead just use $favmovie , there is nothing shown for the value. If you have E_ALL turned on in your php.ini file, you will see the “ undefined variable ” error message. You did not need to do this when you referenced $movierate , though, as the value is kept within moviesite.php ; you did not get the information from another page or source. Special Characters in URL s Passing variables through a URL poses an interesting problem if there are spaces, ampersands, or other special characters in the value of your variable. Luckily, substitutes exist for special characters that maintain the integrity of the variables ’ values. There is a special function called urlencode() to use when passing these values through a URL. If you wanted to change your favorite movie from “ Stripes ” ❑ ❑ ❑ Figure 2-7 c02.indd 36c02.indd 36 12/10/08 5:46:38 PM12/10/08 5:46:38 PM Chapter 2: Creating PHP Pages Using PHP6 37 to “ Life of Brian, ” you would use urlencode() to encode the value and insert the proper HTML special characters. To try this out, perform these steps: 1. Make the following highlighted changes to your movie1.php file: < html > < head > < title > Find my Favorite Movie! < /title > < /head > < body > < ?php //add this line: $myfavmovie = urlencode(‘Life of Brian’); //change this line: echo “ < a href=\”moviesite.php?favmovie=$myfavmovie\” > ”; echo ‘Click here to see information about my favorite movie!’; echo ‘ < /a > ’; ? > < /body > < /html > 2. Save the file, and open it again in your browser. Clicking the link now displays the page shown in Figure 2 - 8 . Figure 2-8 c02.indd 37c02.indd 37 12/10/08 5:46:38 PM12/10/08 5:46:38 PM 38 Part I: Movie Review Web Site Passing Variables with Sessions As we mentioned before, passing a value through a URL is fine if the information is not of a particularly sensitive nature, or if it is relatively static and there is no danger of a user pulling up old information from a previously saved page. If you are transmitting information such as usernames or passwords, however, or personal information such as addresses and phone numbers, better methods exist for passing the information while keeping it private, such as using cookies. You ’ ll learn more about cookies in Chapter 12 . A session is basically a temporary set of variables that exists only until the browser has shut down. Examples of session information include a session ID and whether or not an authorized person has logged in to the site. This information is stored temporarily for your PHP programs to refer back to whenever needed. Every session is assigned a unique session ID, which keeps all the current information together. Your session ID can either be passed through the URL or through the use of cookies. Although it is preferable for security reasons to pass the session ID through a cookie so that it is hidden from the human eye, if cookies are not enabled then the backup method is through the URL. This setting is determined in your php.ini file. If you would like to force the user to pass variables through cookies (instead of allowing a backup plan), you would set the following line: session.use_only_cookies = 1 Also, make sure before using sessions that your php.ini file has been modified to show a valid path for session.save_path , as described in Chapter 1 . Then all you need to do to begin a session in PHP is call the function session_start() . But first, you need to decide what information will be stored in your session. Anything that has been stored in a database can be retrieved and stored temporarily along with your session information. Usually, it is information such as username and login information, but it can also be preferences that have been set at some point by the user. A session identifier will also be stored in the session array of variables. Try It Out Passing the Visitor ’ s Username Suppose you want to pass your visitor ’ s username, and whether or not he or she has authentically logged in to the site between the first page and the second page. This functionality will be discussed more in Chapter 12 , but for now we ’ ll whip together a quick sample to highlight passing the visitor ’ s username in a session variable. Follow these steps: 1. Change your movie1.php file to include the following highlighted lines. < ?php session_start(); $_SESSION[‘username’] = ‘Joe12345’; $_SESSION[‘authuser’] = 1; ? > < html > c02.indd 38c02.indd 38 12/10/08 5:46:38 PM12/10/08 5:46:38 PM Chapter 2: Creating PHP Pages Using PHP6 39 < head > < title > Find my Favorite Movie! < /title > < /head > < body > < ?php $myfavmovie = urlencode(‘Life of Brian’); echo “ < a href=\”moviesite.php?favmovie=$myfavmovie\” > ”; echo ‘Click here to see information about my favorite movie!’; echo ‘ < /a > ’; ? > < /body > < /html > 2. Now save your movie1.php file. 3. Open moviesite.php to make the following highlighted changes: < ?php session_start(); //check to see if user has logged in with a valid password if ($_SESSION[‘authuser’] != 1) { echo ‘Sorry, but you don\’t have permission to view this page!’; exit(); } ? > < html > < head > < title > My Movie Site - < ?php echo $_GET[‘favmovie’]; ? > < /title > < /head > < body > < ?php echo ‘Welcome to our site, ‘; echo $_SESSION[‘username’]; echo ‘! < br/ > ’; echo ‘My favorite movie is ‘; echo $_GET[‘favmovie’]; echo ‘ < br/ > ’; $movierate = 5; echo ‘My movie rating for this movie is: ‘; echo $movierate; ? > < /body > < /html > 4. Click the link in movie1.php , and you should see the text for moviesite.php shown in Figure 2 - 9 . c02.indd 39c02.indd 39 12/10/08 5:46:39 PM12/10/08 5:46:39 PM 40 Part I: Movie Review Web Site How It Works Here are a few important things to note about this procedure: All PHP session information is at the top of the page, before any HTML code is used. This is very important! If there is even a leading space before the PHP code at the top of the page, you will receive an error such as: Warning: session_start(): Cannot send session cache limiter - headers already sent(output started at C:\Program Files\Apache Software Foundation\Apache2.2\ htdocs\moviesite.php:1) in C:\Program Files\Apache Software Foundation\ Apache2.2\htdocs\moviesite.php on line 2 Some other situations also will give you the “ headers already sent ” error, which we discuss in Chapter 18 . Refer to the session variables using syntax $_SESSION[‘varname’] . If you don ’ t, then the variables will contain empty values, and you may receive a warning message. You must use the function session_start() before you send any output to the browser and before you use any session variables. It ’ s best to place session_start() at the beginning of your script. ❑ ❑ ❑ ❑ Figure 2-9 c02.indd 40c02.indd 40 12/10/08 5:46:39 PM12/10/08 5:46:39 PM [...]... your web site visitors, it might get a little labor-intensive on your part What do you say to letting your users supply you with information for a change? If you’ve never filled out a form online, then you have probably been living in a cave somewhere with no Internet access Forms are the great Venus flytraps, just lying in wait to gobble up useful information from web site visitors Forms allow your web. .. 41 c02.indd 41 12/10/08 5:46:39 PM Part I: Movie Review Web Site You make each of these settings as follows: setcookie($name[, $value[, $expire[, $path[, $domain[, $secure]]]]]) As you can probably guess by now, those values will be referenced in the script as $_COOKIE[‘cookiename’] Try It Out Setting a Cookie In this exercise, you’ll have the web site set a cookie on Joe’s machine so that he (theoretically)... potential security risks (however minute), you are encouraged to visit the W3 Security FAQ web site at www.w3.org/Security/faq/wwwsf2.html#CLT-Q10 Because your visitors may either have cookies turned off or may physically delete cookies from their computers, relying on cookie information probably isn’t the best idea from a web development standpoint So why do developers use cookies, anyway? The advantage of... this file in the three existing movie web site files, add the following line, immediately after the tag, to login.php, movie1.php, and moviesite.php: 4 Save your files 5 Take a look at the files again If you open login.php, you should see the screen shown in Figure 2-13 53 c02.indd 53 12/10/08 5:46:43 PM Part I: Movie Review Web Site Figure 2-13 You will see the... previous example lingering about) Then open the movie1.php file Click the link, and your screen should look like the one in Figure 2-10 Figure 2-10 43 c02.indd 43 12/10/08 5:46:40 PM Part I: Movie Review Web Site How It Works If you didn’t notice, you changed the username from Joe12345 when you were using sessions, to Joe when you were using cookies This was to double-check that the information was coming...Chapter 2: Creating PHP Pages Using PHP6 Passing Variables with Cookies Cookies are tiny bits of information stored on your web site visitor ’s computer There appears to be some sort of paranoia about using cookies In theory, cookies can be intercepted to gain information such as a person’s IP address and operating system,... let’s move on Try It Out Using Forms to Get Information Because your program is slowly increasing in size, for this exercise, we suggest you switch to a text editor that will add line numbers to your document If you are using a text editor that inserts these line numbers already, you do not need to worry about adding these in Otherwise, you may want to add periodic line numbers as comments to help... ($_SESSION[‘userpass’] == ‘12345’)) { $_SESSION[‘authuser’] = 1; } else { echo ‘Sorry, but you don\’t have permission to view this page!’; exit(); } ?> 45 c02.indd 45 12/10/08 5:46:41 PM Part I: Movie Review Web Site Find my Favorite Movie! . between Pages Suppose your web site allows viewers to enter their name on the front page. You ’ d like to be able to greet the user by name on each page in your web site, but to do so you need. C:Program FilesApache Software FoundationApache2.2 htdocsmoviesite.php:1) in C:Program FilesApache Software Foundation Apache2.2htdocsmoviesite.php on line 2 Some other situations also. great Venus flytraps, just lying in wait to gobble up useful information from web site visitors. Forms allow your web site to be truly interactive; they take data from the user and send it off