1. Trang chủ
  2. » Công Nghệ Thông Tin

PHP 5 Recipes A Problem-Solution Approach 2005 phần 8 pptx

49 341 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 49
Dung lượng 352,61 KB

Nội dung

11-10. Creating Dynamic Functions One of the advantages of using PHP functions is that you can create conditional occurrences that allow you to write functions only if strictly necessary. By placing function declarations within conditional statements, you can force PHP to create a function only if a condition has been met. By using this sort of functionality, you can actually create functions dynamically by allowing functions to be born based on a certain condition. Let’s say you want to take in a value from the user, and based on that value you create a function that performs a certain task. For instance, based on what the user enters, you need a function either to add two values, to subtract two values, or to multiply two values. Rather than clutter your code with functions you may not use, you can create the valid function on the fly and call it by just one name. The following example is useful in a site where a user can log in and log out based upon their current status. The Code <?php //sample11_10.php if ($_GET['go'] == "yes"){ //Now, if you are logged in, you want the function to log you out. if ($_GET['loggedin'] == "true"){ //Create a logout function. function dosomething (){ $_GET['loggedin'] = false; echo "You have been successfully logged out.<br />"; } } //Now, if you were not logged in, you want to be able to log in. if ($_GET['loggedin'] == "false"){ //Create a login function. function dosomething (){ $_GET['loggedin'] = true; echo "You have been successfully logged in.<br />"; } } dosomething(); } 11-10 ■ CREATING DYNAMIC FUNCTIONS 449 5092_Ch11_FINAL 8/26/05 9:57 AM Page 449 if ($_GET['loggedin']){ ?><a href="sample11_10.php?go=yes&amp;loggedin=true"> ➥ click here to log out</a><?php } elseif (!$_GET['loggedin']){ ?><a href="sample11_10.php?go=yes&amp;loggedin=false"> ➥ click here to log in</a><?php } ?> If you click to log in, you should get this message and hence be logged in: You have been successfully logged in. click here to log out If, however, you click to log out, you should get the following result: You have been successfully logged out. click here to log in How It Works This particular instance is based on a login principle. If a person is logged in, you want the function to allow them to log out. If, however, the person is logged out, you want to provide them with a means to log in. Through the power of dynamic function creation, you can make the same function call but actually have it perform two (or more) different actions. Summary As you can see, PHP 5 not only supports a myriad of ways to clean up and modularize your code, but it also allows you to manipulate your functions in a wide variety of ways. By using functions to ensure that you are never using redundant code in your applications, you cut back on the time you will spend coding and make your code more applicable both for others to use and for you to clean up should the need arise. PHP 5 supports passing and receiving values by reference as well as by value, and you should always use the defaults if you think the validity of the code calling the function could ever come into question. The ideal way to do things is to evaluate the task at hand and then select the most efficient method for the job. Passing and returning by reference can be an ideal solution for keeping integrity within a variable or group of variables, and passing and return- ing by value is ideal for working with a given data set. PHP also supports many ways to base your code upon dynamic dealings. By using dynamic functions or variable function calls, you can reduce the processing and preloading time of your script by deciding on the fly what calls are necessary and which function declara- tions are important. This allows for a wide range of ingenuity and good, clean coding. 11-10 ■ CREATING DYNAMIC FUNCTIONS450 5092_Ch11_FINAL 8/26/05 9:57 AM Page 450 All in all, you can make a powerful set of PHP code that much more efficient by proper, smart function use, and the amount of time it will save you in the end is well worth the initial investment. Looking Ahead In the next chapter, we will introduce a topic that is quite far from basic, web basics. We will cover a wide variety of important web aspects to show you how to turn a bland, static website into a dynamic, living, breathing entity. No good web application is complete without the upcoming knowledge contained within Chapter 12. 11-10 ■ CREATING DYNAMIC FUNCTIONS 451 5092_Ch11_FINAL 8/26/05 9:57 AM Page 451 5092_Ch11_FINAL 8/26/05 9:57 AM Page 452 Understanding Web Basics In the world of online applications, a wide variety of functionality needs to be on hand for the programmer. Thankfully, PHP 5 has done its best to ensure that anything that makes a system work is readily available to a crafty programmer. Algorithms that track a unique individual on a website or functions that work with headers and querystrings are common pieces of func- tionality that make up the backbone of most well-written online software applications. This chapter shows how to set up and maintain a wide variety of functionality that will come in handy with your everyday applications. Considered kind of a “bells and whistles” chapter, this chapter covers some of the functionality that will no doubt serve you well in applications to come. Sit back, relax, and enjoy the ride through some of PHP 5’s fun and rewarding functionality. Using Cookies Before the advent of sessions, there were cookies. Cookies are files that get written to a tempo- rary file on a user’s computer by a web application. Cookies store information that can be read by the online application, thus authenticating a user as unique. By allowing a web application to identify whether a user is unique, the application can then perform login scripts and other functionality. The problem with cookies is that because they are stored on a user’s computer, they have developed a bad rap as being highly insecure. And because of possible insecurities with cook- ies, users have begun to turn them off in their browser security settings; in fact, users often do not accept cookies. Cookies themselves are not bad or insecure if used correctly by a developer. However, since users have the ability to turn them off (and since the actual cookie must be stored on the user’s computer), most good developers have migrated their code to sessions (which are explained in the “Using Sessions” section). For now, though, cookies are certainly functional enough to get the job done, so the following recipes show how they work. 453 CHAPTER 12 ■ ■ ■ 5092_Ch12_FINAL 8/26/05 9:58 AM Page 453 12-1. Setting Cookies To be able to use cookies and store values in them, you must first set a cookie on a user’s computer. You can use plenty of parameters to take full advantage of a cookie, including the expiration time, path of use, name, value, and so on. By using the different parameters, you can customize the way the cookie works for you. The way to set a cookie is by using the func- tion setcookie(), which has the following prototype: bool setcookie ( string name [, string value [, int expire ➥ [, string path [, string domain [, bool secure]]]]] ) Table 12-1 lists the parameters available to you when creating a cookie using setcookie(). Table 12-1. PHP 5 setcookie() Parameters Parameter Description name The name to set the cookie variable to and hence the name to access it with value The value of the current cookie expire When a cookie will expire (in the form of a Unix timestamp) path The directory where the cookie will be available for use domain The domain at which the cookie will be available secure Whether a cookie can be read on a non-SSL enable script The Code <?php //sample12_1.php //Let's say that the correct login is based on these global user and pass values. //In the real world, this would be taken from the database most likely. $GLOBALS['username'] = "test"; $GLOBALS['password'] = "test"; //Here is an example to set a cookie based on a correct login. function validatelogin ($username, $password){ //Check for a valid match. if (strcmp ($username, $GLOBALS['username']) == 0 ➥ && strcmp ($password, $GLOBALS['password']) == 0){ //If you have a valid match, then you set the cookies. //This will set two cookies, one named cookie_user set to $cookieuser, //and another set to cookie_pass, which contains the value of $password. //When storing passwords, it is a good idea to use something like md5() to //encrypt the stored cookie. setcookie ("cookie_user", $username, time()+60*60*24*30); setcookie ("cookie_pass", md5 ($password), time()+60*60*24*30); return true; } else { 12-1 ■ SETTING COOKIES454 5092_Ch12_FINAL 8/26/05 9:58 AM Page 454 return false; } } //You call the validatelogin() script. if (validatelogin ("test","test")){ echo "Successfully logged in."; } else { echo "Sorry, invalid login."; } ?> How It Works As you can see from this example, login validation is a common use for cookies. In this exam- ple, you compare a username and password that you have passed into the function and then set cookies based on a proper login. In a real-world scenario, the username and password would have likely come from a login form, and the comparable variables would likely have been stored in a database, but the functionality is largely the same. Of note as well is the actual structure of the cookies themselves. These particular cookies are set to be usable anywhere, with no changes depending on SSL or otherwise. You set two of them, one named cookie_user and one named cookie_pass. It is important to keep these names in mind, as this is how you will reference the cookies. You will also note that this script uses the md5() function to encrypt the cookies. Because cookies are stored on a user’s machine, it is important to use some manner of encryption to keep others from going to the cookie file and determining a login. The prototype for md5() is as follows: string md5 ( string str [, bool raw_output] ) 12-2. Reading Cookies Naturally, there would be little use for cookies if you could not read from them, hence allowing you to use them in your applications. Cookies can indeed be read—and quite easily. By using the $_COOKIE superglobal, you can have full access to your cookie for reading and writing to it from your script. The following script allows you to determine if you are properly logged in using a function that returns a true value upon proper validation of login. The Code <?php //sample12_2.php //Let's say the correct login is based on these global user and pass values. //In the real world, this would be taken from the database most likely. $GLOBALS['username'] = "test"; $GLOBALS['password'] = "test"; 12-2 ■ READING COOKIES 455 5092_Ch12_FINAL 8/26/05 9:58 AM Page 455 //Let's assume you already have a valid set of cookies in place. setcookie ("cookie_user", "test", time()+60*60*24*30); setcookie ("cookie_pass", md5 ("test"), time()+60*60*24*30); //Here is an example to set a cookie based on a correct login. function validatelogin (){ //Check for a valid match. if (strcmp ($_COOKIE['cookie_user'], $GLOBALS['username']) == 0 ➥ && strcmp ($_COOKIE['cookie_pass'], md5 ($GLOBALS['password'])) == 0){ return true; } else { return false; } } //You call the validatelogin() script. if (validatelogin ()){ echo "Successfully logged in."; } else { echo "Sorry, invalid login."; } ?> How It Works As you can see, using a set of cookies is rather simple; you can simply access them via the $_COOKIE superglobal. In this case, you compare the (currently) global username and pass- word against the cookies that have been set. If a match is acquired, the unique user is logged in, and the script will remember him until the cookie is expired or until the user physically removes the cookies from their collection. Note also the ease of use with encrypted cookies. If you know how and if a cookie has been encrypted, it is a simple matter of comparing the cookie against an md5()-enabled variable. 12-3. Deleting Cookies Removing cookies is also a simple task. You should note that cookies will disappear by them- selves if you have set them up to do so. Cookies that have not been assigned a time to die will simply be removed when the browser window closes. Sometimes, however, a user will want to be able to clear the cookies on a site. Such functionality typically goes by the name of “logout” and is a staple of a well-programmed user interface. The following code allows a user to log out. 12-3 ■ DELETING COOKIES456 5092_Ch12_FINAL 8/26/05 9:58 AM Page 456 The Code <?php //sample12_3.php //Let's assume you already have a valid set of cookies in place. setcookie ("cookie_user", "test", time()+60*60*24*30); setcookie ("cookie_pass", md5 ("test"), time()+60*60*24*30); //Here is a function that will kill the cookies and hence "log out." function logout (){ //To remove a cookie, you simply set the value of the cookie to blank. setcookie ("cookie_user", "", time()+60*60*24*30); setcookie ("cookie_pass", "", time()+60*60*24*30); } //You call the logout script. logout(); //You can no longer access the cookies. echo $_COOKIE['cookie_user'] . "<br />"; echo "You have successfully logged out."; ?> How It Works As you can see, removing cookies is as easy as setting them and leaving the value blank. It is important to remember that when removing the cookies, the parameters passed to the setcookie() function must be identical to the parameters that were passed to it initially. If the parameter list varies from the original, PHP will assume you are trying to remove a differ- ent cookie, and the removal will not take place. Once a cookie has been removed, your scripts will no longer have access to it, and the physical cookie itself will have been deleted from your collection. 12-4.Writing and Using a Cookie Class Cookies should be as easy to use as sessions are. To cut down on some of the more underused functionality that cookies are capable of and make them nice and easy to manage, you can use the following class, which can manage a cookie with the greatest of ease by making instances of a cookieclass. 12-4 ■ WRITING AND USING A COOKIE CLASS 457 5092_Ch12_FINAL 8/26/05 9:58 AM Page 457 The Code <?php //sample12_4.php //A class to manage a very simple cookie set. class cookieclass { private $cookiename; private $cookievalue; private $cookieexpiry; //A function to construct the class. public function __construct (){ $num_args = func_num_args(); if($num_args > 0){ $args = func_get_args(); $this->cookiename = $args[0]; $this->cookievalue = $args[1]; $this->cookieexpiry = $args[2]; $this->cookieset(); } } //The function to actually set a cookie. public function cookieset (){ try { if ($this->cookiename != "" && $this->cookievalue != "" ➥ && $this->cookieexpiry != ""){ setcookie ($this->cookiename, ➥ $this->cookievalue, time() + $this->cookieexpiry); } else { throw new exception ("Sorry, you must assign a ➥ name and expiry date for the cookie."); } } catch (exception $e){ echo $e->getmessage(); } } //A function to change the value of the cookie. public function change ($newvalue){ $_COOKIE[$this->cookiename] = $newvalue; } 12-4 ■ WRITING AND USING A COOKIE CLASS458 5092_Ch12_FINAL 8/26/05 9:58 AM Page 458 [...]... $myclass->setsomeval ("Hello World!"); $myarray = array(); $myarray[0] = "Hello"; $myarray[1] = "World!"; $myarray = serialize ($myarray); $myarray = urlencode ($myarray); $myclass = serialize ($myclass); $myclass = urlencode ($myclass); ?> Output Current Value< /a> < ?php. .. values in a querystring takes a little more effort than passing regular datatyped values To pass a value such as an array or an object, you must first serialize the value into a format that can be passed easily and effectively PHP contains two handy functions that must be utilized in order for such functionality to become feasible The serialize() function will transform a variable into a format that... imagecolorallocate ($animage, 255 , 0, 0); $white = imagecolorallocate ($animage, 255 , 255 , 255 ); imagefilledrectangle ($animage, 0, 0, 50 0, 50 0, $white); imagestring ($animage, 4, ( (50 0 - (strlen($e->getmessage())➥ * imagefontwidth(4))) / 2), 5, $e->getmessage(), $red); imagejpeg ($animage); header ("Content-type: image/jpeg"); imagedestroy ($animage); } ?> How It Works Although the error handling for... the algorithm to kill off the session variables 483 50 92_Ch12_FINAL 484 8/ 26/ 05 9 : 58 AM Page 484 12- 18 ■ READING ENVIRONMENT AND CONFIGURATION VARIABLES Using Environment and Configuration Variables PHP provides a means to use and verify the configuration settings and environment variables relative to the server space the script is occupying Having access to this feature set can come in handy on many... ($_GET['passedclass']) && isset ($_GET['passedarray'])){ $newclass = new someclass; $newclass = $_GET['passedclass']; $newclass = stripslashes ($newclass); $newclass = unserialize ($newclass); echo "Object: " $newclass->getsomeval() ""; $newarray = array (); $newarray = $_GET['passedarray']; $newarray = stripslashes ($newarray); $newarray = unserialize ($newarray); print_r ($newarray); } ?>... 50 92_Ch12_FINAL 8/ 26/ 05 9 : 58 AM Page 4 75 12-16 ■ SETTING UP HTTP-BASED AUTHENTICATION How It Works As you can see, to make this code work, the object variable and the array variable must both be serialized into a format that can be passed from page to page and then unserialized when received If you were to try to pass the variables along without serializing them, they would lose all stored information... 12.17 481 50 92_Ch12_FINAL 482 8/ 26/ 05 9 : 58 AM Page 482 12-17 ■ SETTING UP COOKIE AUTHENTICATION < ?php //Normally your username and pass would be stored in a database //For this example you will assume that you have already retrieved them $GLOBALS['user'] = "test"; $GLOBALS['pass'] = "test"; //Now, check if you have a valid submission... would rather have the file appear as a download, though? You can use the header() function to force a Save As dialog box to appear for the user to accept a download The following example uses largely the same code as the previous example but instead forces the user to download the file 50 92_Ch12_FINAL 8/ 26/ 05 9 : 58 AM Page 463 12-7 ■ FORCING FILE “SAVE AS” DOWNLOADS The Code < ?php //sample12_7 .php //The... means other than a form You can pass values through the address bar of your browser in PHP by using querystrings Basically, by using special characters and values in the address bar of your browser, you can pass values into a script and then have the script pass more values This provides a convenient method to pass values from page to page and also provides a valuable method for reusing the same page... configuration files temporarily, you can increase the limit enough to allow a script to process much larger files 12- 18 Reading Environment and Configuration Variables PHP 5 makes reading environment and configuration variables easy The $_ENV superglobal is PHP s method for reading a system’s environment variables and has an argument set that is based upon the current environment that is available to . 8/ 26/ 05 9 : 58 AM Page 461 $red = imagecolorallocate ($animage, 255 , 0, 0); $white = imagecolorallocate ($animage, 255 , 255 , 255 ); imagefilledrectangle ($animage, 0, 0, 50 0, 50 0, $white); imagestring. can manage a cookie with the greatest of ease by making instances of a cookieclass. 12-4 ■ WRITING AND USING A COOKIE CLASS 457 50 92_Ch12_FINAL 8/ 26/ 05 9 : 58 AM Page 457 The Code < ?php //sample12_4 .php / /A. allows a user to log out. 12-3 ■ DELETING COOKIES 456 50 92_Ch12_FINAL 8/ 26/ 05 9 : 58 AM Page 456 The Code < ?php //sample12_3 .php //Let's assume you already have a valid set of cookies in place. setcookie

Ngày đăng: 06/08/2014, 08:22