Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables My Movie Site <?php $movierate = 5; echo “My movie rating for this movie is: “; echo $movierate; ?>  The ABOVE line of code would cause the.

Similar presentations


Presentation on theme: "Variables My Movie Site <?php $movierate = 5; echo “My movie rating for this movie is: “; echo $movierate; ?>  The ABOVE line of code would cause the."— Presentation transcript:

1 Variables My Movie Site <?php $movierate = 5; echo “My movie rating for this movie is: “; echo $movierate; ?>  The ABOVE line of code would cause the value of “5” to be seen as a string:  $movierate = “5”;  By keeping this value as an integer, you can then perform mathematical calculations on this number later on. 1

2 Math Example  Here is the sample: <?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; ?> 2

3 Built-in mathematical functions  ❑ rand([min],[max]): Generates a random integer.  ❑ ceil(number): Rounds a decimal up to the next highest integer.  ❑ floor(number): Rounds a decimal down to the next lowest integer.  ❑ number_format(number [,dec places] [,dec point] [,thousands]): Formats the number based on the chosen number of decimal places, and uses the designated decimal point and thousands separator, if applicable. By default, PHP uses a period for the decimal point and a comma for the thousands separator, so if that’s acceptable for you, then you can leave off the optional parameters, as noted in brackets above. If you would like to take out the comma, for example, you would type the following code:  $price = 12345.67;  number_format($price); //returns 12,345.67  number_format($price, 2, “.”, “”); //returns 12345.67  ❑ max(argument1, argument2,...): Returns the maximum value of the supplied arguments.  ❑ min(argument1, argument2,...): Returns the minimum value of the supplied arguments. 3

4 Passing Variables between Pages  Suppose your 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 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. 4

5 A Word about register_globals  Before we begin discussing the four methods of parsing variables between pages, you need to understand a little concept called register_globals. This is a configuration setting in your php.ini file that, when turned off, prevents the variable value from being falsely inserted by an outside source. While previous versions of PHP set the default setting in php.ini to “on,” ever since version 4.2, the default has been switched to “off.” This was the cause of many a programmer’s sleepless night, because you must refer to your variables differently if register_globals is turned off, or else find all your variables’ values coming up empty.  Instead of calling variable values by the standard $varname syntax, when register_globals is “off” and you need to pass variables across pages, you need to refer to them in a different way, but only in the receiving page. 5

6 List of Methods  Here is the various ways to refer to variables depend on how they are being sent. 6

7 Passing Variables through a URL  http://www.mydomain.com/art.php?id=12345  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 change the variable value in the URL, leaving your 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. 7

8 Try It Out:Sample  In this exercise,  1. Add a file named as moviesite.php as follows :   My Movie Site -   <?php  echo “My favorite movie is “;  echo $_REQUEST[‘favmovie’];  echo “ ”;  $movierate = 5;  echo “My movie rating for this movie is: “;  echo $movierate;  ?>   2. Save your moviesite.php file and start a new document in your text editor.  3. Type the following code:   Find my Favorite Movie!   <?php  echo “ ”;  echo “Click here to see information about my favorite movie!”;  echo “ ”;  ?>   4. Save this file as movie1.php and open it in your browser. 8

9 Try It Out:Lets Discuss  Pay attention to variable name favmovie exists in both files.  pass by URL is equivalent to get method in forms.  $_REQUEST was chosen for your variable syntax because it really didn’t matter in this example where the value for favmovie came from. You were not trying to validate anything or prevent an unauthorized user from entering this page of the site: You simply wanted to pass the value across.  While passing through URL, & have a special meening, we have some additional special characters and urlencode() function to substitute. 9

10 Special Characters in URLs  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” to “Life of Brian,” you would use urlencode() to encode the value and insert the proper HTML special characters. 10

11 Try It Out Continues  1. Make the following highlighted changes to your movie1.php file: Find my Favorite Movie! <?php //add this line: $myfavmovie = urlencode(“Life of Brian”); //change this line: echo “ ”; echo “Click here to see information about my favorite movie!”; echo “ ”; ?>  2. Save the file and open it again in your browser. 11

12 Passing Variables with Sessions  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. 12

13 Passing Variables with Sessions  A session is basically a temporary set of variables that exists only until the browser has shut down (unless you set this up differently in your php.ini file).  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. 13

14 Passing Variables with Sessions  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, 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 in your file: session.use_only_cookies = 1  To begin a session, use the function session_start(). Because we assume you have register_globals set to “off”, and also session_autostart is set to off. 14

15 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 into the site between the first page and the second page.  1. Create a file named movie1.php file to include the following lines.  <?php  session_start();  $_SESSION[‘username’] = “Joe12345”;  $_SESSION[‘authuser’] = 1;  ?>   Find my Favorite Movie!   <?php  $myfavmovie = urlencode(“Life of Brian”);  echo “ ”;  echo “Click here to see information about my favorite movie!”;  echo “ ”;  ?>   2. Now save your movie1.php file. 15

16 Try It Out: Cntd  3. Create moviesite.php file and add the following lines:  <?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, you loser!”;  exit(); // to terminate unconditionally  }  ?>   My Movie Site -   <?php  echo “Welcome to our site, “;  echo $_SESSION[‘username’];  echo “! ”;  echo “My favorite movie is “;  echo $_REQUEST[‘favmovie’];  echo “ ”;  $movierate = 5;  echo “My movie rating for this movie is: “;  echo $movierate;  ?>   4. Click the link in movie1.php. 16

