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

Plug in PHP 100 POWER SOLUTIONS- P49 pptx

5 237 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 5
Dung lượng 276,87 KB

Nội dung

206 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 'NP', 'no problem', 'OMDB', 'over my dead body', 'OMG', 'oh my gosh', 'ONNA', 'oh no, not again', 'OOTO', 'out of the office', 'OT', 'off topic', 'OTT', 'over the top', 'PLS', 'please', 'PM', 'personal message', 'POOF', 'goodbye', 'QL', 'quit laughing', 'QT', 'cutie', 'RBTL ', 'reading between the lines', 'ROLF', 'rolling on the floor laughing', 'SMEM', 'send me an email', 'SMIM', 'send me an instant message', 'SO', 'significant other', 'SOHF', 'sense of humor failure', 'STR8', 'straight', 'SYS', 'see you soon', 'TAH', 'take a hike', 'TBC', 'to be continued', 'TFH', 'thread from hell', 'TGIF', 'thank goodness it\'s Friday', 'THX', 'thanks', 'TM', 'trust me', 'TOM', 'tomorrow', 'TTG', 'time to go', 'TVM', 'thank you very much', 'VM', 'voice mail', 'WC', 'who cares?', 'WFM', 'Works for me', 'WTG', 'way to go', 'WYP', 'what\'s your problem?', 'WYWH', 'wish you were here', 'XOXO', 'hugs and kisses', 'ZZZ', 'sleeping, bored'); $from1 = array(); $from2 = array(); $to1 = array(); $to2 = array(); for ($j = 0 ; $j < count($sms) ; $j += 2) { $from1[$j] = "/\b$sms[$j]\b/"; $to1[$j] = ucfirst($sms[$j + 1]); $from2[$j] = "/\b$sms[$j]\b/i"; $to2[$j] = $sms[$j + 1]; } $text = preg_replace($from1, $to1, $text); return preg_replace($from2, $to2, $text); } CHAPTER 9 MySQL, Sessions, and Cookies 208 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 208 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s T his chapter covers a lot of different topics, ranging from using MySQL to working with PHP sessions, and from basic security measures to handling cookies. Although at first sight these topics may not seem too closely related, they actually are because they’re mostly to do with the processing, storage, and recall of data. The three MySQL plug-ins provide a means of creating a database to hold various details about a user, the facility to add new users, and a plug-in to verify a user against their username and password; while the PHP session plug-ins provide the ability to hold a user’s details across multiple instances of the same or different web pages or PHP programs. Finally, the cookie plug-ins provide similar functionality to the session variables, except that you can set cookies to live for a shorter or longer time than the current session. Along the way you’ll also learn how to roll your own variations of these plug-ins, or how to extract the basic functionality from them to create totally new functions. Add User to DB This plug-in saves a user’s details in a MySQL database. If the data table used doesn’t already exist, it even creates it for you so there’s minimum setup required. So why MySQL? Well, so far in this book I’ve concentrated on using “flat” text files for storing data on the server. This is a quite adequate solution for small applications and utilities, and it saves on having to configure and maintain a database such as MySQL. Indeed, had I gone the database route (or if you’ve been experimenting with the plug-ins), you’d probably have dozens of databases residing within MySQL. Instead, you should only have a collection of text files, which you can simply delete when you don’t want them any more. However, the time comes when the benefits of using a database begin to outweigh those of not doing so, and this plug-in, which allows thousands of users and several fields per user, is such a case. Yes, I could have used a text file and split all records at line breaks, separating out the fields with a special token. But the code required to support such a system would never run as fast or be as flexible as using a database. Figure 9-1 shows this plug-in in action with a user being added twice to the database, the duplicate checking ensuring that the second insertion is ignored. FIGURE 9-1 This plug-in creates a user database and adds users to it. 61 C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 209 C h a p t e r 9 : M y S Q L , S e s s i o n s , a n d C o o k i e s 209 About the Plug-in This plug-in inserts a record into a MySQL database. If the database table does not already exist, it creates it first. Upon success, a value of 1 is returned. Otherwise, -1 is returned if the insert failed, or -2 if the handle already exists. It requires these arguments: • $table The name of the data table • $nmax The maximum length allowed for $name • $hmax The maximum length allowed for $handle • $salt1 Semi-random string to help secure the password • $salt2 A second string to go with $salt1 • $name The user’s full name to add to the database • $handle The user’s username • $pass The user’s password • $email The user’s e-mail address Variables, Arrays, and Functions $query String containing the query to pass to the MySQL database How It Works At the start of this plug-in, the query required to create the table named by $table is put together. For example, assuming that names are allowed 32 characters and handles 16, then the command-line MySQL statements in the query would be as follows: CREATE TABLE IF NOT EXISTS Users ( name VARCHAR(32), handle VARCHAR(16), pass CHAR(32), email VARCHAR(256), INDEX(name(6)), INDEX(handle(6)), INDEX(email(6)) ); As you may know, when the command-line interface is used, MySQL allows you to input a line at a time, and only sends the completed instructions when a final semicolon is encountered. So the preceding is valid MySQL syntax that you could type in. If you were to then enter: DESCRIBE Users; MySQL would show you the format of the table by displaying the following, which shows that the table Users has four fields (also known as columns), with name, handle, and 210 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 210 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s email being variable length character fields of up to 32, 16, or 256 characters respectively, and pass being a fixed length field of exactly 32 characters: + + + + + + + | Field | Type | Null | Key | Default | Extra | + + + + + + + | name | varchar(32) | YES | MUL | NULL | | | handle | varchar(16) | YES | MUL | NULL | | | pass | char(32) | YES | | NULL | | | email | varchar(256) | YES | MUL | NULL | | + + + + + + + This output also shows another thing worth pointing out, which is that all of name, handle, and email have been given indexes by the MySQL INDEX() statement, as shown by the word MUL under the Key heading. This means that, just like using a card index in a library, they will be quick to search. Back to the PHP, though. No semicolon is required (or even allowed) when using the mysql_query() function, so all the preceding commands are run together into a single string stored in $query, which is then passed onto the mysql_query() function. If the call fails, then something has gone very wrong and so the code exits, returning an error message. This will enable you to properly debug your program, but on a production server you may wish to replace the die() function call with error handling of your own. By the way, did you notice the IF NOT EXISTS clause at the start of the query? Using this means that the CREATE TABLE instruction will only ever be called once. Thereafter, the table will already exist and the command will be ignored. It’s a neat way of avoiding having to issue an additional MySQL call to see whether a table exists before creating it. Note that this code assumes you have already created a suitable database and a user to access it (there’s more on this in the following section). So, having ensured that the table named by $table exists, a new query is placed in $query with which to check whether the user already exists in the table. We need to do this to avoid filling it up with duplicates. The query takes the following form (although tablename and handle would be replaced by the actual values): SELECT * FROM tablename WHERE handle='handle'; Again, the preceding is a MySQL command as you would type it into the command line—just leaving off the final semicolon makes it work with mysql_query(), to which the query is passed. Upon success, the mysql_query() function always returns a resource after a SELECT command, which can be used to examine the result of the query. In this case the resource is returned directly to the mysql_num_rows() function, which returns a count representing the number of times the search is found in the database. In this case only a single entry of any handle is allowed, so this value will be either 0 or 1. If the returned value is 1, then an entry already exists and so the function returns with a value of -2 to indicate the fact. Otherwise, it is all right to proceed with inserting the data into the database. First, however, the password needs to be obfuscated to protect all the users should the database get into the wrong hands. This is done by converting the password into a special string called a hash using the md5() function. This is a type of function that only goes one way, and so the input cannot be derived from the output. In addition, to prevent attempts at . database. Figure 9-1 shows this plug- in in action with a user being added twice to the database, the duplicate checking ensuring that the second insertion is ignored. FIGURE 9-1 This plug- in creates a user. utilities, and it saves on having to configure and maintain a database such as MySQL. Indeed, had I gone the database route (or if you’ve been experimenting with the plug- ins), you’d probably have. INDEX(name(6)), INDEX(handle(6)), INDEX(email(6)) ); As you may know, when the command-line interface is used, MySQL allows you to input a line at a time, and only sends the completed instructions

Ngày đăng: 07/07/2014, 08:20

TỪ KHÓA LIÊN QUAN