17 How It Works  Here are a few important things to note about this procedure:  ❑ All the session information is at the top of the page, before any HTML code. This is very important! If there is even a leading space before the PHP code at the top of the page, you will get this error: Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at c:\program files\Apache Group\Apache2\test\moviesite.php:1) in c:\program files\Apache Group\Apache2\test\moviesite.php on line 2  ❑ Refer to the session variables using the register_globals syntax, $_SESSION[‘varname’]; if you don’t, the variables will contain empty values.  ❑ You must use the function session_start() at the beginning of every page that references the session variables.  ❑ You used an if statement, which we did not cover yet. It’s a good idea to take a quick glance at this syntax, just to familiarize yourself with it. 17

18 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, so many people choose to disable this feature in their web browsers. In theory, cookies can be intercepted to gain information such as a person’s IP address and operating system, but cookies are primarily used for storing information only. A few ad campaigns have developed technology to use cookies to track your browsing habits, and many people see this as an invasion of privacy. Also, because cookies are stored in a commonly named directory, anyone with access to someone else’s computer (either via a hack or physical location) can potentially open cookie files and glean information about the owner. Because of these possibilities it’s not a good idea to store any potentially private information on a computer.  Therefore, 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 brightest idea from a Web development standpoint. 18

19 Passing Variables with Cookies  So why do developers use cookies, anyway? The advantage to storing information in a cookie versus a session is longevity. Sessions alone can’t store information for more than the length of time the browser window is open. Like the elusive and mean-spirited video game that loses all high scores once it’s unplugged, once a browser closes, all session information is lost. Cookies, on the other hand, can live on a person’s computer until the developer has decided it’s been long enough and they automatically “die.” It is because of this longevity that cookies are fabulous for storing information such as a visitor’s username or language preferences. These are the pieces of information that users won’t have to retype every time they visit your site, but if for some reason someone did get wind of the information, it wouldn’t be the end of the world. 19

20 Passing Variables with Cookies  To set a cookie, you use the appropriately named setcookie() function. When setting a cookie, you can determine that the following information be set along with it:  ❑ Cookie name (this is mandatory).  ❑ Value of the cookie (such as the person’s username).  ❑ Time in seconds when the cookie will expire. (This time is based on a Unix timestamp, but you can set it using the syntax time()+60*60*24*365, which keeps the cookie alive for a year. This is optional, but if it is not set, the cookie will expire when the browser is closed.)  ❑ Path (the directory where the cookie will be saved—the default is usually sufficient; this is optional).  ❑ Domain (domains that may access this cookie—this is optional).  ❑ Whether a cookie must have a secure connection to be set (defaults to 0; to enable this feature set this to 1).  You make each of these settings as follows: setcookie(‘cookiename’, ‘value’, ‘expiration time’, ‘path’, ‘domain’,‘secure connection’);  Those values will be referenced in the script as $_COOKIE[‘cookiename’]. 20

21 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) doesn’t have to type his username (Joe12345) every time he comes back to visit. To do this, follow these steps:  1. Create your movie1.php file as shown: <?php setcookie(‘username’, ‘Joe’, time()+60); session_start(); //delete this line: $_SESSION[‘username’]=”Joe12345”; $_SESSION[‘authuser’] = 1; ?> Find my Favorite Movie! <?php $myfavmovie = urlencode(“Life of Brian”); echo “ ”; echo “Click here to see information about my favorite movie!”; echo “ ”; ?>  2. Save the file. 21

22 Try It Out: Setting a Cookie  3. Make the following changes to your moviesite.php file:  <?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, you loser!”;  exit();  }  ?>   My Movie Site -   <?php  echo “Welcome to our site, “;  echo $_COOKIE[‘username’];  echo “! ”;  echo “My favorite movie is “;  echo $_REQUEST[‘favmovie’];  echo “ ”;  $movierate=5;  echo “My movie rating for this movie is: “;  echo $movierate;  ?>   4. Save the file. Open a new browser window and open the movie1.php file. Click the link 22

23 How It Works  When using cookies, remember the following:  ❑ Like sessions, cookies must be placed at the very top of the page, before your first line. Otherwise, you get the “headers already sent” error.  ❑ The expire time for the cookie was set to 60 seconds so you could play with and test your cookies without having to wait around for them to kick off. For a normal application storing usernames, it would be logical to set this higher.  ❑ Unlike sessions, cookie information can’t be accessed in the current page where the cookies have been set. You have to move on to the next page for the cookie to be set and accessible to your program. 23

24 Passing Information using Forms  Forms have always been one of the quickest and easiest ways to add interactivity to your web site. A form enables you to ask customers if they like your products and casual visitors for comments. PHP can simplify the task of processing webbased forms substantially, by providing a simple mechanism to read user data submitted through a form into PHP variables. Consider the following sample form:   Enter your message: 

25 Passing Information using Forms  The most critical line in this entire page is the tag:   Enter your message:   As you probably already know, the method attribute of the tag specifies the manner in which form data will be submitted (POST), while the action attribute specifies the name of the server-side script (message.php) that will process the information entered into the form. Here is what message.php looks like:  <?php  // retrieve form data in a variable  $input = $_POST['msg'];  // print it  echo "You said: $input ";  ?>

26 Passing Information using Forms  To see how this works, enter some data into the form (“boo”) and submit it. The form processor should read it and display it back to you (“you said: boo”).  Thus, whenever a form is POST-ed to a PHP script, all variable-value pairs within that form automatically become available for use within the script through a special PHP container variable, $_POST. To then access the value of the form variable, use its name inside the $_POST container, as in the previous script.  If the form uses GET instead of POST, simply retrieve values from $_GET instead of $_POST.  The $_GET and $_POST variables are a special type of animal called an array.


Download ppt "Variables My Movie Site <?php $movierate = 5; echo “My movie rating for this movie is: “; echo $movierate; ?>  The ABOVE line of code would cause the."

Similar presentations


Ads by Google