Learning PHP, MySQL & JavaScript With jQuery, CSS & HTML5 4th Edition

This book is for people who wish to learn how to create effective and dynamic websites.

Robin Nixon

806 Pages

100574 Reads



PDF Format

11.3 MB

Java Script

Download PDF format

  • Robin Nixon   
  • 806 Pages   
  • 23 Feb 2015
  • Page - 1

    Robin Nixon Learning PHP, MySQL & Ja vaScript WITH JQUERY, CSS & HTML 5 4t h Ed itio n wi th jQuer y read more..

  • Page - 2

    WEB DEVELOPMENT Learning PHP, MySQL & JavaScript ISBN: 978-1-491-91866-1 US $49.99 CAN $52.99 “ This is a great beginner's book that introduces several crucial web developer languages. It's a quick-paced, easy- to-read, information- packed book that will soon have you creating dynamically driven web- sites, including a basic read more..

  • Page - 3

    Robin Nixon Learning PHP, MySQL & JavaScript With jQuery, CSS & HT ML5 FOURTH EDITION read more..

  • Page - 4

    978-1-491-91866-1 [LSI] Learning PHP, MySQL & JavaScript With jQuery, CSS & HTML5 by Robin Nixon Copyright © 2015 Robin N ixon. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also read more..

  • Page - 5

    For Julie read more..

  • Page - 6

    read more..

  • Page - 7

    Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii 1. Introduction to Dynamic Web Content. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 8

    Questions 33 3. Introduction to PHP. . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 9

    Dynamic Linking in Action 92 Questions read more..

  • Page - 10

    count 132 sort read more..

  • Page - 11

    Creating an Index 186 Querying a MySQL Database read more..

  • Page - 12

    Deleting a Record 244 Displaying the Form read more..

  • Page - 13

    The number and range Input Types 285 Date and Time Pickers read more..

  • Page - 14

    Local Variables 323 The Document Object Model read more..

  • Page - 15

    Creating an Object 357 Accessing Objects read more..

  • Page - 16

    Using IDs 415 Using Classes read more..

  • Page - 17

    Positioning Elements 439 Absolute Positioning read more..

  • Page - 18

    3D Transformations 473 Transitions read more..

  • Page - 19

    Avoiding Library Conflict 505 Selectors read more..

  • Page - 20

    Using jQuery Without Selectors 549 The $.each Method read more..

  • Page - 21

    The measureText Method 581 Drawing Lines read more..

  • Page - 22

    24. HTML5 Audio and Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617 About Codecs read more..

  • Page - 23

    Processing the Image 668 Displaying the Current Profile read more..

  • Page - 24

    read more..

  • Page - 25

    Preface The combination of PHP and MySQL is the most convenient approach to dynamic, database-driven web design, holding its own in the face of challenges from integrated frameworks—such as Ruby on Rails—that are harder to learn. Due to its open source roots (unlike the competing Microsoft .NET Framework), it is free to implement and is therefore an extremely popular option for read more..

  • Page - 26

    Organization of This Book The chapters in this book are written in a specific order, first introducing all of the core technologies it covers and then walking you through their installation on a web development server so that you will be ready to work through the examples. In the first section, you will gain a grounding in the PHP programming language, covering the basics read more..

  • Page - 27

    • Dynamic HTML: The Definitive Reference (9780596527402) by Danny Goodman • PHP in a Nutshell (9780596100674) by Paul Hudson • MySQL in a Nutshell (9780596514334) by Russell Dyer • JavaScript: The Definitive Guide (9780596805524) by David Flanagan • CSS: The Definitive Guide (9780596527334) by Eric A. Myer • HTML5: The Missing Manual (9781449363260) by Matthew read more..

  • Page - 28

    need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require read more..

  • Page - 29

    How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international or local) (707) 829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can read more..

  • Page - 30

    read more..

  • Page - 31

    CHAPTER 1 Introduction to Dynamic Web Content The World Wide Web is a constantly evolving network that has already traveled far beyond its conception in the early 1990s, when it was created to solve a specific prob‐ lem. State-of-the-art experiments at CERN (the European Laboratory for Particle Physics—now best known as the operator of the Large Hadron Collider) were pro‐ read more..

  • Page - 32

    Shopping carts, search engines, and social networks have clearly altered how we use the Web. In this chapter, we’ll take a brief look at the various components that make up the Web, and the software that helps make it a rich and dynamic experience. It is necessary to start using some acronyms more or less right away. I have tried to clearly explain them before read more..

  • Page - 33

    Figure 1-1. The basic client/server request/response sequence Each step in the request and response sequence is as follows: 1. You enter http://server.com into your browser’s address bar. 2. Your browser looks up the IP address for server.com. 3. Your browser issues a request for the home page at server.com. 4. The request crosses the Internet and arrives at the server.com read more..

  • Page - 34

    (DNS) to find its associated IP address and then uses it to communicate with the computer. For dynamic web pages, the procedure is a little more involved, because it may bring both PHP and MySQL into the mix (see Figure 1-2). Figure 1-2. A dynamic client/server request/response sequence 1. You enter http://server.com into your browser’s address bar. 2. Your browser looks up read more..

  • Page - 35

    6. With the home page now in memory, the web server notices that it is a file incor‐ porating PHP scripting and passes the page to the PHP interpreter. 7. The PHP interpreter executes the PHP code. 8. Some of the PHP contains MySQL statements, which the PHP interpreter now passes to the MySQL database engine. 9. The MySQL database returns the results of the statements read more..

  • Page - 36

    just about anything a website would need in order to find and serve up data to brows‐ ers. When PHP allies with MySQL to store and retrieve this data, you have the funda‐ mental parts required for the development of social networking sites and the beginnings of Web 2.0. And when you bring JavaScript and CSS into the mix too, you have a recipe for build‐ ing read more..

  • Page - 37

    information from a third-party website, you can do it all from within the same PHP files in which the HTML itself resides. Using MySQL Of course, there’s not a lot of point to being able to change HTML output dynami‐ cally unless you also have a means to track the changes that users make as they use your website. In the early days of the Web, many sites used read more..

  • Page - 38

    you know only part of the string that you are searching for, return only the nth result, and a lot more. Using PHP, you can make all these calls directly to MySQL without having to run the MySQL program yourself or use its command-line interface. This means you can save the results in arrays for processing and perform multiple lookups, each dependent on the results read more..

  • Page - 39

    Unless you need to specify an exact version of JavaScript, you can normally omit the type="text/javascript" and just use <script> to start the interpretation of the JavaScript. As previously mentioned, JavaScript was originally developed to offer dynamic con‐ trol over the various elements within an HTML document, and that is still its main use. But more and more, read more..

  • Page - 40

    As you’ll learn in Chapter 18, there are many different ways you can lay out CSS rules, and you can also include them directly within tags or save a set of rules to an external file to be loaded in separately. This flexibility not only lets you style your HTML pre‐ cisely, but it can also (for example) provide built-in hover functionality to animate objects as read more..

  • Page - 41

    Applications Including two new rendering technologies: MathML (Math Markup Language) for displaying mathematical formulae and SVG (Scalable Vector Graphics) for creating graphical elements outside of the new <canvas> element. However, MathML and SVG are somewhat specialist, and are so feature-packed they would need a book of their own, so I don’t cover them here. All these read more..

  • Page - 42

    requirements, and the Proxy module, which you can use to serve up often-requested pages from a cache to ease the load on the server. Later in the book, you’ll see how to use some of these modules to enhance the fea‐ tures provided by the three core technologies. About Open Source Whether or not being open source is the reason these technologies are so popular has read more..

  • Page - 43

    Figure 1-3. Gmail uses Ajax to check the availability of usernames The steps involved in this Ajax process would be similar to the following: 1. The server outputs the HTML to create the web form, which asks for the neces‐ sary details, such as username, first name, last name, and email address. 2. At the same time, the server attaches some JavaScript to the read more..

  • Page - 44

    All of this takes place quietly in the background and makes for a comfortable and seamless user experience. Without Ajax, the entire form would have to be submitted to the server, which would then send back HTML, highlighting any mistakes. It would be a workable solution, but nowhere near as tidy or pleasurable as on-the-fly form-field processing. Ajax can be used for a lot read more..

  • Page - 45

    CHAPTER 2 Setting Up a Development Server If you wish to develop Internet applications but don’t have your own development server, you will have to upload every modification you make to a server somewhere else on the Web before you can test it. Even on a fast broadband connection, this can still represent a significant slowdown in development time. On a local computer, read more..

  • Page - 46

    What Is a WAMP, MAMP, or LAMP? WAMP, MAMP, and LAMP are abbreviations for “Windows, Apache, MySQL, and PHP,” “Mac, Apache, MySQL, and PHP,” and “Linux, Apache, MySQL, and PHP.” These abbreviations describe a fully functioning setup used for developing dynamic Internet web pages. WAMPs, MAMPs, and LAMPs come in the form of a package that binds the bundled programs read more..

  • Page - 47

    Figure 2-1. The XAMPP website I recommend that you always download the latest stable release (in this instance, it’s 1.8.3), and there is a direct download link for Windows, OS X, and Linux on the main page. During the lifetime of this edition, some of the screens and options shown in the following walk-through may change. If so, just use your common sense to proceed read more..

  • Page - 48

    Figure 2-2. The initial installation window of the installer Click Next and then uncheck any of the components shown in Figure 2-3 that you don’t need. For example, at the minimum for this book you will want to keep Apache, MySQL, PHP, and PHPMyAdmin checked. The other features are not covered in this book, but you can get more details on all of these, plus read more..

  • Page - 49

    Figure 2-3. Select the components to install Figure 2-4. Choose a folder for the installation Clicking Next brings up the screen in Figure 2-5 with a checkbox already checked (which you can uncheck) for supplying information on adding free installers for related products in a new web browser window or tab. After you choose whether or not to receive this information, read more..

  • Page - 50

    Figure 2-5. Information on related free products is available Having supplied the basic information required by the installer, you will arrive at the screen in Figure 2-6. Setup is ready to start, so click the Next button. Figure 2-6. Accept the default values offered for the ports 20 | Chapter 2: Setting Up a Development Server read more..

  • Page - 51

    When you click the Next button, installation will begin, and you will see the screen in Figure 2-7 while it progresses. During installation, you can click any of the icons to open up a web browser window displaying information on the product shown. The whole process should take only a few minutes on most computers. Figure 2-7. Installation is in progress Once installation read more..

  • Page - 52

    Figure 2-8. Click Finish to complete installation Figure 2-9. The control panel The first thing I recommend you do is click the Config button at the top-right corner to call up the window shown in Figure 2-10. In particular, if they are not already 22 | Chapter 2: Setting Up a Development Server read more..

  • Page - 53

    checked, I recommend you check the Apache and MySQL boxes to ensure they autos‐ tart. Or, you can simply click the Start buttons for Apache and MySQL to have them run for this session only. Figure 2-10. Choose your editor, autostart components and more While on that screen, you may find that you also wish to alter the port settings used by clicking Service and read more..

  • Page - 54

    The control panel is where you can conduct most of the actions required for manag‐ ing XAMPP, including editing and viewing the various configuration files, and look‐ ing at access, error, and other log files, all with a simple interface. For example, in Figure 2-12, the Apache Log button has been clicked, and the folder of log files opened. Figure 2-12. Opening the read more..

  • Page - 55

    Figure 2-13. How the XAMPP home page should look by default The word localhost is used in URLs to specify the local computer, which will also respond to the IP address of, so you can use either method of calling up the document root of your web server. If you chose a server port other than 80 using the control panel (for example 8080), then you read more..

  • Page - 56

    <html> <head> <title>A quick test</title> </head> <body> Hello World! </body> </html> Once you have typed this, save the file into the document root directory previously discussed, using the filename test.htm. If you are using Notepad, make sure that the “Save as type” box is changed from “Text Documents read more..

  • Page - 57

    Installing XAMPP on Mac OS X XAMPP is also available on OS X, and you can download it from http://apache friends.org, as shown previously in Figure 2-1. Double-click the .dmg file once downloaded, and then double-click the installer and follow the same sequence of instructions as for Windows (although you may also be given checkbox options to choose whether to load the core read more..

  • Page - 58

    <title>A quick test</title> </head> <body> Hello World! </body> </html> Installing a LAMP on Linux This book is aimed mostly at PC and Mac users, but its contents will work equally well on a Linux computer. However, there are dozens of popular flavors of Linux, and each of them may require installing a LAMP in a read more..

  • Page - 59

    On a Mac, you already have SSH available. Just select the Applications folder, followed by Utilities, and then launch Terminal. In the terminal window, log in to a server using SSH as follows: ssh mylogin@server.com where server.com is the name of the server you wish to log into and mylogin is the username you will log in under. You will then be prompted for the read more..

  • Page - 60

    Figure 2-15. FireFTP offers full FTP access from within Firefox Using a Program Editor Although a plain-text editor works for editing HTML, PHP, and JavaScript, there have been some tremendous improvements in dedicated program editors, which now incorporate very handy features such as colored syntax highlighting. Today’s program editors are smart and can show you where you read more..

  • Page - 61

    Figure 2-16. Program editors are superior to plain-text editors Again, if you have a different preferred program editor, use that; it’s always a good idea to use programs you’re already familiar with. Using an IDE As good as dedicated program editors can be for your programming productivity, their utility pales into insignificance when compared to integrated development read more..

  • Page - 62

    Figure 2-17. When you’re using an IDE such as phpDesigner, PHP development becomes much quicker and easier When developing with an IDE, you can set breakpoints and then run all (or portions) of your code, which will then stop at the breakpoints and provide you with informa‐ tion about the program’s current state. As an aid to learning programming, the read more..

  • Page - 63

    Table 2-1. A selection of PHP IDEs IDE Download URL Cost Win Mac Lin Eclipse PDT http://eclipse.org/pdt/downloads/ Free Komodo IDE http://activestate.com/Products/komodo_ide $245 NetBeans http://www.netbeans.org Free phpDesigner http://mpsoftware.dk $39 PHPEclipse http://phpeclipse.de Free PhpED http://nusphere.com $119 PHPEdit http://www.phpedit.com $119 You should take the time to install a program read more..

  • Page - 64

    read more..

  • Page - 65

    CHAPTER 3 Introduction to PHP In Chapter 1, I explained that PHP is the language that you use to make the server generate dynamic output—output that is potentially different each time a browser requests a page. In this chapter, you’ll start learning this simple but powerful lan‐ guage; it will be the topic of the following chapters up through Chapter 7. I encourage you read more..

  • Page - 66

    force files ending with .htm or .html to also get parsed by the PHP processor, usually because they want to hide the fact that they are using PHP. Your PHP program is responsible for passing back a clean file suitable for display in a web browser. At its very simplest, a PHP document will output only HTML. To prove this, you can take any normal HTML document read more..

  • Page - 67

    Although it’s not as obvious that the PHP parser is being called, this is a valid, alter‐ native syntax that also usually works, but should be discouraged, as it is incompatible with XML and its use is now deprecated (meaning that it is no longer recommended and could be removed in future versions). If you have only PHP code in a file, you may omit the closing read more..

  • Page - 68

    As well as having all the examples saved by chapter and example number (such as example3-1.php), the provided archive also contains an additional directory called named_examples, in which you’ll find all the examples I suggest you save using a spe‐ cific filename (such as the upcoming Example 3-4, which should be saved as test1.php). The Structure of PHP We’re going to cover read more..

  • Page - 69

    A common error is to use /* and */ to comment out a large section of code that already contains a commented-out section that uses those characters. You can’t nest comments this way; the PHP inter‐ preter won’t know where a comment ends and will display an error message. However, if you use a program editor or IDE with syntax highlighting, this type of error read more..

  • Page - 70

    prehensive commenting) to help you understand your code when you come back to it. It also helps other programmers when they have to maintain your code. Variables There’s a simple metaphor that will help you understand what PHP variables are all about. Just think of them as little (or big) matchboxes! That’s right—matchboxes that you’ve painted over and written names on. read more..

  • Page - 71

    If you are keen to start trying out PHP for yourself, you could enter the examples in this chapter into an IDE (as recommended at the end of Chapter 2) to see instant results, or you could enter the code in Example 3-4 into a program editor and save it to your server’s document root directory (also discussed in Chapter 2) as test1.php. Example 3-4. Your first read more..

  • Page - 72

    To read the contents of the matchbox, you would simply open it and count the beads. In PHP, you would assign the value of $count to another variable or perhaps just echo it to the web browser. Arrays So what are arrays? Well, you can think of them as several matchboxes glued together. For example, let’s say we want to store the player names for a five-person read more..

  • Page - 73

    The reason the previous statement has the number 3, not 4, is because the first ele‐ ment of a PHP array is actually the zeroth element, so the player numbers will there‐ fore be 0 through 4. Two-dimensional arrays There’s a lot more you can do with arrays. For example, instead of being single- dimensional lines of matchboxes, they can be two-dimensional matrixes read more..

  • Page - 74

    Once again, we’ve moved up a step in complexity, but it’s easy to understand if you grasp the basic array syntax. There are three array() constructs nested inside the outer array() construct. To then return the third element in the second row of this array, you would use the following PHP command, which will display an x : echo $oxo[1][2]; Remember that array read more..

  • Page - 75

    Operators Operators are the mathematical, string, comparison, and logical commands such as plus, minus, multiply, and divide. PHP looks a lot like plain arithmetic; for instance, the following statement outputs 8: echo 6 + 2; Before moving on to learn what PHP can do for you, take a moment to learn about the various operators it provides. Arithmetic operators Arithmetic operators read more..

  • Page - 76

    Table 3-2. Assignment operators Operator Example Equivalent to =$j = 15 $j = 15 += $j += 5 $j = $j + 5 -= $j -= 3 $j = $j - 3 *= $j *= 8 $j = $j * 8 /= $j /= 16 $j = $j / 16 .= $j .= $k $j = $j . $k %= $j %= 4 $j = $j % 4 Comparison operators Comparison operators are generally used inside a construct such read more..

  • Page - 77

    Here we have moved the set of instructions for actually going to lunch into a function that we will have to create later called dolunch . The then of the statement is left out, because it is implied and therefore unnecessary. As the previous example shows, you generally use a logical operator to combine the results of two of the comparison operators shown in the read more..

  • Page - 78

    Variable Assignment The syntax to assign a value to a variable is always variable = value. Or, to reassign the value to another variable, it is other variable = variable. There are also a couple of other assignment operators that you will find useful. For example, we’ve already seen $x += 10; which tells the PHP parser to add the value on the right (in this read more..

  • Page - 79

    String concatenation String concatenation uses the period (.) to append one string of characters to another. The simplest way to do this is as follows: echo "You have " . $msgs . " messages."; Assuming that the variable $msgs is set to the value 5 , the output from this line of code will be the following: You have 5 messages. Just as you can add a value to read more..

  • Page - 80

    $text = 'My spelling's atroshus'; // Erroneous syntax To correct this, you can add a backslash directly before the offending quotation mark to tell PHP to treat the character literally and not to interpret it: $text = 'My spelling\'s still atroshus'; And you can perform this trick in almost all situations in which PHP would other‐ wise return an error by trying to read more..

  • Page - 81

    Measuring aircraft building progress by weight. - $author."; ?> PHP also offers a multiline sequence using the <<< operator—commonly referred to as a here-document or heredoc—as a way of specifying a string literal, preserving the line breaks and other whitespace (including indentation) in the text. Its use can be seen in Example 3-8. Example 3-8. read more..

  • Page - 82

    Example 3-9. A multiline string variable assignment <?php $author = "Scott Adams"; $out = <<<_END Normal people believe that if it ain't broke, don't fix it. Engineers believe that if it ain't broke, it doesn't have enough features yet. - $author. _END; ?> The variable $out will then be populated with the contents between the two read more..

  • Page - 83

    12345 and 67890 are multiplied together, returning a result of 838102050, which is then placed in the variable $number , as shown in Example 3-10. Example 3-10. Automatic conversion from a number to a string <?php $number = 12345 * 67890; echo substr($number, 3, 1); ?> At the point of the assignment, $number is a numeric variable. But on the second line, read more..

  • Page - 84

    $directory = ROOT_LOCATION; Now, whenever you need to run your PHP code on a different server with a different folder configuration, you have only a single line of code to change. The main two things you have to remember about constants are that they must not be prefaced with a $ (as with regular variables), and that you can define them only using the define read more..

  • Page - 85

    echo "This is line " . __LINE__ . " of file " . __FILE__; This causes the current program line in the current file (including the path) being executed to be output to the web browser. The Difference Between the echo and print Commands So far, you have seen the echo command used in a number of different ways to output text from the server to your browser. In read more..

  • Page - 86

    passed parameters to make them perform differently. They can also return values to the calling code. To create a function, declare it in the manner shown in Example 3-12. Example 3-12. A simple function declaration <?php function longdate($timestamp) { return date("l F jS Y", $timestamp); } ?> This function takes a Unix timestamp (an integer number read more..

  • Page - 87

    Local variables Local variables are variables that are created within, and can be accessed only by, a function. They are generally temporary variables that are used to store partially pro‐ cessed results prior to the function’s return. One set of local variables is the list of arguments to a function. In the previous sec‐ tion, we defined a function that accepted a read more..

  • Page - 88

    The reason for this is that, by default, variables created within a function are local to that function, and variables created outside of any functions can be accessed only by nonfunction code. Some ways to repair Example 3-14 appear in Example 3-15 and Example 3-16. Example 3-15. Rewriting to refer to $temp within its local scope fixes the problem <?php $temp read more..

  • Page - 89

    Global variables There are cases when you need a variable to have global scope, because you want all your code to be able to access it. Also, some data may be large and complex, and you don’t want to keep passing it as arguments to functions. To declare a variable as having global scope, use the keyword global . Let’s assume that you have a way of logging read more..

  • Page - 90

    Example 3-17. A function using a static variable <?php function test() { static $count = 0; echo $count; $count++; } ?> Here the very first line of function test creates a static variable called $count and ini‐ tializes it to a value of 0 . The next line outputs the variable’s value; the final one incre‐ ments it. The read more..

  • Page - 91

    Superglobal name Contents $_GET Variables passed to the current script via the HTTP Get method. $_POST Variables passed to the current script via the HTTP Post method. $_FILES Items uploaded to the current script via the HTTP Post method. $_COOKIE Variables passed to the current script via HTTP cookies. $_SESSION Session read more..

  • Page - 92

    This chapter has provided you with a solid background in using PHP. In Chapter 4, we’ll start using what you’ve learned to build expressions and control program flow— in other words, do some actual programming. But before moving on, I recommend that you test yourself with some (if not all) of the following questions to ensure that you have fully digested the contents read more..

  • Page - 93

    CHAPTER 4 Expressions and Control Flow in PHP The previous chapter introduced several topics in passing that this chapter covers more fully, such as making choices (branching) and creating complex expressions. In the previous chapter, I wanted to focus on the most basic syntax and operations in PHP, but I couldn’t avoid touching on more-advanced topics. Now I can fill in read more..

  • Page - 94

    (You can combine Boolean operations using operators such as AND , OR , and XOR , which are covered later in this chapter.) Note that I am using uppercase letters for the names TRUE and FALSE . This is because they are predefined constants in PHP. You can also use the lowercase versions, if you prefer, as they are also predefined. In fact, the lowercase versions are more read more..

  • Page - 95

    constant FALSE is defined as NULL , or nothing. To verify this for yourself, you could enter the code in Example 4-2. Example 4-2. Outputting the values of TRUE and FALSE <?php // test2.php echo "a: [" . TRUE . "]<br>"; echo "b: [" . FALSE . "]<br>"; ?> that outputs the following: a: [1] b: [] By the way, in read more..

  • Page - 96

    In conjunction with operators, it’s possible to create more-complex expressions that evaluate to useful results. When you combine assignment or control-flow constructs with expressions, the result is a statement. Example 4-4 shows one of each. The first assigns the result of the expression 366 - $day_number to the variable $days_to_new_year , and the second outputs a friendly read more..

  • Page - 97

    • Binary operators, which represent the bulk of PHP operators, including addition, subtraction, multiplication, and division. • One ternary operator, which takes the form ? x : y . It’s a terse, single-line if statement that chooses between two expressions, depending on the result of a third one. Operator Precedence If all operators had the same precedence, they would be read more..

  • Page - 98

    Example 4-8. Three expressions showing implied parentheses 1 + (2 * 3) - (4 * 5) 2 - (4 * 5 * 3) + 1 5 + 2 - 4 + (1 * 3) Clearly, PHP must evaluate the subexpressions within parentheses first to derive the semi-completed expressions in Example 4-9. Example 4-9. After evaluating the subexpressions in parentheses 1 + (6) - (20) 2 - (60) + 1 5 + 2 - 4 + read more..

  • Page - 99

    Operator(s) Type & Bitwise (and references) ^ Bitwise | Bitwise && Logical || Logical ? : Ternary = += -= *= /= .= %= &= != ^= <<= >>= Assignment and Logical xor Logical or Logical Associativity We’ve been looking at processing expressions from left to right, except where opera‐ tor precedence is in effect. But some operators require read more..

  • Page - 100

    Operator Description Associativity - Subtraction and negation Left * Multiplication Left / Division Left % Modulus Left . String concatenation Left << >> & ^ | Bitwise Left ?: Ternary Left || && and or xor Logical Left , Separator Left For example, let’s take a look at the assignment operator in Example 4-11, where three variables are all set to the value read more..

  • Page - 101

    Example 4-12. Assigning a value and testing for equality <?php $month = "March"; if ($month == "March") echo "It's springtime"; ?> As you see, by returning either TRUE or FALSE , the equality operator enables you to test for conditions using, for example, an if statement. But that’s not the whole story, because PHP is a loosely typed read more..

  • Page - 102

    Example 4-14. The inequality and not-identical operators <?php $a = "1000"; $b = "+1000"; if ($a != $b) echo "1"; if ($a !== $b) echo "2"; ?> And, as you might expect, the first if statement does not output the number 1 , because the code is asking whether $a and $b are not equal to each other numerically. read more..

  • Page - 103

    Table 4-4. The logical operators Logical operator Description AND TRUE if both operands are TRUE OR TRUE if either operand is TRUE XOR TRUE if one of the two operands is TRUE NOT TRUE if the operand is FALSE , or FALSE if the operand is TRUE You can see these operators used in Example 4-16. Note that the ! symbol is read more..

  • Page - 104

    If you need getnext to be called at each if statement, you could rewrite the code as has been done in Example 4-18. Example 4-18. The “if...OR” statement modified to ensure calling of getnext <?php $gn = getnext(); if ($finished == 1 OR $gn == 1) exit; ?> In this case, the code in function getnext will be executed and the value returned read more..

  • Page - 105

    The if Statement One way of thinking about program flow is to imagine it as a single-lane highway that you are driving along. It’s pretty much a straight line, but now and then you encounter various signs telling you where to go. In the case of an if statement, you could imagine coming across a detour sign that you have to follow if a certain condition is read more..

  • Page - 106

    Example 4-19. An if statement with curly braces <?php if ($bank_balance < 100) { $money = 1000; $bank_balance += $money; } ?> In this example, you are checking your balance to see whether it is less than 100 dol‐ lars (or whatever your currency is). If so, you pay yourself 1,000 dollars and then add it to the read more..

  • Page - 107

    Figure 4-2. The highway now has an if detour and an else detour Example 4-20. An if...else statement with curly braces <?php if ($bank_balance < 100) { $money = 1000; $bank_balance += $money; } else { $savings += 50; $bank_balance -= 50; } ?> In this example, now that read more..

  • Page - 108

    As with if statements, if your else has only one conditional statement, you can opt to leave out the curly braces. (Curly braces are always recommended, though. First, they make the code easier to understand. Second, they let you easily add more state‐ ments to the branch later.) The elseif Statement There are also times when you want a number of different possibilities read more..

  • Page - 109

    Figure 4-3. The highway with if, elseif, and else detours An else statement closes either an if...else or an if...elseif...else statement. You can leave out a final else if it is not required, but you cannot have one before an elseif ; neither can you have an elseif before an if statement. You may have as many elseif statements as you like. But as the read more..

  • Page - 110

    About, News, Login, and Links, and we set the variable $page to one of these, accord‐ ing to the user’s input. If we write the code for this using if...elseif...else , it might look like Example 4-22. Example 4-22. A multiple-line if...elseif...statement <?php if ($page == "Home") echo "You selected Home"; elseif ($page == "About") read more..

  • Page - 111

    With switch statements, you do not use curly braces inside case commands. Instead, they commence with a colon and end with the break statement. The entire list of cases in the switch state‐ ment is enclosed in a set of curly braces, though. Breaking out If you wish to break out of the switch statement because a condition has been fulfil‐ led, use the break read more..

  • Page - 112

    Example 4-25. Alternate switch statement syntax <?php switch ($page): case "Home": echo "You selected Home"; break; // etc... case "Links": echo "You selected Links"; break; endswitch; ?> The ? Operator One way of avoiding the verbosity of if and read more..

  • Page - 113

    Here $enough will be assigned the value TRUE only when there is more than a gallon of fuel; otherwise, it is assigned the value FALSE . If you find the ? operator confusing, you are free to stick to if statements, but you should be familiar with it, because you’ll see it in other people’s code. It can be hard to read, because it often mixes multiple read more..

  • Page - 114

    Figure 4-4. Imagining a loop as part of a program highway layout while Loops Let’s turn the digital car dashboard in Example 4-26 into a loop that continuously checks the fuel level as you drive, using a while loop (Example 4-28). Example 4-28. A while loop <?php $fuel = 10; while ($fuel > 1) { // Keep driving ... echo read more..

  • Page - 115

    Example 4-29. A while loop to print the 12 times table <?php $count = 1; while ($count <= 12) { echo "$count times 12 is " . $count * 12 . "<br>"; ++$count; } ?> Here the variable $count is initialized to a value of 1, and then a while loop is started with the comparative expression $count <= 12 . This loop read more..

  • Page - 116

    now happens is that PHP encounters the variable $count at the start of each iteration of the loop and, noticing that it is prefaced with the increment operator, first incre‐ ments the variable and only then compares it to the value 12 . You can therefore see that $count now has to be initialized to 0 , not 1 , because it is incremented as soon as the loop is read more..

  • Page - 117

    Example 4-33 shows how to write the multiplication table program with a for loop. Example 4-33. Outputting the times table for 12 from a for loop <?php for ($count = 1 ; $count <= 12 ; ++$count) echo "$count times 12 is " . $count * 12 . "<br>"; ?> See how the code has been reduced to a single for statement containing a read more..

  • Page - 118

    form of the for statement even lets you perform multiple operations in each of the three parameters: for ($i = 1, $j = 1 ; $i + $j < 10 ; $i++ , $j++) { // ... } That’s complicated and not recommended for first-time users. The key is to distin‐ guish commas from semicolons. The three parameters must be separated by semico‐ lons. Within each parameter, read more..

  • Page - 119

    fclose($fp); ?> This is the most complicated piece of code that you have seen so far, but you’re ready for it. We’ll look into the file-handling commands in a later chapter, but for now all you need to know is that the first line opens the file text.txt for writing in binary mode, and then returns a pointer to the file in the variable $fp , which is read more..

  • Page - 120

    Example 4-36. Trapping division-by-zero errors using continue <?php $j = 10; while ($j > -10) { $j--; if ($j == 0) continue; echo (10 / $j) . "<br>"; } ?> For all values of $j between 10 and –10 , with the exception of 0 , the result of calculat‐ ing 10 divided by $j is displayed. But for the read more..

  • Page - 121

    Otherwise, only the variable $a would have been cast to an integer—a pointless exer‐ cise, as the division by $b would still have returned a floating-point number. You can explicitly cast to the types shown in Table 4-6, but you can usually avoid having to use a cast by calling one of PHP’s built-in functions. For example, to obtain an integer value, you could read more..

  • Page - 122

    chapters), you can split up your website into sensible sections of PHP code, each one self-contained, and therefore treat yourself to a much easier future, developing each new feature and maintaining old ones. Dynamic Linking in Action One of the more popular PHP-driven applications on the Web today is the blogging platform WordPress (see Figure 4-5). As a blogger or a blog read more..

  • Page - 123

    This chapter has covered quite a lot of ground, and by now you should be able to put together your own small PHP programs. But before you do, and before proceeding with the following chapter on functions and objects, you may wish to test your new knowledge on the following questions. Questions 1. What actual underlying values are represented by TRUE and FALSE ? 2. What read more..

  • Page - 124

    read more..

  • Page - 125

    CHAPTER 5 PHP Functions and Objects The basic requirements of any programming language include somewhere to store data, a means of directing program flow, and a few bits and pieces such as expression evaluation, file management, and text output. PHP has all these, plus tools like else and elseif to make life easier. But even with all these in our toolkit, programming can be read more..

  • Page - 126

    PHP Functions PHP comes with hundreds of ready-made, built-in functions, making it a very rich language. To use a function, call it by name. For example, you can see the print func‐ tion in action here: print("print is a pseudo-function"); The parentheses tell PHP that you’re referring to a function. Otherwise, it thinks you’re referring to a constant. You may see read more..

  • Page - 127

    Figure 5-1. The output of PHP’s built-in phpinfo function Some of the built-in functions that use one or more arguments appear in Example 5-1. Example 5-1. Three string functions <?php echo strrev(" .dlrow olleH"); // Reverse string echo str_repeat("Hip ", 2); // Repeat string echo strtoupper("hooray!"); // String to uppercase ?> This read more..

  • Page - 128

    Defining a Function The general syntax for a function is as follows: function function_name([parameter [, ...]]) { // Statements } I’ll explain all the square brackets, in case you find them confusing. The first line of the syntax indicates the following: • A definition starts with the word function . • A name follows, which must start with a letter or underscore, read more..

  • Page - 129

    echo $ucfixed; The output is as follows: Any # of letters and punctuation you want Now we can do our first bit of program design: to get a word with its initial letter capitalized, we call strtolower on a string first, and then ucfirst . The way to do this is to nest a call to strtolower within ucfirst . Let’s see why, because it’s important to understand read more..

  • Page - 130

    return $n1 . " " . $n2 . " " . $n3; } ?> You may well find yourself writing this type of code, because users often leave their Caps Lock key on, accidentally insert capital letters in the wrong places, and even for‐ get capitals altogether. The output from this example is shown here: William Henry Gates Returning an Array We just saw a function read more..

  • Page - 131

    Passing by reference was deprecated in PHP 5.3.0 and was removed in PHP 5.4.0. You should therefore not use this feature other than on legacy websites, and even there you are recommended to rewrite code that passes by reference, because it will halt with a fatal error on newer versions of PHP. In case you are called upon to maintain legacy code you need to know how read more..

  • Page - 132

    fix_names($a1, $a2, $a3); echo $a1 . " " . $a2 . " " . $a3; function fix_names(&$n1, &$n2, &$n3) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucfirst(strtolower($n3)); } ?> Rather than passing strings directly to the function, you first assign them to variables and print them out to see their read more..

  • Page - 133

    function fix_names() { global $a1; $a1 = ucfirst(strtolower($a1)); global $a2; $a2 = ucfirst(strtolower($a2)); global $a3; $a3 = ucfirst(strtolower($a3)); } ?> Now you don’t have to pass parameters to the function, and it doesn’t have to accept them. Once declared, these variables remain global and available to the rest of your program, read more..

  • Page - 134

    The include Statement Using include , you can tell PHP to fetch a particular file and load all its contents. It’s as if you pasted the included file into the current file at the insertion point. Example 5-6 shows how you would include a file called library.php. Example 5-6. Including a PHP file <?php include "library.php"; // Your code goes here read more..

  • Page - 135

    Using require and require_once A potential problem with include and include_once is that PHP will only attempt to include the requested file. Program execution continues even if the file is not found. When it is absolutely essential to include a file, require it. For the same reasons I gave for using include_once , I recommend that you generally stick with require_once read more..

  • Page - 136

    PHP Objects In much the same way that functions represent a huge increase in programming power over the early days of computing, where sometimes the best program naviga‐ tion available was a very basic GOTO or GOSUB statement, object-oriented programming (OOP) takes the use of functions to a whole new level. Once you get the hang of condensing reusable bits of code into read more..

  • Page - 137

    This approach makes debugging easy: you have to fix faulty code only within a class. Additionally, when you want to upgrade a program, if you have used proper encapsu‐ lation and maintained the same interface, you can simply develop new replacement classes, debug them fully, and then swap them in for the old ones. If they don’t work, you can swap the old ones back read more..

  • Page - 138

    Example 5-10. Declaring a class and examining an object <?php $object = new User; print_r($object); class User { public $name, $password; function save_user() { echo "Save User code goes here"; } } ?> Here I have also used an invaluable function called print_r . It asks PHP to display information read more..

  • Page - 139

    Accessing Objects Let’s add a few lines to Example 5-10 and check the results. Example 5-11 extends the previous code by setting object properties and calling a method. Example 5-11. Creating and interacting with an object <?php $object = new User; print_r($object); echo "<br>"; $object->name = "Joe"; $object->password = read more..

  • Page - 140

    [password] => mypass ) Save User code goes here Again, print_r shows its utility by providing the contents of $object before and after property assignment. From now on, I’ll omit print_r statements, but if you are working along with this book on your development server, you can put some in to see exactly what is happening. You can also see that the code in the read more..

  • Page - 141

    just to the name property of $object2 —or so we might think. But this code outputs the following: object1 name = Amy object2 name = Amy What has happened? Both $object1 and $object2 refer to the same object, so chang‐ ing the name property of $object2 to Amy also sets that property for $object1 . To avoid this confusion, you can use the clone operator, read more..

  • Page - 142

    { // Constructor statements go here public $username = "Guest"; } } ?> However, PHP 5 provides a more logical approach to naming the constructor, which is to use the function name __construct (that is, construct preceded by two under‐ score characters), as in Example 5-15. Example 5-15. Creating a constructor method read more..

  • Page - 143

    You also have access to a special variable called $this , which can be used to access the current object’s properties. To see how it works, take a look at Example 5-17, which contains a different method from the User class definition called get_password . Example 5-17. Using the variable $this in a method <?php class User { public $name, read more..

  • Page - 144

    } ?> Note how we call the class itself, along with the static method, using a double colon (also known as the scope resolution operator), not -> . Static functions are useful for performing actions relating to the class itself, but not to specific instances of the class. You can see another example of a static method in Example 5-21. If you try to access read more..

  • Page - 145

    Example 5-20. Valid and invalid property declarations <?php class Test { public $name = "Paul Smith"; // Valid public $age = 42; // Valid public $time = time(); // Invalid - calls a function public $score = $level * 2; // Invalid - uses an expression } ?> Declaring read more..

  • Page - 146

    public These properties are the default when you are declaring a variable using the var or public keywords, or when a variable is implicitly declared the first time it is used. The keywords var and public are interchangeable because, although deprecated, var is retained for compatibility with previous versions of PHP. Methods are assumed to be public by default. protected read more..

  • Page - 147

    been registered. These facts and operations apply separately to each user and there‐ fore use instance-specific properties and methods. But occasionally you’ll want to maintain data about a whole class. For instance, to report how many users are registered, you will store a variable that applies to the whole User class. PHP provides static properties and methods for such read more..

  • Page - 148

    Inheritance Once you have written a class, you can derive subclasses from it. This can save lots of painstaking code rewriting: you can take a class similar to the one you need to write, extend it to a subclass, and just modify the parts that are different. You achieve this using the extends operator. In Example 5-24, the class Subscriber is declared a subclass of read more..

  • Page - 149

    Name: Fred Pass: pword Phone: 012 345 6789 Email: fred@bloggs.com The parent operator If you write a method in a subclass with the same name as one in its parent class, its statements will override those of the parent class. Sometimes this is not the behavior you want, and you need to access the parent’s method. To do this, you can use the parent operator, as read more..

  • Page - 150

    If you wish to ensure that your code calls a method from the current class, you can use the self keyword, like this: self::method(); Subclass constructors When you extend a class and declare your own constructor, you should be aware that PHP will not automatically call the constructor method of the parent class. If you want to be certain that all initialization code is read more..

  • Page - 151

    Tigers have... Fur: TRUE Stripes: TRUE Final methods When you wish to prevent a subclass from overriding a superclass method, you can use the final keyword. Example 5-27 shows how. Example 5-27. Creating a final method <?php class User { final function copyright() { echo "This class was written by Joe Smith"; } } ?> read more..

  • Page - 152

    read more..

  • Page - 153

    CHAPTER 6 PHP Arrays In Chapter 3, I gave a very brief introduction to PHP’s arrays—just enough for a little taste of their power. In this chapter, I’ll show you many more things that you can do with arrays, some of which—if you have ever used a strongly typed language such as C—may surprise you with their elegance and simplicity. Arrays are an example of what read more..

  • Page - 154

    Example 6-1. Adding items to an array <?php $paper[] = "Copier"; $paper[] = "Inkjet"; $paper[] = "Laser"; $paper[] = "Photo"; print_r($paper); ?> In this example, each time you assign a value to the array $paper , the first empty location within that array is used to store the value, and a pointer internal to PHP is read more..

  • Page - 155

    Example 6-3. Adding items to an array and retrieving them <?php $paper[] = "Copier"; $paper[] = "Inkjet"; $paper[] = "Laser"; $paper[] = "Photo"; for ($j = 0 ; $j < 4 ; ++$j) echo "$j: $paper[$j]<br>"; ?> This example prints out the following: 0: Copier 1: Inkjet 2: Laser 3: Photo So far, you’ve read more..

  • Page - 156

    Printer . The names (copier, inkjet , and so on) are called indexes or keys, and the items assigned to them (such as Laser Printer ) are called values. This very powerful feature of PHP is often used when you are extracting information from XML and HTML. For example, an HTML parser such as those used by a search engine could place all the elements of a web page read more..

  • Page - 157

    and not to a variable. The index is then inextricably linked with that value, unless it is assigned a new value. The echo command therefore prints out this: p2 element: Inkjet Printer You can verify that $p1 and $p2 are different types of array, because both of the fol‐ lowing commands, when appended to the code, will cause an Undefined index or Undefined offset read more..

  • Page - 158

    Example 6-7. Walking through an associative array using foreach...as <?php $paper = array('copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"); read more..

  • Page - 159

    Example 6-9. Using the list function <?php list($a, $b) = array('Alice', 'Bob'); echo "a=$a b=$b"; ?> The output from this code is as follows: a=Alice b=Bob So you can take your pick when walking through arrays. Use foreach...as to create a loop that extracts values to the variable following the as , or use the each function and create your own read more..

  • Page - 160

    'clips' => "Paperclips" ) ); echo "<pre>"; foreach($products as $section => $items) foreach($items as $key => $value) echo "$section:\t$key\t($value)<br>"; echo "</pre>"; ?> To make things clearer now that the code is starting to grow, I’ve renamed some of the elements. For read more..

  • Page - 161

    echo $products['misc']['glue']; This outputs the value Adhesives . You can also create numeric multidimensional arrays that are accessed directly by indexes rather than by alphanumeric identifiers. Example 6-11 creates the board for a chess game with the pieces in their starting positions. Example 6-11. Creating a multidimensional numeric array <?php $chessboard = array( read more..

  • Page - 162

    P P P P P P P P R N B Q K B N R You can also directly access any element within this array by using square brackets: echo $chessboard[7][3]; This statement outputs the uppercase letter Q , the eighth element down and the fourth along (remembering that array indexes start at 0, not 1). Using Array Functions You’ve already seen the list and each functions, but read more..

  • Page - 163

    sort Sorting is so common that PHP provides a built-in function. In its simplest form, you would use it like this: sort($fred); Unlike some other functions, sort will act directly on the supplied array rather than returning a new array of sorted elements. Instead, it returns TRUE on success and FALSE on error and also supports a few flags, but the main two that you read more..

  • Page - 164

    [3] => sentence [4] => with [5] => seven [6] => words ) The first parameter, the delimiter, need not be a space or even a single character. Example 6-13 shows a slight variation. Example 6-13. Exploding a string delimited with *** into an array <?php $temp = explode('***', "A***sentence***with***asterisks"); print_r($temp); ?> The read more..

  • Page - 165

    extract($_GET, EXTR_PREFIX_ALL, 'fromget'); In this case, all the new variables will begin with the given prefix string followed by an underscore, so $q will become $fromget_q . I strongly recommend that you use this version of the function when handling the $_GET and $_POST arrays, or any other array whose keys could be controlled by the user, because malicious users could read more..

  • Page - 166

    Example 6-15. Using compact to help with debugging <?php $j = 23; $temp = "Hello"; $address = "1 Old Street"; $age = 61; print_r(compact(explode(' ', 'j temp address age'))); ?> This works by using the explode function to extract all the words from the string into an array, which is then passed to read more..

  • Page - 167

    Questions 1. What is the difference between a numeric and an associative array? 2. What is the main benefit of the array keyword? 3. What is the difference between foreach and each ? 4. How can you create a multidimensional array? 5. How can you determine the number of elements in an array? 6. What is the purpose of the explode function? 7. How can you set read more..

  • Page - 168

    read more..

  • Page - 169

    CHAPTER 7 Practical PHP Previous chapters went over the elements of the PHP language. This chapter builds on your new programming skills to teach you some common but important practical tasks. You will learn the best ways to manage string handling to achieve clear and concise code that displays in web browsers exactly how you want it to, including advanced date and time read more..

  • Page - 170

    Specifier Conversion action on argument arg Example (for an arg of 123) e Display arg using scientific notation 1.23000e+2 f Display arg as floating point 123.000000 o Display arg as an octal integer 173 s Display arg as a string 123 u Display arg as an unsigned decimal 123 x Display arg in lowercase hexadecimal 7b X Display arg read more..

  • Page - 171

    are correctly stored internally, but displayed with only two digits of precision, you can insert the string ".2" between the % symbol and the conversion specifier: printf("The result is: $%.2f", 123.42 / 12); The output from this command is as follows: The result is $10.29 But you actually have even more control than that, because you can also specify whether to pad read more..

  • Page - 172

    the previous example, this is 15 characters. If the output is already equal to or greater than the padding length, then this argument is ignored. • The leftmost parameter allowed after the % symbol is a 0 , which is ignored unless a padding value has been set, in which case the output is padded with zeros instead of spaces. If a pad character other than zero or read more..

  • Page - 173

    Note how for purposes of layout in a web page, I’ve used the <pre> HTML tag to pre‐ serve all the spaces and the \n newline character after each of the lines to be dis‐ played. The output from this example is as follows: [Rasmus] [ Rasmus] [Rasmus ] [000000Rasmus] [######Rasmus] [ Rasmus L] [Rasmus Lerdo] [Rasmus Ler@@] When you are read more..

  • Page - 174

    echo time(); Because the value is stored as seconds, to obtain the timestamp for this time next week, you would use the following, which adds 7 days times 24 hours times 60 minutes times 60 seconds to the returned value: echo time() + 7 * 24 * 60 * 60; If you wish to create a timestamp for a given date, you can use the mktime function. Its output is the read more..

  • Page - 175

    The parameter $format should be a string containing formatting specifiers as detailed in Table 7-4, and $timestamp should be a Unix timestamp. For the complete list of specifiers, please see http://php.net/manual/en/function.date.php. The following com‐ mand will output the current date and time in the format "Thursday July 6th, 2017 - 1:38pm" : echo date("l F jS, Y - read more..

  • Page - 176

    Format Description Returned value i Minutes, with leading zeros 00 to 59 s Seconds, with leading zeros 00 to 59 Date Constants There are a number of useful constants that you can use with the date command to return the date in specific formats. For example, date(DATE_RSS) returns the current date and time in the valid format for an RSS feed. Some of the read more..

  • Page - 177

    $year = 2018; // 2018 if (checkdate($month, $day, $year)) echo "Date is valid"; else echo "Date is invalid"; ?> File Handling Powerful as it is, MySQL is not the only (or necessarily the best) way to store all data on a web server. Sometimes it can be quicker and more convenient to directly access files on the hard disk. Cases in which you read more..

  • Page - 178

    When you run this in a browser, all being well, you will receive the message File 'testfile.txt' written successfully . If you receive an error message, your hard disk may be full or, more likely, you may not have permission to create or write to the file, in which case you should modify the attributes of the destination folder accord‐ ing to your operating system. read more..

  • Page - 179

    Table 7-5. The supported fopen modes Mode Action Description 'r' Read from file start Open for reading only; place the file pointer at the beginning of the file. Return FALSE if the file doesn’t already exist. 'r+' Read from file start and allow writing Open for reading and writing; place the file pointer at the read more..

  • Page - 180

    echo $text; ?> I’ve requested three characters in the fread call, so the program displays this: Lin The fread function is commonly used with binary data. But if you use it on text data that spans more than one line, remember to count newline characters. Copying Files Let’s try out the PHP copy function to create a clone of testfile.txt. Type Example 7-7 and read more..

  • Page - 181

    Deleting a File Deleting a file is just a matter of using the unlink function to remove it from the file system, as in Example 7-10. Example 7-10. Deleting a file <?php // deletefile.php if (!unlink('testfile2.new')) echo "Could not delete file"; else echo "File 'testfile2.new' successfully deleted"; ?> Whenever you access files on your hard disk directly, you read more..

  • Page - 182

    echo "File 'testfile.txt' successfully updated"; ?> This program opens testfile.txt for both reading and writing by setting the mode with 'r+' , which puts the file pointer right at the start. It then uses the fgets function to read in a single line from the file (up to the first line feed). After that, the fseek func‐ tion is called to move the file read more..

  • Page - 183

    flock function. This function queues up all other requests to access a file until your program releases the lock. So, whenever your programs use write access on files that may be accessed concurrently by multiple users, you should also add file locking to them, as in Example 7-12, which is an updated version of Example 7-11. Example 7-12. Updating a file with file read more..

  • Page - 184

    Something else you must consider is that flock is what is known as an advisory lock. This means that it locks out only other processes that call the function. If you have any code that goes right in and modifies files without implementing flock file lock‐ ing, it will always override the locking and could wreak havoc on your files. By the way, implementing file read more..

  • Page - 185

    Figure 7-1. The O’Reilly home page grabbed with file_get_contents Uploading Files Uploading files to a web server is a subject that seems daunting to many people, but it actually couldn’t be much easier. All you need to do to upload a file from a form is choose a special type of encoding called multipart/form-data, and your browser will handle the rest. To see read more..

  • Page - 186

    echo "</body></html>"; ?> Let’s examine this program a section at a time. The first line of the multiline echo statement starts an HTML document, displays the title, and then starts the docu‐ ment’s body. Next we come to the form that selects the Post method of form submission, sets the target for posted data to the program upload.php (the read more..

  • Page - 187

    Figure 7-2. Uploading an image as form data Using $_FILES Five things are stored in the $_FILES array when a file is uploaded, as shown in Table 7-6 (where file is the file upload field name supplied by the submitting form). Table 7-6. The contents of the $_FILES array Array element Contents $_FILES[' file']['name'] The name of the uploaded file (e.g., read more..

  • Page - 188

    Validation I hope it now goes without saying (although I’ll do so anyway) that form data valida‐ tion is of the utmost importance, due to the possibility of users attempting to hack into your server. In addition to maliciously formed input data, some of the things you also have to check are whether a file was actually received and, if so, whether the right type of read more..

  • Page - 189

    The non-HTML section of code has been expanded from the half-dozen lines of Example 7-15 to more than 20 lines, starting at if ($_FILES) . As with the previous version, this if line checks whether any data was actually pos‐ ted, but there is now a matching else near the bottom of the program that echoes a message to screen when nothing has been uploaded. Within read more..

  • Page - 190

    But if you must use a supplied filename, you should sanitize it by allowing only alphanumeric characters and the period, which you can do with the following com‐ mand, using a regular expression (see Chapter 17) to perform a search and replace on $name : $name = preg_replace("/[^A-Za-z0-9.]/", "", $name); This leaves only the characters A–Z, a–z, 0–9, and read more..

  • Page - 191

    foreach($output as $line) echo htmlspecialchars("$line\n"); echo "</pre>"; ?> The htmlspecialchars function is called to turn any special characters returned by the system into ones that HTML can understand and properly display, neatening the output. Depending on the system you are using, the result of running this program will look something read more..

  • Page - 192

    The system calling functions are typically disabled on shared web hosts, as they pose a security risk. You should always try to solve your problems within PHP if you can, and go to the system directly only if it is really necessary. Also, going to the system is relatively slow, and you need to code two implementations if your applica‐ tion is expected to run on both read more..

  • Page - 193

    5. Which file access mode would you use with fopen to open a file in write and read mode, with the file truncated and the file pointer at the start? 6. What is the PHP command for deleting the file file.txt? 7. Which PHP function is used to read in an entire file in one go, even from across the Web? 8. Which PHP superglobal variable holds the details on read more..

  • Page - 194

    read more..

  • Page - 195

    CHAPTER 8 Introduction to MySQL With well over 10 million installations, MySQL is probably the most popular database management system for web servers. Developed in the mid-1990s, it’s now a mature technology that powers many of today’s most-visited Internet destinations. One reason for its success must be the fact that, like PHP, it’s free to use. But it’s also read more..

  • Page - 196

    Table 8-1. Example of a simple database Author Title Type Year Mark Twain The Adventures of Tom Sawyer Fiction 1876 Jane Austen Pride and Prejudice Fiction 1811 Charles Darwin The Origin of Species Nonfiction 1856 Charles Dickens The Old Curiosity Shop Fiction 1841 William Shakespeare Romeo and Juliet Play 1594 Each row in the table is the same as a row in read more..

  • Page - 197

    Starting the Command-Line Interface The following sections describe relevant instructions for Windows, OS X, and Linux. Windows users If you installed XAMPP (as explained in Chapter 2), you will be able to access the MySQL executable from the following directory: C:\xampp\mysql\bin If you installed XAMPP in a place other than \xampp, you will need to use that directory instead. By read more..

  • Page - 198

    Figure 8-1. Accessing MySQL from a Windows command prompt You are now ready to move on to the next section, “Using the Command-Line Inter‐ face” on page 171. OS X users To proceed with this chapter, you should have installed XAMPP as detailed in Chap‐ ter 2. You should also have the web server running and the MySQL server started. To enter the MySQL read more..

  • Page - 199

    Figure 8-2. Accessing MySQL from the OS X Terminal program If you receive an error such as “Can’t connect to local MySQL server through socket,” you will need to first start the MySQL server as described in Chapter 2. You should now be ready to move on to the next section, “Using the Command-Line Interface” on page 171. Linux users On a system running a read more..

  • Page - 200

    Figure 8-3. Accessing MySQL using Linux If this procedure fails at any point, please refer to Chapter 2 to ensure that you have MySQL properly installed. Otherwise, you should now be ready to move on to the next section, “Using the Command-Line Interface” on page 171. MySQL on a remote server If you are accessing MySQL on a remote server, you should Telnet (or read more..

  • Page - 201

    password. You should also ask for the ability to create new databases or, at a mini‐ mum, to have at least one database created for you ready to use. You can then create all the tables you require within that database. Using the Command-Line Interface From here on out, it makes no difference whether you are using Windows, Mac OS X, or Linux to access MySQL read more..

  • Page - 202

    Canceling a command If you are partway through entering a command and decide you don’t wish to execute it after all, whatever you do, don’t press Control-C! That will close the program. Instead, you can enter \c and press Return. Example 8-1 shows how to use it. Example 8-1. Canceling a line of input meaningless gibberish to mysql \c When you type that line, read more..

  • Page - 203

    Command Action RENAME Rename a table SHOW List details about an object SOURCE Execute a file STATUS (\s) Display the current status TRUNCATE Empty a table UNLOCK Unlock table(s) UPDATE Update an existing record USE Use a database I’ll cover most of these as we proceed, but first, you need to remember a couple of points about MySQL commands: • SQL read more..

  • Page - 204

    To create a user, issue the GRANT command, which takes the following form (don’t type this in; it’s not an actual working command): GRANT PRIVILEGES ON database.object TO 'username'@'hostname' IDENTIFIED BY 'password'; This should be pretty straightforward, with the possible exception of the data base.object part, which refers to the database itself and the objects it read more..

  • Page - 205

    You can grant only privileges that you already have, and you must also have the privilege to issue GRANT commands. There are a whole range of privileges you can choose to grant if you are not granting all privileges. For further details, please visit the following site, which also covers the REVOKE command, which can remove privi‐ leges once granted: read more..

  • Page - 206

    All being well, you will see the sequence of commands and responses shown in Example 8-4, where you should particularly note the table format displayed. Example 8-4. A MySQL session: creating and checking a new table mysql> USE publications; Database changed mysql> CREATE TABLE classics ( -> author VARCHAR(128), -> title VARCHAR(128), read more..

  • Page - 207

    Data Types In Example 8-3, you may have noticed that three of the table’s fields were given the data type of VARCHAR , and one was given the type CHAR . The term VARCHAR stands for VARiable length CHARacter string, and the command takes a numeric value that tells MySQL the maximum length allowed for a string stored in this field. This data type is very useful, read more..

  • Page - 208

    Table 8-6. MySQL’s CHAR data types Data type Bytes used Examples CHAR( n) Exactly n (<= 255) CHAR(5) “Hello” uses 5 bytes CHAR(57) “Goodbye” uses 57 bytes VARCHAR( n) Up to n (<= 65535) VARCHAR(7) “Morning” uses 7 bytes VARCHAR(100) “Night” uses 5 bytes The BINARY data type The BINARY data type is used for storing strings read more..

  • Page - 209

    The BLOB data type The term BLOB stands for Binary Large OBject and, therefore, as you would think, the BLOB data type is most useful for binary data in excess of 65,536 bytes in size. The main other difference between the BLOB and BINARY data types is that BLOB s cannot have default values (see Table 8-9). Table 8-9. MySQL’s BLOB data types Data type read more..

  • Page - 210

    To specify whether a data type is signed or unsigned, use the UNSIGNED qualifier. The following example creates a table called tablename with a field in it called fieldname of the data type UNSIGNED INTEGER : CREATE TABLE tablename (fieldname INT UNSIGNED); When creating a numeric field, you can also pass an optional number as a parameter, like this: CREATE TABLE tablename read more..

  • Page - 211

    The AUTO_INCREMENT data type Sometimes you need to ensure that every row in your database is guaranteed to be unique. You could do this in your program by carefully checking the data you enter and making sure that there is at least one value that differs in any two rows, but this approach is error-prone and works only in certain circumstances. In the classics table, read more..

  • Page - 212

    Rather than applying the column retroactively, you could have included it by issuing the CREATE command in a slightly different format. In that case, the command in Example 8-3 would be replaced with Example 8-6. Check the final line in particular. Example 8-6. Adding the auto-incrementing id column at table creation CREATE TABLE classics ( author VARCHAR(128), read more..

  • Page - 213

    SELECT * FROM classics; Figure 8-4. Populating the classics table and viewing its contents Don’t worry about the SELECT command for now—we’ll come to it in the section “Querying a MySQL Database” on page 192. Suffice it to say that, as typed, it will dis‐ play all the data you just entered. Let’s go back and look at how we used the INSERT command. The read more..

  • Page - 214

    If you tried that command, you should revert the table name by entering the follow‐ ing, so that later examples in this chapter will work as printed: ALTER TABLE pre1900 RENAME classics; Changing the data type of a column Changing a column’s data type also makes use of the ALTER command, this time in conjunction with the MODIFY keyword. So to change the data type read more..

  • Page - 215

    Figure 8-5. Adding the new pages column and viewing the table Renaming a column Looking again at Figure 8-5, you may decide that having a column named type can be confusing, because that is the name used by MySQL to identify data types. Again, no problem—let’s change its name to category, like this: ALTER TABLE classics CHANGE type category VARCHAR(16); read more..

  • Page - 216

    and then delete it by typing the commands in Example 8-9. The result of these four commands should look like Figure 8-6. Example 8-9. Creating, viewing, and deleting a table CREATE TABLE disposable(trash INT); DESCRIBE disposable; DROP TABLE disposable; SHOW tables; Figure 8-6. Creating, viewing, and deleting a table Indexes As things stand, the table classics works and can be read more..

  • Page - 217

    decide which columns require an index, a judgment that requires you to predict whether you will be searching any of the data in that column. Indexes can also get complicated, because you can combine multiple columns in one index. And even when you’ve decided that, you still have the option of reducing index size by limiting the amount of each column to be indexed. If we read more..

  • Page - 218

    which is exactly what we want, as authors may appear many times, the same book title could be used by multiple authors, and so on. Figure 8-7. Adding indexes to the classics table Using CREATE INDEX An alternative to using ALTER TABLE to add an index is to use the CREATE INDEX com‐ mand. They are equivalent, except that CREATE INDEX cannot be used for read more..

  • Page - 219

    Example 8-12. Creating the table classics with indexes CREATE TABLE classics ( author VARCHAR(128), title VARCHAR(128), category VARCHAR(16), year SMALLINT, INDEX(author(20)), INDEX(title(20)), INDEX(category(4)), INDEX(year)) ENGINE MyISAM; Primary keys So far, you’ve created the table classics and ensured that MySQL can search it quickly by adding indexes, but there’s still read more..

  • Page - 220

    Example 8-13. Populating the isbn column with data and using a primary key ALTER TABLE classics ADD isbn CHAR(13); UPDATE classics SET isbn='9781598184891' WHERE year='1876'; UPDATE classics SET isbn='9780582506206' WHERE year='1811'; UPDATE classics SET isbn='9780517123201' WHERE year='1856'; UPDATE classics SET isbn='9780099533474' WHERE year='1841'; UPDATE classics SET isbn='9780192814968' WHERE read more..

  • Page - 221

    INDEX(year), PRIMARY KEY (isbn)) ENGINE MyISAM; Creating a FULLTEXT index Unlike a regular index, MySQL’s FULLTEXT allows super-fast searches of entire col‐ umns of text. It stores every word in every data string in a special index that you can search using “natural language,” in a similar manner to using a search engine. It’s not strictly true that MySQL read more..

  • Page - 222

    If you find that MySQL is running slower than you think it should be when accessing your database, the problem is usually related to your indexes. Either you don’t have an index where you need one, or the indexes are not optimally designed. Tweaking a table’s indexes will often solve such a problem. Performance is beyond the scope of this book, but in Chapter 9 read more..

  • Page - 223

    Figure 8-9. The output from two different SELECT statements SELECT COUNT Another replacement for the something parameter is COUNT , which can be used in many ways. In Example 8-17, it displays the number of rows in the table by passing * as a parameter, which means all rows. As you’d expect, the result returned is 5 , as there are five publications in the read more..

  • Page - 224

    show that the simple SELECT lists Dickens twice, and the command with the DISTINCT qualifier shows him only once. Example 8-19. With and without the DISTINCT qualifier SELECT author FROM classics; SELECT DISTINCT author FROM classics; Figure 8-10. Selecting data with and without DISTINCT DELETE When you need to remove a row from a table, use the DELETE command. Its read more..

  • Page - 225

    WHERE The WHERE keyword enables you to narrow down queries by returning only those where a certain expression is true. Example 8-20 returns only the rows where the col‐ umn exactly matches the string Little Dorrit , using the equality operator = . Example 8-21 shows a couple more examples of using WHERE with = . Example 8-21. Using the WHERE keyword SELECT read more..

  • Page - 226

    Figure 8-11. Using WHERE with the LIKE qualifier LIMIT The LIMIT qualifier enables you to choose how many rows to return in a query, and where in the table to start returning them. When passed a single parameter, it tells MySQL to start at the beginning of the results and just return the number of rows given in that parameter. If you pass it two parameters, read more..

  • Page - 227

    Figure 8-12. Restricting the rows returned with LIMIT MATCH...AGAINST The MATCH...AGAINST construct can be used on columns that have been given a FULL TEXT index (see the section “Creating a FULLTEXT index” on page 191). With it, you can make natural-language searches as you would in an Internet search engine. Unlike the use of WHERE...= or WHERE...LIKE , read more..

  • Page - 228

    Figure 8-13. Using MATCH...AGAINST on a FULLTEXT index MATCH...AGAINST...in Boolean Mode If you wish to give your MATCH...AGAINST queries even more power, use Boolean mode. This changes the effect of the standard FULLTEXT query so that it searches for any combination of search words, instead of requiring all search words to be in the text. The presence of a single word read more..

  • Page - 229

    Figure 8-14. Using MATCH...AGAINST...in Boolean Mode As you would expect, the first request returns only The Old Curiosity Shop by Charles Dickens, because any rows containing the word species have been excluded, so Charles Darwin’s publication is ignored. There is something of interest to note in the second query: the stopword of is part of the search string, but is read more..

  • Page - 230

    Figure 8-15. Updating columns in the classics table In the first query, Mark Twain’s real name of Samuel Langhorne Clemens was appended to his pen name in brackets, which affected only one row. The second query, however, affected three rows, because it changed all occurrences of the word Fiction in the category column to the term Classic Fiction. When performing read more..

  • Page - 231

    Figure 8-16. Sorting the results of requests If you wanted to sort all the rows by author and then by descending year of publica‐ tion (to view the most recent first), you would issue the following query: SELECT author,title,year FROM classics ORDER BY author,year DESC; This shows that each ascending and descending qualifier applies to a single column. The DESC read more..

  • Page - 232

    Joining Tables Together It is quite normal to maintain multiple tables within a database, each holding a differ‐ ent type of information. For example, consider the case of a customers table that needs to be able to be cross-referenced with publications purchased from the classics table. Enter the commands in Example 8-28 to create this new table and populate it with read more..

  • Page - 233

    Of course, in a proper table containing customers’ details there would also be addresses, phone numbers, email addresses, and so on, but they aren’t necessary for this explanation. While creating the new table, you should have noticed that it has something in common with the classics table: a column called isbn. Because it has the same meaning in both tables (an ISBN read more..

  • Page - 234

    particularly useful when you have long queries that reference the same table names many times. SELECT name,author,title from customers AS cust, classics AS class WHERE cust.isbn=class.isbn; The result of this operation is the following: +-------------+-----------------+------------------------+ | name | author | title read more..

  • Page - 235

    Having functions built into MySQL substantially reduces the time needed for per‐ forming complex queries, as well as their complexity. If you wish to learn more about the available string and date/time functions, you can visit the following URLs: http://tinyurl.com/mysqlstrings http://tinyurl.com/mysqldates However, to get you started, Appendix D describes a subset containing the most read more..

  • Page - 236

    Now click the phpMyAdmin link toward the bottom of the lefthand menu to open up the program (see Figure 8-19). Figure 8-19. The phpMyAdmin main screen In the lefthand pane of the main phpMyAdmin screen, you can click to select any database you wish to work with. This will open the database and display its tables. You can also click New to create a new database. From read more..

  • Page - 237

    3. How would you create a new MySQL user on the local host called newuser with a password of newpass and with access to everything in the database newdatabase? 4. How can you view the structure of a table? 5. What is the purpose of a MySQL index? 6. What benefit does a FULLTEXT index provide? 7. What is a stopword? 8. Both SELECT DISTINCT and GROUP BY read more..

  • Page - 238

    read more..

  • Page - 239

    CHAPTER 9 Mastering MySQL Chapter 8 provided you with a good grounding in the practice of using relational databases with Structured Query Language. You’ve learned about creating databases and the tables they comprise, as well as inserting, looking up, changing, and deleting data. With that knowledge under your belt, we now need to look at how to design databa‐ ses for read more..

  • Page - 240

    • Which books have not sold this year? • Which books did a certain customer buy? • Which books have been purchased along with the same other books? Of course, there are many more queries that you could make on such a database, but even this small sample will begin to give you insights into how to lay out your tables. For example, books and ISBNs can probably read more..

  • Page - 241

    tomers, you can just assign arbitrary keys, which the AUTO_INCREMENT feature that you saw in the last chapter makes easy. In short, every table will be designed around some object that you’re likely to search for a lot—an author, book, or customer, in this case—and that object will have a pri‐ mary key. Don’t choose a key that could possibly have the same read more..

  • Page - 242

    Table 9-1. A highly inefficient design for a database table Author 1 Author 2 Title ISBN Price $US Customer Name Customer Address Purchase Date David Sklar Adam Trachtenberg PHP Cookbook 0596101015 44.99 Emma Brown 1565 Rainbow Road, Los Angeles, CA 90014 Mar 03 2009 Danny Goodman Dynamic HTML 0596527403 59.99 Darren Ryder 4758 Emily Drive, Richmond, VA 23219 Dec 19 2008 read more..

  • Page - 243

    Table 9-2 shows the result of removing the Authors columns from Table 9-1. Already it looks a lot less cluttered, although there remain duplications that are highlighted. Table 9-2. The result of stripping the Authors columns from Table 9-1 Title ISBN Price $US Customer Name Customer Address Purchase Date PHP Cookbook 0596101015 44.99 Emma Brown 1565 Rainbow Road, read more..

  • Page - 244

    cannot be the primary key in this table, because it’s not unique: the same ISBN appears multiple times whenever two or more authors have collaborated on a book. Because we’ll use it to link authors to books in another table, this column is called a foreign key. Keys (also called indexes) have several purposes in MySQL. The fundamental reason for defining a key is read more..

  • Page - 245

    However, looking at the extracted Customer columns, now in Table 9-5, we can see that there’s still more normalization work to do, because Darren Ryder’s details are still duplicated. And it could also be argued that First Normal Form Rule 2 (all col‐ umns should contain a single value) has not been properly complied with, because the addresses really need to be read more..

  • Page - 246

    Table 9-7. The new Purchases table CustNo ISBN Date 1 0596101015 Mar 03 2009 2 0596527403 Dec 19 2008 2 0596101015 Dec 19 2008 3 0596005436 Jun 22 2009 4 0596006815 Jan 16 2009 Here the CustNo column from Table 9-6 is reused as a key to tie both the Customers and the Purchases tables together. Because the ISBN column is also repeated here, this table can read more..

  • Page - 247

    Dynamic HTML, was written by Danny Goodman, and that ISBN 0596101015, PHP Cookbook, was written by David Sklar and Adam Trachtenberg. Third Normal Form Once you have a database that complies with both the First and Second Normal Forms, it is in pretty good shape and you might not have to modify it any further. However, if you wish to be very strict with your database, read more..

  • Page - 248

    Table 9-11. Third Normal Form States table StateID Name Abbreviation 5 California CA 46 Virginia VA 17 Kentucky KY 21 Massachusetts MA So, how would you use this set of four tables instead of the single Table 9-6? Well, you would look up the Zip code in Table 9-8, and then find the matching CityID in Table 9-9. Given this information, you could look up the city Name read more..

  • Page - 249

    When Not to Use Normalization Now that you know all about normalization, I’m going to tell you why you should throw these rules out of the window on high-traffic sites. That’s right—you should never fully normalize your tables on sites that will cause MySQL to thrash. Normalization requires spreading data across multiple tables, and this means making multiple calls to MySQL read more..

  • Page - 250

    of a one-to-one relationship is the relationship between the name of a state and its two-character abbreviation. However, for the sake of argument, let’s assume that there can always be only one cus‐ tomer at any address. In such a case, the Customers–Addresses relationship in Figure 9-1 is a one-to-one relationship: only one customer lives at each address, and each read more..

  • Page - 251

    is also the preferred scheme to use when describing a many-to-one relationship, in which case you would normally swap the left and right tables to view them as a one- to-many relationship. Figure 9-2. Illustrating the relationship between two tables Many-to-Many In a many-to-many relationship, many rows in one table are linked to many rows in another table. To create this read more..

  • Page - 252

    find out his or her name, or use the new intermediary Table 9-12 to see the book(s) purchased. From here, you will find that two titles were purchased and can follow them back to Table 9-4 to find the titles and prices of these books, or to Table 9-3 to see who the authors were. If it seems to you that this is really combining multiple one-to-many relationships, read more..

  • Page - 253

    Transactions In some applications, it is vitally important that a sequence of queries runs in the cor‐ rect order and that every single query successfully completes. For example, suppose that you are creating a sequence of queries to transfer funds from one bank account to another. You would not want either of the following events to occur: • You add the funds to the read more..

  • Page - 254

    +---------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+---------+------+-----+---------+-------+ | number | int(11) | NO | PRI | 0 | | | balance | float | YES | | NULL | | +---------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) read more..

  • Page - 255

    As you can see, the balance of account number 12345 was increased by 25.11 and is now 1050.61. You may also have noticed the COMMIT command in Example 9-3, which is explained next. Using COMMIT When you are satisfied that a series of queries in a transaction has successfully com‐ pleted, issue a COMMIT command to commit all the changes to the database. Until it read more..

  • Page - 256

    You should now see the following output, showing that the two accounts have had their previous balances restored, due to the entire transaction being cancelled via the ROLLBACK command: +--------+---------+ | number | balance | +--------+---------+ | 12345 | 1050.61 | | 67890 | 140 | +--------+---------+ 2 rows in set (0.00 sec) Using EXPLAIN MySQL comes with a powerful read more..

  • Page - 257

    key The key actually used is PRIMARY . This is good. key_len The key length is 4 . This is the number of bytes of the index that MySQL will use. ref The ref column displays which columns or constants are used with the key. In this case, a constant key is being used. rows The number of rows that needs to be searched by this query is 1 . This is good. Whenever read more..

  • Page - 258

    Or you can lock the tables you are backing up before running mysqldump . To lock tables for reading (as we want to read the data), from the MySQL command line issue this command: LOCK TABLES tablename1 READ, tablename2 READ ... Then, to release the lock(s), enter the following: UNLOCK TABLES; By default, the output from mysqldump is simply printed out, but you can read more..

  • Page - 259

    Figure 9-4. Dumping the publications database to screen Creating a Backup File Now that you have mysqldump working, and have verified it outputs correctly to the screen, you can send the backup data directly to a file using the > redirect symbol. Assuming that you wish to call the backup file publications.sql, type the command in Example 9-8 (remembering to replace read more..

  • Page - 260

    KEY 'category' ('category'(4)), KEY 'year' ('year'), FULLTEXT KEY 'author_2' ('author','title') ) ENGINE=MyISAM DEFAULT CHARSET=latin1; This is smart code that can be used to restore a database from a backup, even if it currently exists, because it will first drop any tables that need to be re-created, thus avoiding potential MySQL errors. Backing up a single table To read more..

  • Page - 261

    Restoring from a Backup File To perform a restore from a file, call the mysql executable, passing it the file to restore from using the < symbol. So, to recover an entire database that you dumped using the --all-databases option, use a command such as that in Example 9-10. Example 9-10. Restoring an entire set of databases mysql -u user -p password < read more..

  • Page - 262

    Mary Smith','9780582506206 Jack Wilson','9780517123201 Planning Your Backups The golden rule to backing up is to do so as often as you find practical. The more valuable the data, the more often you should back it up, and the more copies you should make. If your database gets updated at least once a day, you should really back it up on a daily basis. If, on the other read more..

  • Page - 263

    CHAPTER 10 Accessing MySQL Using PHP If you worked through the previous chapters, you’re proficient in using both MySQL and PHP. In this chapter, you will learn how to integrate the two by using PHP’s built- in functions to access MySQL. Querying a MySQL Database with PHP The reason for using PHP as an interface to MySQL is to format the results of SQL queries in a read more..

  • Page - 264

    2. Build a query string. 3. Perform the query. 4. Retrieve the results and output them to a web page. 5. Repeat steps 2 to 4 until all desired data has been retrieved. 6. Disconnect from MySQL. We’ll work through these sections in turn, but first it’s important to set up your login details in a secure manner so people snooping around on your system have trouble read more..

  • Page - 265

    Web. However, the examples in this chapter will be working on the local server. So, in place of specifying a domain such as mysql.myserver.com, you can just use the word localhost (or the IP address The database we’ll be using, $db , is the one called publications, which we created in Chapter 8 (or may have been provided to you by your server read more..

  • Page - 266

    The die function is great for when you are developing PHP code, but of course you will want more user-friendly error messages on a production server. In this case, you won’t abort your PHP program, but format a message that will be displayed when the program exits normally, perhaps something like this: function mysql_fatal_error($msg) { $msg2 = mysql_error(); read more..

  • Page - 267

    Fetching a result Once you have an object returned in $result , you can use it to extract the data you want, one item at a time, using the fetch_assoc method of the object. Example 10-4 combines and extends the previous examples into a program that you can type and run yourself to retrieve these results (as depicted in Figure 10-1). I suggest that you save this read more..

  • Page - 268

    Figure 10-1. The output from the query.php program in Example 10-4 Here, to seek to the correct row each time around the loop, we call the data_seek method of $result before fetching each item of data. Then we call the fetch_assoc method to retrieve the value stored in each cell, and output the result using echo statements. You will probably agree that all this read more..

  • Page - 269

    Fetching a row To fetch one row at a time, replace the for loop from Example 10-4 with the one highlighted in bold in Example 10-5, and you will find that you get exactly the same result that was displayed in Figure 10-1. You may wish to save this revised file using the name fetchrow.php. Example 10-5. Fetching results one row at a time <?php //fetchrow.php read more..

  • Page - 270

    MYSQLI_ASSOC Associative array. Each key is the name of a column. Because items of data are refer‐ enced by column name (rather than index number), use this option where possible in your code to make debugging easier and help other programmers better manage your code. MYSQLI_BOTH Associative and numeric array. Associative arrays are usually more useful than numeric ones because read more..

  • Page - 271

    Example 10-6 creates a standard HTML form. Chapter 11 explains forms in detail, but in this chapter I take form handling for granted and just deal with database interaction. Example 10-6. Inserting and deleting using sqltest.php <?php // sqltest.php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); read more..

  • Page - 272

    $result = $conn->query($query); if (!$result) die ("Database access failed: " . $conn->error); $rows = $result->num_rows; for ($j = 0 ; $j < $rows ; ++$j) { $result->data_seek($j); $row = $result->fetch_array(MYSQLI_NUM); echo <<<_END <pre> Author $row[0] Title $row[1] Category $row[2] read more..

  • Page - 273

    Figure 10-2. The output from Example 10-6, sqltest.php At over 80 lines of code, this program may appear daunting, but don’t worry—you’ve already covered many of them in Example 10-5, and what the code does is actually quite simple. It first checks for any inputs that may have been made and then either inserts new data into the table classics of the read more..

  • Page - 274

    server bundles up all of the user input (even if the form was filled out with a hundred fields) and puts in into an array named $_POST . $_POST is an associative array, which you encountered in Chapter 6. Depending on whether a form has been set to use the Post or the Get method, either the $_POST or the $_GET associative array will be populated with the read more..

  • Page - 275

    values, then $query is set to an INSERT INTO command, followed by the five values to be inserted. The string is then passed to the query method, which upon completion returns either TRUE or FALSE . If FALSE is returned, the error message held in the error property of the $conn object is displayed, like this: if (!$result) echo "INSERT failed: $query<br>" read more..

  • Page - 276

    Querying the Database Next, the code returns to the familiar territory of Example 10-5, where a query is sent to MySQL asking to see all the records in the classics table, like this: $query = "SELECT * FROM classics"; $result = $conn->query($query); After that, $rows is set to a value representing the number of rows in the table: $rows = $result->num_rows; Using read more..

  • Page - 277

    Herman Melville Moby Dick Fiction 1851 9780199535729 Running the Program When you have submitted this data using the ADD RECORD button, scroll down to the bottom of the web page to see the new addition. It should look like Figure 10-3. Figure 10-3. The result of adding Moby Dick to the database Now let’s look at how deleting a record works by creating a read more..

  • Page - 278

    Assuming that everything worked, you are now able to add and delete records at will. Try doing this a few times, but leave the main records in place (including the new one for Moby Dick), as we’ll be using them later. You could also try adding the record with all 1s again a couple of times and note the error message that you receive the second time, indicating read more..

  • Page - 279

    $result = $conn->query($query); if (!$result) die ("Database access failed: " . $conn->error); ?> As you can see, the MySQL query looks pretty similar to how you would type it directly in the command line, except that there is no trailing semicolon, as none is needed when you are accessing MySQL from PHP. Describing a Table When you aren’t logged into the read more..

  • Page - 280

    name varchar(32) NO age tinyint(4) NO Dropping a Table Dropping a table is very easy to do and is therefore very dangerous, so be careful. Example 10-9 shows the code that you need. However, I don’t recommend that you try it until you have been through the other examples, as it will drop the table cats and you’ll have to re-create it using Example read more..

  • Page - 281

    Of course, the most efficient way to populate MySQL with data is to create an array and insert the data with a single query. Retrieving Data Now that some data has been entered into the cats table, Example 10-11 shows how you can check that it was correctly inserted. Example 10-11. Retrieving rows from the cats table <?php require_once 'login.php'; $conn = read more..

  • Page - 282

    Example 10-12. Renaming Charly the cheetah to Charlie <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); $query = "UPDATE cats SET name='Charlie' WHERE name='Charly' "; $result = $conn->query($query); if (!$result) die ("Database access failed: " . $conn->error); ?> If you read more..

  • Page - 283

    and then refer to the newly created CustId when inserting a purchase into the pur‐ chase table. Example 10-10 can be rewritten as Example 10-14 to display this value after each insert. Example 10-14. Adding data to table cats and reporting the insertion id <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if read more..

  • Page - 284

    Using locks A completely safe procedure for linking tables through the insert ID is to use locks (or transactions, as described in Chapter 9). It can slow down response time a bit when there are many people submitting data to the same table, but it can also be worth it. The sequence is as follows: 1. Lock the first table (e.g., cats). 2. Insert data into the first read more..

  • Page - 285

    $subquery = "SELECT * FROM classics WHERE isbn='$row[1]'"; $subresult = $conn->query($query); if (!$subresult) die ("Database access failed: " . $conn->error); $subrow = $subresult->fetch_array(MYSQLI_NUM); echo " '$subrow[1]' by $subrow[0]<br>"; } ?> This program uses an initial query to the customers table to read more..

  • Page - 286

    Do you see the problem there? In MySQL, the # symbol represents the start of a com‐ ment. Therefore, the user will be logged in as admin (assuming there is a user admin), without having to enter a password. In the following, the part of the query that will be executed is shown in bold; the rest will be ignored. SELECT * FROM users WHERE user='admin' # ' AND read more..

  • Page - 287

    The get_magic_quotes_gpc function returns TRUE if magic quotes are active. In that case, any slashes that have been added to a string have to be removed, or the real_escape_string method could end up double-escaping some characters, creat‐ ing corrupted strings. Example 10-17 illustrates how you would incorporate mysql_fix_string within your own code. Example 10-17. How to read more..

  • Page - 288

    Example 10-18. MySQL placeholders PREPARE statement FROM "INSERT INTO classics VALUES(?,?,?,?,?)"; SET @author = "Emily Brontë", @title = "Wuthering Heights", @category = "Classic Fiction", @year = "1847", @isbn = "9780553212587"; EXECUTE statement USING @author,@title,@category,@year,@isbn; read more..

  • Page - 289

    Before going any further, it makes sense to next check whether the command was executed successfully, so here’s how you can do that by checking the affected_rows property of $statement : printf("%d Row inserted.\n", $stmt->affected_rows); In the preceding example, there should be notification of one row inserted. Once you are happy that the statement executed successfully (or read more..

  • Page - 290

    This occurs when you allow HTML, or more often JavaScript code, to be input by a user and then displayed back by your website. One place this is common is in a com‐ ment form. What happens most often is that a malicious user will try to write code that steals cookies from your site’s users, allowing him or her to discover username and password pairs or other read more..

  • Page - 291

    Example 10-21. How to safely access MySQL and prevent XSS attacks <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); $user = mysql_entities_fix_string($conn, $_POST['user']); $pass = mysql_entities_fix_string($conn, $_POST['pass']); $query = "SELECT * FROM users WHERE user='$user' AND read more..

  • Page - 292

    An integer is returned in $rows . You can fetch the actual data one row at a time in the following way, which returns a numeric array: $row = mysqli_fetch_array($result, MYSQLI_NUM); In this instance, $row[0] will contain the first column of data, $row[1] the second, and so on. As described in Example 11-5, rows can also be returned as associative arrays or as both read more..

  • Page - 293

    Questions 1. How do you connect to a MySQL database using mysqli ? 2. How do you submit a query to MySQL using mysqli ? 3. How can you retrieve a string containing an error message when a mysqli error occurs? 4. How can you determine the number of rows returned by a mysqli query? 5. How can you retrieve a particular row of data from a set of mysqli results? read more..

  • Page - 294

    read more..

  • Page - 295

    CHAPTER 11 Form Handling The main way that website users interact with PHP and MySQL is through the use of HTML forms. These were introduced very early on in the development of the World Wide Web in 1993—even before the advent of ecommerce—and have remained a mainstay ever since, due to their simplicity and ease of use. Of course, enhancements have been made over the read more..

  • Page - 296

    Example 11-1 shows a very simple form created with PHP, which you should type in and save as formtest.php. Example 11-1. formtest.php—a simple PHP form handler <?php // formtest.php echo <<<_END <html> <head> <title>Form Test</title> </head> <body> <form read more..

  • Page - 297

    Retrieving Submitted Data Example 11-1 is only one part of the multipart form-handling process. If you enter a name and click the Submit Query button, absolutely nothing will happen other than the form being redisplayed. So now it’s time to add some PHP code to process the data submitted by the form. Example 11-2 expands on the previous program to include data read more..

  • Page - 298

    Notice how the <input> elements in this example do not use the /> form of self-closing, because in the new world of HTML5 this style is optional (and it was never actually required in HTML4 anyway; it was recommended purely because XHTML was planned to supersede HTML at some point—but this never happened). So since I’m always in favor of less work when read more..

  • Page - 299

    If you ever find yourself maintaining code that seems to assume values for certain variables for no apparent reason, you can make an educated guess that the programmer probably wrote the code using register_globals , and that these values are intended to be extracted from a Post or Get. If so, I recommend that you rewrite the code to load these variables explicitly from the read more..

  • Page - 300

    Figure 11-3. Using default values for selected form fields Default values are also used for hidden fields if you want to pass extra information from your web page to your program, in addition to what users enter. We’ll look at hidden fields later in this chapter. Input Types HTML forms are very versatile and allow you to submit a wide range of input types, read more..

  • Page - 301

    The first thing to notice is that <textarea> has its own tag and is not a subtype of the <input> tag. It therefore requires a closing </textarea> to end input. Instead of a default attribute, if you have default text to display, you must put it before the closing </textarea> , and it will then be displayed and be editable by the user: read more..

  • Page - 302

    On the other hand, if you wish to offer a newsletter to your readers when submitting a form, you might want to have the checkbox already checked as the default value: Subscribe? <input type="checkbox" name="news" checked="checked"> If you want to allow groups of items to be selected at one time, assign them all the same name. However, only the last read more..

  • Page - 303

    If the field ice has been posted as a single value, $ice will be a single string, such as "Strawberry" . But if ice was defined in the form as an array (like Example 11-5), $ice will be an array, and its number of elements will be the number of values sub‐ mitted. Table 11-2 shows the seven possible sets of values that could be submitted by read more..

  • Page - 304

    Figure 11-5. Selecting a single value with radio buttons Here, the second option of Noon–4pm has been selected by default. This default choice ensures that at least one delivery time will be chosen by the user, which she can change to one of the other two options if she prefers. Had one of the items not been already checked, the user might forget to select an read more..

  • Page - 305

    <select> The <select> tag lets you create a drop-down list of options, offering either single or multiple selections. It conforms to the following syntax: <select name=" name" size="size" multiple="multiple"> The attribute size is the number of lines to display. Clicking on the display causes a list to drop down, showing all the options. If read more..

  • Page - 306

    <option value="Peas">Peas</option> <option value="Beans">Beans</option> <option value="Carrots">Carrots</option> <option value="Cabbage">Cabbage</option> <option value="Broccoli">Broccoli</option> </select> This HTML is not very different; only the size has been changed to "5" and the attribute read more..

  • Page - 307

    The submit button To match the type of form being submitted, you can change the text of the submit button to anything you like by using the value attribute, like this: <input type="submit" value="Search"> You can also replace the standard text button with a graphic image of your choice, using HTML such as this: <input type="image" name="submit" read more..

  • Page - 308

    To get rid of unwanted slashes, use this: $variable = stripslashes($variable); And to remove any HTML from a string, use the following: $variable = htmlentities($variable); For example, this would change a string of interpretable HTML code like <b>hi</b> into &lt;b&gt;hi&lt;/b&gt; , which displays as text, and won’t be interpreted as HTML tags. Finally, if you read more..

  • Page - 309

    If you are using the procedural version of the mysqli extension, you will need to modify the sanitizeMySQL function to call the mysqli_real_escape_string function, like this (in which case $connection will then be a handle, not an object): $var = mysqli_real_escape_string($connection, $var); An Example Program So let’s look at how a real-life PHP program integrates with an read more..

  • Page - 310

    </html> _END; function sanitizeString($var) { $var = stripslashes($var); $var = strip_tags($var); $var = htmlentities($var); return $var; } ?> When you call up convert.php in a browser, the result should look something like Figure 11-8. Figure 11-8. The temperature conversion program in action To break the program down, the first read more..

  • Page - 311

    On the other hand, if $c is found to have a value, a complementary operation is per‐ formed to convert the value of $c from Celsius to Fahrenheit and assign the result to $f . The formula used is Fahrenheit = (9 / 5) × Celsius + 32. As with the previous sec‐ tion, the string $out is then set to contain a message about the conversion. In both conversions, the PHP read more..

  • Page - 312

    The autocomplete Attribute You can apply the autocomplete attribute to either the <form> element, or to any of the color , date , email , password , range , search , tel , text , or url types of the <input> element. With autocomplete enabled, previous user inputs are recalled and automatically entered into fields as suggestions. You can also disable this feature read more..

  • Page - 313

    <input type='text' name='creditcard' required='required'> When the browser detects attempted form submission where there’s an uncompleted required input, a message is displayed, prompting the user to complete the field. Override Attributes With override attributes, you can override form settings on an element-by-element basis. So, for example, using the formaction attribute, you can specify read more..

  • Page - 314

    attribute. The following code shows a form being created, but with its input outside of the <form> and </form> tags: <form action='myscript.php' method='post' id='form1'> </form> <input type='text' name='username' form='form1'> To do this, you must give the form an ID using the id attribute, and this is the ID to which the form attribute of an input element read more..

  • Page - 315

    When you are stepping through date or time values, each unit represents 1 second. This attribute is not yet supported by Firefox or IE. The color Input Type The color input type calls up a color picker so that you can simply click the color of your choice. You use it like this: Choose a color <input type='color' name='color'> Neither Firefox nor IE supports this read more..

  • Page - 316

    4. If a form has to offer three choices to a user, each of which is mutually exclusive so that only one of the three can be selected, which input type would you use, given a choice between checkboxes and radio buttons? 5. How can you submit a group of selections from a web form using a single field name? 6. How can you submit a form field without displaying it read more..

  • Page - 317

    CHAPTER 12 Cookies, Sessions, and Authentication As your web projects grow larger and more complicated, you will find an increasing need to keep track of your users. Even if you aren’t offering logins and passwords, you will still often need to store details about a user’s current session and possibly also recognize her when she returns to your site. Several technologies read more..

  • Page - 318

    Because of this, most browsers allow users to turn cookies off either for the current server’s domain, third-party servers, or both. Fortunately, most people who disable cookies do so only for third-party websites. Cookies are exchanged during the transfer of headers, before the actual HTML of a web page is sent, and it is impossible to send a cookie once any HTML has been read more..

  • Page - 319

    4. Because the cookie has already been set, when the server receives the request to send /news.html, it does not have to resend the cookie, but just returns the requested page. Setting a Cookie Setting a cookie in PHP is a simple matter. As long as no HTML has yet been trans‐ ferred, you can call the setcookie function, which has the following syntax (see Table read more..

  • Page - 320

    Accessing a Cookie Reading the value of a cookie is as simple as accessing the $_COOKIE system array. For example, if you wish to see whether the current browser has the cookie called user name already stored and, if so, to read its value, use the following: if (isset($_COOKIE['username'])) $username = $_COOKIE['username']; Note that you can read a cookie back only after read more..

  • Page - 321

    After entering your URL into the browser or visiting via a link, the user will see an “Authentication Required” prompt pop up, requesting two fields: User Name and Password (Figure 12-2 shows how this looks in Firefox). Figure 12-2. An HTTP authentication login prompt Example 12-1 shows the code to make this happen. Example 12-1. PHP authentication <?php if read more..

  • Page - 322

    By default, the type of interface Zend Server uses is cgi-fcgi, which is incompatible with basic authentication. However, configuring Zend is beyond the scope of this book, so if you are using it for Example 12-1 through Example 12-5, you may prefer to test them on a different server. To determine the interface of a server, you can call the php_sapi_name function, which read more..

  • Page - 323

    Once a user has been authenticated, you will not be able to get the authentication dialog to pop up again unless the user closes and reopens all browser windows, as the web browser will keep return‐ ing the same username and password to PHP. You may need to close and reopen your browser a few times as you work through this section and try different things out. Now read more..

  • Page - 324

    Storing Usernames and Passwords Obviously, MySQL is the natural way to store usernames and passwords. But again, we don’t want to store the passwords as clear text, because our website could be com‐ promised if the database were accessed by a hacker. Instead, we’ll use a neat trick called a one-way function. This type of function is easy to use and converts a string read more..

  • Page - 325

    $token = hash('ripemd128', 'saltstringmypassword'); In this example, the text saltstring has been prepended to the password. Of course, the more obscure you can make the salt, the better. I like to use salts such as this: $token = hash('ripemd128', 'hqb%$tmypasswordcg*l'); Here some random characters have been placed both before and after the password. Given just the database, and read more..

  • Page - 326

    $password = 'acrobat'; $token = hash('ripemd128', "$salt1$password$salt2"); add_user($connection, $forename, $surname, $username, $token); function add_user($connection, $fn, $sn, $un, $pw) { $query = "INSERT INTO users VALUES('$fn', '$sn', '$un', '$pw')"; $result = $connection->query($query); if (!$result) die($connection->error); read more..

  • Page - 327

    Hi $row[0], you are now logged in as '$row[2]'"; else die("Invalid username/password combination"); } else die("Invalid username/password combination"); } else { header('WWW-Authenticate: Basic realm="Restricted Section"'); header('HTTP/1.0 401 Unauthorized'); die ("Please enter your read more..

  • Page - 328

    Figure 12-4. Bill Smith has now been authenticated You can try this out for yourself by calling up the program in your browser and enter‐ ing a username of bsmith and password of mysecret (or pjones and acrobat ), the values that were saved in the database by Example 12-3. By sanitizing input immediately after it is encountered, you will block any malicious HTML, read more..

  • Page - 329

    Starting a Session Starting a session requires calling the PHP function session_start before any HTML has been output, similarly to how cookies are sent during header exchanges. Then, to begin saving session variables, you just assign them as part of the $_SESSION array, like this: $_SESSION['variable'] = $value; They can then be read back just as easily in later program runs, read more..

  • Page - 330

    $salt2 = "pg!@"; $token = hash('ripemd128', "$salt1$pw_temp$salt2"); if ($token == $row[3]) { session_start(); $_SESSION['username'] = $un_temp; $_SESSION['password'] = $pw_temp; read more..

  • Page - 331

    $username = $_SESSION['username']; $password = $_SESSION['password']; $forename = $_SESSION['forename']; $surname = $_SESSION['surname']; echo "Welcome back $forename.<br> Your full name is $forename $surname.<br> Your username is '$username' and your password is read more..

  • Page - 332

    Ending a Session When the time comes to end a session, usually when a user requests to log out from your site, you can use the session_destroy function in association, as in Example 12-7. That example provides a useful function for totally destroying a ses‐ sion, logging a user out, and unsetting all session variables. Example 12-7. A handy function to destroy a read more..

  • Page - 333

    The first time you navigate from authenticate2.php to continue.php, it will display all the session variables. But, because of the call to destroy_session_and_data , if you then click your browser’s Reload button, the session will have been destroyed and you’ll be prompted to return to the login page. Setting a Time-Out There are other times when you might wish to close a read more..

  • Page - 334

    What code you place in your different_user function is up to you. I recommend that you simply delete the current session and ask the user to log in again due to a technical error. Don’t say any more than that, or you’re giving away potentially useful information. Of course, you need to be aware that users on the same proxy server, or sharing the same IP read more..

  • Page - 335

    echo $_SESSION['count']; ?> Once it’s saved, call it up in your browser using the following URL (prefacing it with the correct pathname, such as http://localhost/web/): sessiontest.php?PHPSESSID=1234 Press Reload a few times, and you’ll see the counter increase. Now try browsing to sessiontest.php?PHPSESSID=5678 Press Reload a few times here, and you should see it count up again read more..

  • Page - 336

    This way, an attacker can come back to your site using any of the session IDs that he or she generated, but none of them will call up another user’s session, as they will all have been replaced with regenerated IDs. If you want to be ultra-paranoid, you can even regenerate the session ID on each request. Forcing cookie-only sessions If you are prepared to require read more..

  • Page - 337

    Questions 1. Why must a cookie be transferred at the start of a program? 2. Which PHP function stores a cookie on a web browser? 3. How can you destroy a cookie? 4. Where are the username and password stored in a PHP program when you are using HTTP authentication? 5. Why is the hash function a powerful security measure? 6. What is meant by salting a string? 7. read more..

  • Page - 338

    read more..

  • Page - 339

    CHAPTER 13 Exploring JavaScript JavaScript brings a dynamic functionality to your websites. Every time you see some‐ thing pop up when you mouse over an item in the browser, or see new text, colors, or images appear on the page in front of your eyes, or grab an object on the page and drag it to a new location—all those things are done through JavaScript. It offers read more..

  • Page - 340

    JavaScript and HTML Text JavaScript is a client-side scripting language that runs entirely inside the web browser. To call it up, you place it between opening <script> and closing </script> HTML tags. A typical HTML 4.01 “Hello World” document using JavaScript might look like Example 13-1. Example 13-1. “Hello World” displayed using JavaScript <html> read more..

  • Page - 341

    When Example 13-1 is loaded, a web browser with JavaScript enabled will output the following (see Figure 13-1): Hello World Figure 13-1. JavaScript, enabled and working A browser with JavaScript disabled will display this message (see Figure 13-2): Your browser doesn't support or has disabled JavaScript. Figure 13-2. JavaScript has been disabled Using Scripts Within a Document Head read more..

  • Page - 342

    Example 13-2. The “Hello World” example modified for non-JavaScript browsers <html> <head><title>Hello World</title></head> <body> <script type="text/javascript"><!-- document.write("Hello World") // --> </script> </body> </html> Here an opening HTML comment tag (<!--) has been added directly after read more..

  • Page - 343

    <script type="text/javascript" src="http://someserver.com/script.js"> </script> As for the script files themselves, they must not include any <script> or </script> tags, because they are unnecessary: the browser already knows that a JavaScript file is being loaded. Putting them in the JavaScript files will cause an error. Including script files is the read more..

  • Page - 344

    tion mark has been left off the end of the string "Hello World" —a common syntax error. Example 13-3. A JavaScript “Hello World” script with an error <html> <head><title>Hello World</title></head> <body> <script type="text/javascript"> document.write("Hello World) </script> </body> read more..

  • Page - 345

    If you find this support a little underwhelming, the Firebug plug-in for Firefox (and now Chrome too) at http://getfirebug.com is very popular among JavaScript develop‐ ers and is definitely worth a look. If you will be typing the following code snippets to try them out, don’t forget to surround them with <script> and </script> tags. Using Comments Because of read more..

  • Page - 346

    There are exceptions to the semicolon rule. If you write JavaScript bookmarklets, or end a statement with a variable or function refer‐ ence, and the first character of the line below is a left parenthesis or bracket, you must remember to append a semicolon or the Java‐ Script will fail. So, when in doubt, use a semicolon. Variables No particular character identifies a read more..

  • Page - 347

    Numeric Variables Creating a numeric variable is as simple as assigning a value, like these examples: count = 42 temperature = 98.4 Like strings, numeric variables can be read from and used in expressions and func‐ tions. Arrays JavaScript arrays are also very similar to those in PHP, in that an array can contain string or numeric data, as well as other arrays. read more..

  • Page - 348

    JavaScript arrays are powerful storage structures, so Chapter 15 dis‐ cusses them in much greater depth. Operators Operators in JavaScript, as in PHP, can involve mathematics, changes to strings, and comparison and logical operations (and, or , etc.). JavaScript mathematical operators look a lot like plain arithmetic; for instance, the following statement outputs 15 : document.write(13 + read more..

  • Page - 349

    Table 13-3 lists the various assignment operators available. Table 13-3. Assignment operators Operator Example Equivalent to =j = 99 j = 99 += j += 2 j = j + 2 += j += 'string' j = j + 'string' -= j -= 12 j = j - 12 *= j *= 2 j = j * 2 /= j /= 6 j = j / 6 %= j %= 7 j = j % 7 Comparison Operators Comparison read more..

  • Page - 350

    Table 13-5. Logical operators Operator Description Example && And j == 1 && k == 2 || Or j < 100 || j > 0 ! Not ! (j == k) Variable Incrementing and Decrementing The following forms of post- and pre-incrementing and decrementing you learned to use in PHP are also supported by JavaScript: ++x --y x += 22 y -= 3 String Concatenation JavaScript read more..

  • Page - 351

    Table 13-6. JavaScript’s escape characters Character Meaning \b Backspace \f Form feed \n New line \r Carriage return \t Tab \' Single quote (or apostrophe) \" Double quote \\ Backslash \ XXX An octal number between 000 and 377 that represents the Latin-1 character equivalent (such as \251 for the © symbol) \x XX A hexadecimal number between read more..

  • Page - 352

    n += ' plus some text' // Change 'n' from a number to a string document.write('n = ' + n + ', and is a ' + typeof n + '<br>') </script> The output from this script looks like this: n = 838102050, and is a string n = 838102050, and is a number n = 838102050 plus some text, and is a string If there is ever any doubt about the type of read more..

  • Page - 353

    a = 123 // Global scope var b = 456 // Global scope if (a == 123) var c = 789 // Global scope Regardless of whether you are using the var keyword, as long as a variable is defined outside of a function, it is global in scope. This means that every part of a script can have access to read more..

  • Page - 354

    if (a == 123) var c = 789 } </script> The output from this script is the following single line: a = "123" This shows that only the variable a was given global scope, which is exactly what we would expect, since the variables b and c were given local scope by being prefaced with the var keyword. If your browser issues a warning about read more..

  • Page - 355

    Figure 13-3. Example of DOM object hierarchy The figure uses HTML tags that you are already familiar with to illustrate the parent/ child relationship between the various objects in a document. For example, a URL within a link is part of the body of an HTML document. In JavaScript, it is referenced like this: url = document.links.linkname.href Notice how this follows the read more..

  • Page - 356

    </script> </body> </html> Note the short form of the <script> tags where I have omitted the parameter type="text/JavaScript" to save you some typing. If you wish, just for the purposes of testing this (and other examples), you could also omit everything outside of the <script> and </script> tags. The output from this example read more..

  • Page - 357

    Another use for the $ symbol As mentioned earlier, the $ symbol is allowed in JavaScript variable and function names. Because of this, you may sometimes encounter strange-looking code like this: url = $('mylink').href Some enterprising programmers have decided that the getElementById function is so prevalent in JavaScript that they have written a function to replace it called $ read more..

  • Page - 358

    However, to stop websites from snooping on your browsing history, the history object stores only the number of sites in the array: you cannot read from or write to these values. But you can replace the current page with one from the history, if you know what position it has within the history. This can be very useful in cases in which you know that certain read more..

  • Page - 359

    Writing into Elements It is possible to write directly into the text of an HTML element, which is a fairly ele‐ gant solution (and the best one for production websites), except that for this book every example would require such an element to be created, and some lines of Java‐ Script code to access it. This gets in the way of teaching the core of an example read more..

  • Page - 360

    8. Give two cross-browser methods to display the URL assigned to the link with an id of thislink . 9. Which two JavaScript commands will make the browser load the previous page in its history array? 10. What JavaScript command would you use to replace the current document with the main page at the oreilly.com website? See Chapter 13 Answers in Appendix A for the read more..

  • Page - 361

    CHAPTER 14 Expressions and Control Flow in JavaScript In the previous chapter, I introduced the basics of JavaScript and the DOM. Now it’s time to look at how to construct complex expressions in JavaScript and how to con‐ trol the program flow of your scripts by using conditional statements. Expressions JavaScript expressions are very similar to those in PHP. As you read more..

  • Page - 362

    c: false d: true Notice that both expressions a: and d: evaluate to true . But b: and c: evaluate to false . Unlike PHP (which would print the number 1 and nothing, respectively), actual strings of true and false are displayed. In JavaScript, when you are checking whether a value is true or false , all values eval‐ uate to true except the following, which read more..

  • Page - 363

    And, as you’d expect, you see a return value from all of these in the following output: a: 42 b: Hi c: true d: Peter e: 24 Operators let you create more-complex expressions that evaluate to useful results. When you combine assignment or control-flow constructs with expressions, the result is a statement. Example 14-3 shows one of each. The first assigns the result of the read more..

  • Page - 364

    • Binary operators, which represent the bulk of JavaScript operators—including addition, subtraction, multiplication, and division—take two operands. • One ternary operator, which takes the form ? x : y . It’s a terse single-line if statement that chooses between two expressions depending on a third one. Operator Precedence As with PHP, JavaScript utilizes operator read more..

  • Page - 365

    This multiple assignment is possible only because the rightmost part of the expres‐ sion is evaluated first and then processing continues in a right-to-left direction. Table 14-3 lists operators and their associativity. Table 14-3. Operators and associativity Operator Description Associativity ++ -- Increment and decrement None new Create a new object Right + - ~ ! Unary and read more..

  • Page - 366

    Example 14-5. The equality and identity operators <script> a = 3.1415927 b = "3.1415927" if (a == b) document.write("1") if (a === b) document.write("2") </script> However, if you run the example, you will see that it outputs the number 1 , which means that the first if statement evaluated to true . This is because the read more..

  • Page - 367

    Table 14-4. JavaScript’s logical operators Logical operator Description && (and) true if both operands are true || (or) true if either operand is true ! (not) true if the operand is false , or false if the operand is true You can see how these can be used in Example 14-7, which outputs 0 , 1 , and true . Example 14-7. The read more..

  • Page - 368

    Table 14-5 shows all the possible variations of using the logical operators. You should also note that !true equals false , and !false equals true . Table 14-5. All possible logical expressions Inputs Operators and results Ab&& || true true true true true false false true false true false true false false false false The with Statement The with statement is not one that read more..

  • Page - 369

    Using onerror There are more constructs not available in PHP. Using either the onerror event, or a combination of the try and catch keywords, you can catch JavaScript errors and deal with them yourself. Events are actions that can be detected by JavaScript. Every element on a web page has certain events that can trigger JavaScript functions. For example, the onclick read more..

  • Page - 370

    Figure 14-1. Using the onerror event with an alert method pop-up Using try...catch The try and catch keywords are more standard and more flexible than the onerror technique shown in the previous section. These keywords let you trap errors for a selected section of code, rather than all scripts in a document. However, they do not catch syntax errors, for which you read more..

  • Page - 371

    I won’t go into how we implement the missing object in Internet Explorer here, but you can see how the system works. There’s also another keyword associated with try and catch called finally that is always executed, regardless of whether an error occurs in the try clause. To use it, just add something like the following statements after a catch statement: read more..

  • Page - 372

    Unlike PHP, JavaScript has no elseif statement, but that’s not a problem, because you can use an else followed by another if to form the equivalent of an elseif statement, like this: if (a > 100) { document.write("a is greater than 100") } else if(a < 100) { document.write("a is less than 100") } else { document.write("a is equal to 100") read more..

  • Page - 373

    But using a switch construct, the code could look like Example 14-14. Example 14-14. A switch construct <script> switch (page) { case "Home": document.write("You selected Home") break case "About": document.write("You selected About") break case "News": read more..

  • Page - 374

    The ? Operator The ternary operator (?), combined with the : character, provides a quick way of doing if...else tests. With it you can write an expression to evaluate, and then fol‐ low it with a ? symbol and the code to execute if the expression is true . After that, place a : and the code to execute if the expression evaluates to false . Example 14-16 read more..

  • Page - 375

    document.write("Counter: " + counter + "<br>") ++counter } </script> This script outputs the following: Counter: 0 Counter: 1 Counter: 2 Counter: 3 Counter: 4 If the variable counter were not incremented within the loop, it is quite possible that some browsers could become unresponsive due to a never-ending loop, and the page may not even be read more..

  • Page - 376

    for Loops A for loop combines the best of all worlds into a single looping construct that allows you to pass three parameters for each statement: • An initialization expression • A condition expression • A modification expression These are separated by semicolons, like this: for ( expr1 ; expr2 ; expr3) . At the start of the first iteration of the loop, the read more..

  • Page - 377

    Example 14-20. Using the break command in a for loop <script> haystack = new Array() haystack[17] = "Needle" for (j = 0 ; j < 20 ; ++j) { if (haystack[j] == "Needle") { document.write("<br>- Found at location " + j) break } else document.write(j + ", read more..

  • Page - 378

    Notice how the second document.write call does not have to be enclosed in an else statement (as it did before), because the continue command will skip it if a match has been found. The output from this script is as follows: 0, 1, 2, 3, - Found at location 4 5, 6, 7, 8, 9, 10, - Found at location 11 12, 13, 14, 15, 16, - Found at location 17 18, 19, Explicit read more..

  • Page - 379

    4. What is the best way to force your own operator precedence? 5. When would you use the === (identity) operator? 6. What are the simplest two forms of expressions? 7. Name the three conditional statement types. 8. How do if and while statements interpret conditional expressions of different data types? 9. Why is a for loop more powerful than a while loop? 10. read more..

  • Page - 380

    read more..

  • Page - 381

    CHAPTER 15 JavaScript Functions, Objects, and Arrays Just like PHP, JavaScript offers access to functions and objects. In fact, JavaScript is actually based on objects, because—as you’ve seen—it has to access the DOM, which makes every element of an HTML document available to manipulate as an object. The usage and syntax are also quite similar to those of PHP, so you read more..

  • Page - 382

    • One or more parameters, separated by commas, are optional (indicated by the square brackets, which are not part of the function syntax). Function names are case-sensitive, so all of the following strings refer to different functions: getInput , GETINPUT , and getinput . In JavaScript there is a general naming convention for functions: the first letter of each word in a name read more..

  • Page - 383

    All of this is fine, but what if you wanted to pass more than five items to the function? Also, reusing the document.write call multiple times instead of employing a loop is wasteful programming. Luckily, the arguments array gives you the flexibility to han‐ dle a variable number of arguments. Example 15-2 shows how you can use it to rewrite the example in a much read more..

  • Page - 384

    return s.substr(0, s.length-1) } </script> When called with the parameters the , DALLAS , and CowBoys , for example, the func‐ tion returns the string The Dallas Cowboys . Let’s walk through the function. The function first initializes the temporary (and local) variable s to the empty string. Then a for loop iterates through each of the passed parameters, read more..

  • Page - 385

    This practice is often referred to as method chaining. So, for example, if the string mixedCASE is passed to the example expression, it will go through the following trans‐ formations: mixedCASE ixedCASE ixedcase One final reminder: the s variable created inside the function is local, and therefore cannot be accessed outside the function. By returning s in the return read more..

  • Page - 386

    As for the fixNames function, it’s almost identical to Example 15-3, except that the variable s is now an array, and after each word has been processed, it is stored as an element of this array, which is returned by the return statement. This function enables the extraction of individual parameters from its returned val‐ ues, like the following (the output from read more..

  • Page - 387

    The function is different from other functions we’ve seen so far in two ways: • It refers to an object named this . When the program creates an instance of User by running this function, this refers to the instance being created. The same function can be called over and over with different arguments, and will create a new User each time with different values for read more..

  • Page - 388

    details = new User() and then populate it later, like this: details.forename = "Wolfgang" details.username = "w.a.mozart" details.password = "composer" You can also add new properties to an object, like this: details.greeting = "Hello" You can verify that adding such new properties works with the following statement: document.write(details.greeting) Accessing Objects read more..

  • Page - 389

    Example 15-7. Declaring a class using the prototype keyword for a method <script> function User(forename, username, password) { this.forename = forename this.username = username this.password = password User.prototype.showUser = function() { document.write("Forename: " + this.forename + "<br>") read more..

  • Page - 390

    Static methods and properties When reading about PHP objects, you learned that classes can have static properties and methods as well as properties and methods associated with a particular instance of a class. JavaScript also supports static properties and methods, which you can con‐ veniently store and retrieve from the class’s prototype . Thus, the following state‐ ments read more..

  • Page - 391

    The result is that when either of these expressions matches, the match is replaced with the empty string, thus returning a trimmed version of the string without any leading or trailing whitespace. JavaScript Arrays Array handling in JavaScript is very similar to PHP, although the syntax is a little dif‐ ferent. Nevertheless, given all you have already learned about arrays, read more..

  • Page - 392

    Example 15-8. Creating, building, and printing an array <script> numbers = [] numbers.push("One") numbers.push("Two") numbers.push("Three") for (j = 0 ; j < numbers.length ; ++j) document.write("Element " + j + " = " + numbers[j] + "<br>") </script> The output from this script is as follows: Element 0 = read more..

  • Page - 393

    To verify that the array has been correctly created and populated, I have used another kind of for loop using the in keyword. This creates a new variable to use only within the array (ball, in this example) and iterates through all elements of the array to the right of the in keyword (balls, in this example). The loop acts on each element of balls , placing read more..

  • Page - 394

    In this example, the lowercase letters represent black pieces, and the uppercase white. A pair of nested for loops walks through the array and displays its contents. The outer loop contains two statements, so curly braces enclose them. The inner loop then processes each square in a row, outputting the character at location [j][k] , fol‐ lowed by a space (to square up read more..

  • Page - 395

    forEach (for non-IE browsers) The forEach method in JavaScript is another way of achieving functionality similar to the PHP foreach keyword, but only for browsers other than Internet Explorer. To use it, you pass it the name of a function, which will be called for each element within the array. Example 15-11 shows how. Example 15-11. Using the forEach method read more..

  • Page - 396

    Example 15-12. Using the join method <script> pets = ["Cat", "Dog", "Rabbit", "Hamster"] document.write(pets.join() + "<br>") document.write(pets.join(' ') + "<br>") document.write(pets.join(' : ') + "<br>") </script> Without a parameter, join uses a comma to separate the elements; read more..

  • Page - 397

    Example 15-14. Using push and pop inside and outside of a loop <script> numbers = [] for (j = 0 ; j < 3 ; ++j) { numbers.push(j); document.write("Pushed " + j + "<br>") } // Perform some other activity here document.write("<br>") document.write("Popped " + numbers.pop() + "<br>") read more..

  • Page - 398

    Example 15-16. Using the sort method <script> // Alphabetical sort sports = ["Football", "Tennis", "Baseball", "Hockey"] sports.sort() document.write(sports + "<br>") // Reverse alphabetical sort sports = ["Football", "Tennis", "Baseball", "Hockey"] sports.sort().reverse() document.write(sports + read more..

  • Page - 399

    Questions 1. Are JavaScript functions and variable names case-sensitive or -insensitive? 2. How can you write a function that accepts and processes an unlimited number of parameters? 3. Name a way to return multiple values from a function. 4. When you’re defining a class, what keyword do you use to refer to the current object? 5. Do all the methods of a class have to be read more..

  • Page - 400

    read more..

  • Page - 401

    CHAPTER 16 JavaScript and PHP Validation and Error Handling With your solid foundation in both PHP and JavaScript, it’s time to bring these tech‐ nologies together to create web forms that are as user-friendly as possible. We’ll be using PHP to create the forms and JavaScript to perform client-side valida‐ tion to ensure that the data is as complete and correct as it read more..

  • Page - 402

    The validate.html Document (Part 1) Let’s begin with a general sign-up form, common on most sites that offer member‐ ships or registered users. The inputs requested will be forename, surname, username, password, age, and email address. Example 16-1 provides a good template for such a form. Example 16-1. A form with JavaScript validation (part 1) <!DOCTYPE html> read more..

  • Page - 403

    <tr><td colspan="2" align="center"><input type="submit" value="Signup"></td></tr> </form> </table> </body> </html> As it stands, this form will display correctly but will not self-validate, because the main validation functions have not yet been added. Even so, read more..

  • Page - 404

    The second part of this example features the HTML for the form with each field and its name placed within its own row of a table. This is pretty straightforward HTML, with the exception of the onSubmit="return validate(this)" statement within the opening <form> tag. Using onSubmit , you can cause a function of your choice to be called when a form is submitted. read more..

  • Page - 405

    else if (field.length < 6) return "Passwords must be at least 6 characters.\n" else if (!/[a-z]/.test(field) || ! /[A-Z]/.test(field) || !/[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\n" return "" } function validateAge(field) { if (isNaN(field)) return "No Age was entered.\n" read more..

  • Page - 406

    limit the characters allowed in either of the name fields to allow for possibilities such as non-English and accented characters. Validating the username The validateUsername function is a little more interesting, because it has a more complicated job. It has to allow through only the characters a-z , A-Z , 0-9 , _ and - , and ensure that usernames are at least five read more..

  • Page - 407

    If those two checks are satisfied, the test function is called to see whether any disal‐ lowed characters appear in the field. If any of these tests fail, an error message is returned. The allowed characters in an email address are uppercase and lowercase let‐ ters, numbers, and the _ , - , period, and @ characters, as detailed in the regular expres‐ sion passed read more..

  • Page - 408

    Matching Through Metacharacters Every regular expression must be enclosed in slashes. Within these slashes, certain characters have special meanings; they are called metacharacters. For instance, an asterisk (*) has a meaning similar to what you have seen if you use a shell or Win‐ dows command prompt (but not quite the same). An asterisk means, “The text you’re trying to read more..

  • Page - 409

    <a href="www.mozilla.org"> Unfortunately, the plus sign keeps on matching up to the last > on the line, so you might end up with this: <h1><b>Introduction</b></h1> A lot more than one tag! I’ll show a better solution later in this section. If you use the dot on its own between the angle brackets, without following it with either a + or read more..

  • Page - 410

    The parentheses mean “treat this as a group when you apply something such as a plus sign.” 1,00,000 and 1,000,00 won’t match because the text must have a 1 followed by one or more complete groups of a comma followed by three zeros. The space after the + character indicates that the match must end when a space is encountered. Without it, 1,000,00 would read more..

  • Page - 411

    (The name of the company officially contains an exclamation point!) You could do it as follows: /Yahoo[^!]/ The character class consists of a single character—an exclamation point—but it is inverted by the preceding ^ . This is actually not a great solution to the problem—for instance, it fails if Yahoo is at the end of the line, because then it’s not followed by read more..

  • Page - 412

    + Allows any number of characters to match the previous [^>] , as long as there is at least one of them. > Closing bracket of an HTML tag. This is matched exactly. / Closing slash that indicates the end of the regular expression. Another solution to the problem of matching HTML tags is to use a nongreedy operation. By default, pattern matching is greedy, returning the read more..

  • Page - 413

    a-z Represents any lowercase letter. A-Z Represents any uppercase letter. 0-9 Represents any digit. _ An underscore. - A dash. ] Closing bracket that ends a character class. / Closing slash that indicates the end of the regular expression. There are two other important metacharacters. They “anchor” a regular expression by requiring that it appear in a particular place. If a caret (^) read more..

  • Page - 414

    Table 16-1. Regular expression metacharacters Metacharacters Description / Begins and ends the regular expression . Matches any single character except the newline element* Matches element zero or more times element+ Matches element one or more times element? Matches element zero or one times [ characters] Matches a character out of those read more..

  • Page - 415

    To give you more ideas of how this all works, Table 16-2 shows a range of expressions and the patterns they match. Table 16-2. Some example regular expressions Example Matches r The first r in The quick brown rec[ei][ei]ve Either of receive or recieve (but also receeve or reciive) rec[ei]{2}ve Either of receive or recieve (but also receeve read more..

  • Page - 416

    Using Regular Expressions in JavaScript In JavaScript, you will use regular expressions mostly in two methods: test (which you have already seen) and replace . Whereas test just tells you whether its argu‐ ment matches the regular expression, replace takes a second parameter: the string to replace the text that matches. Like most functions, replace generates a new string read more..

  • Page - 417

    $n = preg_match_all("/cats/i", "Cats are strange. I like cats.", $match); echo "$n Matches: "; for ($j=0 ; $j < $n ; ++$j) echo $match[0][$j]." "; As before, $match is passed to the function and the element $match[0] is assigned the matches made, but this time as a subarray. To display the subarray, this example iter‐ ates through it with a read more..

  • Page - 418

    if (isset($_POST['email'])) $email = fix_string($_POST['email']); $fail = validate_forename($forename); $fail .= validate_surname($surname); $fail .= validate_username($username); $fail .= validate_password($password); $fail .= validate_age($age); $fail .= validate_email($email); echo "<!DOCTYPE html>\n<html><head><title>An Example read more..

  • Page - 419

    function validateSurname(field) { return (field == "") ? "No Surname was entered.\n" : "" } function validateUsername(field) { if (field == "") return "No Username was entered.\n" else if (field.length < 5) return read more..

  • Page - 420

    in your form: <p><font color=red size=1><i>$fail</i></font></p> </td></tr> <form method="post" action="adduser.php" onSubmit="return validate(this)"> <tr><td>Forename</td> <td><input type="text" maxlength="32" read more..

  • Page - 421

    else if (!preg_match("/[a-z]/", $field) || !preg_match("/[A-Z]/", $field) || !preg_match("/[0-9]/", $field)) return "Passwords require 1 each of a-z, A-Z and 0-9<br>"; return ""; } function validate_age($field) { if ($field == "") return read more..

  • Page - 422

    Figure 16-5. The form as represented after PHP validation fails I have put the PHP section of this code (and changes to the HTML section) in a bold typeface so that you can more clearly see the difference between this and Example 16-1 and Example 16-2. If you browsed through this example (or typed it or downloaded it from the http:// lpmj.net website), you’ll read more..

  • Page - 423

    In the real world, you probably wouldn’t start with an HTML form such as the one in Example 16-1. Instead, you’d be more likely to go straight ahead and write the PHP program in Example 16-3, which incorporates all the HTML. And, of course, you’d also need to make a minor tweak for the case when it’s the first time the pro‐ gram is called up, to read more..

  • Page - 424

    read more..

  • Page - 425

    CHAPTER 17 Using Ajax The term Ajax was first coined in 2005. It stands for Asynchronous JavaScript and XML, which, in simple terms, means using a set of methods built in to JavaScript to transfer data between the browser and a server in the background. An excellent example of this technology is Google Maps (see Figure 17-1), in which new sections of a map are read more..

  • Page - 426

    Figure 17-1. Google Maps is an excellent example of Ajax in action Using XMLHttpRequest Because of the differences between browser implementations of XMLHttpRequest , you must create a special function in order to ensure that your code will work on all major browsers. To do this, you must understand the three ways of creating an XMLHttpRequest object: • IE 5: request read more..

  • Page - 427

    Example 17-1. A cross-browser Ajax function <script> function ajaxRequest() { try // Non IE Browser? { // Yes var request = new XMLHttpRequest() } catch(e1) { try // IE 6+? { // Yes request = new ActiveXObject("Msxml2.XMLHTTP") } read more..

  • Page - 428

    Table 17-1. An XMLHttpRequest object’s properties Property Description onreadystatechange Specifies an event-handling function to be called whenever the readyState property of an object changes. readyState An integer property that reports on the status of a request. It can have any of these values: 0 = Uninitialized, 1 = Loading, read more..

  • Page - 429

    Example 17-2. urlpost.html <!DOCTYPE html> <html> <head> <title>AJAX Example</title> </head> <body style='text-align:center'> <h1>Loading a web page into a DIV</h1> <div id='info'>This sentence will be replaced</div> <script> params = "url=amazon.com/gp/aw" request = new read more..

  • Page - 430

    catch(e2) { try { request = new ActiveXObject("Microsoft.XMLHTTP") } catch(e3) { request = false } read more..

  • Page - 431

    } } If you wish to use a separate, named function, the syntax is slightly different: request.onreadystatechange = ajaxCallback function ajaxCallback() { if (this.readyState == 4) { // do something } } Looking at Table 17-1, you’ll see that readyState can have five values. But only one concerns us: value 4 , which represents a completed Ajax call. read more..

  • Page - 432

    The server half of the Ajax process Now we get to the PHP half of the equation, which you can see in Example 17-3. Type it and save it as urlpost.php. Example 17-3. urlpost.php <?php // urlpost.php if (isset($_POST['url'])) { echo file_get_contents('http://' . SanitizeString($_POST['url'])); } function SanitizeString($var) { $var = strip_tags($var); read more..

  • Page - 433

    Figure 17-2. The Amazon mobile website has been loaded into a DIV Not only have we succeeded in making an Ajax call and having a response returned to JavaScript, but we’ve also harnessed the power of PHP to enable the merging in of a totally unrelated web object. Incidentally, if we had tried to find a way to fetch the Amazon mobile web page directly via Ajax read more..

  • Page - 434

    Example 17-4 shows how you would achieve the same result as with Example 17-2, but using an Ajax Get request instead of Post. Example 17-4. urlget.html <!DOCTYPE html> <html> <head> <title>AJAX Example</title> </head> <body style='text-align:center'> <h1>Loading a web page into a DIV</h1> <div id='info'>This sentence read more..

  • Page - 435

    { try { request = new ActiveXObject("Microsoft.XMLHTTP") } catch(e3) { request = false } } read more..

  • Page - 436

    } ?> All that’s different between this and Example 17-3 is that the references to $_POST have been replaced with $_GET . The end result of calling up urlget.html in your browser is identical to loading in urlpost.html. Sending XML Requests Although the objects we’ve been creating are called XMLHttpRequest objects, so far we have made absolutely no use of XML. read more..

  • Page - 437

    <title>AJAX Example</title> </head> <body> <h1>Loading a web page into a DIV</h1> <div id='info'>This sentence will be replaced</div> <script> nocache = "&nocache=" + Math.random() * 1000000 url = "rss.news.yahoo.com/rss/topstories" out = read more..

  • Page - 438

    try { request = new ActiveXObject("Microsoft.XMLHTTP") } catch(e3) { request = false } } } read more..

  • Page - 439

    </item> <item> <title>Headline 2</title> <guid>http://website.com/headline2</guid> <description>The 2nd headline</description> </item> </channel> </rss> Figure 17-3. The DOM tree of Example 17-8 Therefore, using the getElementsByTagName method, you can quickly extract the val‐ ues read more..

  • Page - 440

    Figure 17-4. Fetching a Yahoo! XML news feed via Ajax As with all form data, you can use either the Post or the Get method when requesting XML data; your choice will make little difference to the result. Why use XML? You may ask why you would use XML other than for fetching XML documents such as RSS feeds. Well, the simple answer is that you don’t have to, read more..

  • Page - 441

    Using Frameworks for Ajax Now that you know how to code your own Ajax routines, you might like to investi‐ gate some of the free frameworks that are available to make it even easier, and which offer many more advanced features. In particular, I would suggest you check out jQuery, probably the most commonly used framework, and which I introduce in Chapter 21. In the read more..

  • Page - 442

    read more..

  • Page - 443

    CHAPTER 18 Introduction to CSS Using CSS (Cascading Style Sheets), you can apply styles to your web pages to make them look exactly how you want. This works because CSS is connected to the DOM (Document Object Model), which I explained in Chapter 13. With CSS and its integration with the DOM, you can quickly and easily restyle any element. For example, if you don’t read more..

  • Page - 444

    <h1>Hello there</h1> </body> </html> Figure 18-1. Styling a tag, with the original style shown in the inset Importing a Style Sheet When you wish to style a whole site, rather than a single page, a better way to manage style sheets is to move them completely out of your web pages to separate files, and then import the ones read more..

  • Page - 445

    Just as you can use multiple @import directives within your CSS to include multiple external style sheets, you can also use as many <link> elements as you like in your HTML. Embedded Style Settings There’s also nothing stopping you from individually setting or overriding certain styles for the current page on a case-by-case basis by inserting style declarations directly read more..

  • Page - 446

    Instead of the # symbol, which is reserved for IDs, class statements are prefaced with a . (period). Using Semicolons In CSS, semicolons are used to separate multiple CSS statements on the same line. But if there is only one statement in a rule (or in an inline style setting within an HTML tag), you can omit the semicolon, as you can for the final statement in a read more..

  • Page - 447

    Or you can space out the assignments a little more, so that they line up below each other in a column at the colons, like this: h1 { font-size:240%; color :blue; } This way, you can easily see where each new set of rules begins, because the selector is always in the first column, and the assignments that follow are neatly lined up with all property read more..

  • Page - 448

    Or you can extend a comment over many lines, like this: /* A Multi line comment */ When using multiline comments, note that you cannot nest single- line (or any other) comments within them. Doing so can lead to unpredictable errors. Style Types There are a number of different style types, ranging from the default styles set up by your browser read more..

  • Page - 449

    Figure 18-2. Applying a user style to Internet Explorer If a user style is assigned that has already been defined as a browser default, it will then override the browser’s default setting. Any styles not defined in a user style sheet will retain their default values as set up in the browser. External Style Sheets The next types of styles are those assigned in an read more..

  • Page - 450

    Inline Styles Finally, inline styles are where you assign a property directly to an element. They have the highest precedence of any style type, and are used like this: <a href="http://google.com" style="color:green;">Visit Google</a> In this example, the link specified will be displayed in green, regardless of any default or other color settings applied by any read more..

  • Page - 451

    <!DOCTYPE html> <html> <head> <style> ol ol { list-style-type:lower-alpha; } </style> </head> <body> <ol> <li>One</li> <li>Two</li> <li>Three <ol> <li>One</li> read more..

  • Page - 452

    For a practical example, suppose you wish to make bold only those <li> elements that are direct children of <ol> elements. You can achieve this as follows, where the <li> elements that are direct children of <ul> elements are not made bold: <!DOCTYPE html> <html> <head> <style> ol > li { font-weight:bold; } read more..

  • Page - 453

    #myid { text-decoration:underline; } However, you can ensure that CSS applies the rule to both occurrences, like this: span#myid { text-decoration:underline; } div#myid { text-decoration:underline; } Or more succinctly, like this (see “Selecting by Group” on page 425): span#myid, div#myid { text-decoration:underline; } I don’t recommend using this form of selection because any Java‐ read more..

  • Page - 454

    reference attributes in the following manner, which sets all elements with the attribute type="submit" to a width of 100 pixels: [type="submit"] { width:100px; } If you wish to narrow down the scope of the selector to, for example, only form input elements with that attribute type, you could use the following rule instead: form input[type="submit"] { width:100px; } read more..

  • Page - 455

    4. Apply the styles within the { and } characters to the objects returned in step 3. The net result of this is that the green border is applied only to paragraphs that are grandchildren (or great-grandchildren, and so on) of the main element. Selecting by Group Using CSS, you can apply a rule to more than one element, class, or any other type of selector at the read more..

  • Page - 456

    Style Sheet Creators There are three main types of style sheet supported by all modern browsers. In order of precedence from high to low, they are as follows: 1. Those created by a document’s author 2. Those created by the user 3. Those created by the browser These three sets of style sheets are processed in reverse order. First, the defaults in the web browser are read more..

  • Page - 457

    1. Referencing by individual ID or attribute selector 2. Referencing in groups by class 3. Referencing by element tags (such as <p> or <b> ) Selectors are processed according to the number and types of elements affected by a rule, which is a little different from the previous two methods for resolving conflicts. This is because rules do not have to apply only to read more..

  • Page - 458

    have greater precedence. Where two rules share the same value, the most recently applied one wins. Using a different number base Where there are more than nine of a type in a number, you have to work in a higher number base. For example, you can’t convert the compound number [11,7,19] to decimal by simply concatenating the three parts. Instead, you can convert the read more..

  • Page - 459

    User style sheets can be created for specifying default browser styles, and they may use the !important declaration, in which case the user’s style setting will take precedence over the same proper‐ ties specified in the current web page. However, on very old brows‐ ers using CSS 1, this feature isn’t supported. The Difference Between Div and Span Elements Both read more..

  • Page - 460

    to the next line of the browser</span> </body> </html> Figure 18-4 shows what this example looks like in a web browser. Although it is printed only in shades of gray in this book, the figure clearly shows how <div> ele‐ ments extend to the righthand edge of a browser, and force the following content to appear at the start of the read more..

  • Page - 461

    Measurements CSS supports an impressive range of units of measurement, enabling you to tailor your web pages precisely to specific values, or by relative dimensions. The ones I gen‐ erally use (and believe you will also find the most useful) are pixels, points, ems, and percent, but here’s the complete list: Pixels The size of a pixel varies according to the dimensions and read more..

  • Page - 462

    used as a good approximation for helping to set the width of a box that will con‐ tain some text. For example: .classname { width:20ex; } Percent This unit is related to the em in that it is exactly 100 times greater (when used on a font). Whereas 1 em equals the current font size, the same size is 100 in percent. When not relating to a font, this unit is read more..

  • Page - 463

    font-family The font-family property assigns the font to use. It also supports listing a variety of fonts in order of preference from left to right, so that styling can fall back gracefully when the user doesn’t have the preferred font installed. For example, to set the default font for paragraphs, you might use a CSS rule such as this: p { font-family:Verdana, Arial, read more..

  • Page - 464

    .normal { font-style:normal; } .italic { font-style:italic; } .oblique { font-style:oblique; } font-size As described in the earlier section on measurements, there are a large number of ways you can change a font’s size. But these all boil down to two main types: fixed and rela‐ tive. A fixed setting looks like the following rule, which sets the default paragraph font read more..

  • Page - 465

    .bold { font-weight:bold; } Managing Text Styles Regardless of the font in use, you can further modify the way text displays by altering its decoration, spacing, and alignment. There is a crossover between the text and font properties, though, in that effects such as italics or bold text are achieved via the font-style and font-weight properties, while others such as read more..

  • Page - 466

    p { line-height :125%; word-spacing :30px; letter-spacing:3px; } Alignment There are four types of text alignment available in CSS: left , right , center , and jus tify . In the following rule, default paragraph text is set to full justification: p { text-align:justify; } Transformation There are four properties available for transforming your text: none , capitalize , read more..

  • Page - 467

    Figure 18-9. Indenting, uppercase, and spacing rules being applied CSS Colors You can apply colors to the foreground and background of text and objects by using the color and background-color properties (or by supplying a single argument to the background property). The colors specified can be one of the named colors (such as red or blue ), colors created from read more..

  • Page - 468

    If you prefer not to work in ranges of 256 levels per color, you can use percentages in the rgb function instead, with values from 0 to 100 ranging from the lowest (0) amount of a primary color, through to the highest (100), like this: rgb(58%, 95%, 74%) . You can also use floating-point values for even finer color control, like this: rgb(23.4%, 67.6%, 15.5%) . Short read more..

  • Page - 469

    </head> <body> <div class='orangegrad'>Black text<br> on an orange<br>linear gradient</div> </body> </html> Figure 18-10. A solid background color, a linear gradient, and a radial gradient As shown in the preceding example, many CSS rules require browser-specific prefixes such as -moz- , -webkit- , -o- , and -ms- (for read more..

  • Page - 470

    Absolute Positioning An element with absolute positioning is removed from the document, and any other elements that are capable will flow into its released space. You can then position the object anywhere you like within the document by using the top , right , bottom , and left properties. It will then rest on top of (or behind) other elements. So, for example, to move read more..

  • Page - 471

    Figure 18-11. Using different positioning values When this is done, it is immediately obvious that the element with fixed positioning remains in place even through scrolling. You can also see that the element with abso‐ lute positioning is located exactly at 100 pixels down, with 0 horizontal offset, while the element with relative positioning is actually moved up by 8 read more..

  • Page - 472

    } </style> </head> <body> <br><br><br><br><br> <div id='object1'>Absolute Positioning</div> <div id='object2'>Relative Positioning</div> <div id='object3'>Fixed Positioning</div> </body> </html> In the figure, the element with fixed positioning initially lines up read more..

  • Page - 473

    a:hover { color :white; background:red; } Here I have used the background property with a single argument, instead of the longer background-color property. The active pseudoclass is also dynamic in that it effects a change to a link during the time between the mouse button being clicked and released, as with this rule, which changes the link color to dark read more..

  • Page - 474

    Figure 18-12. Pseudoclasses applied to a selection of elements Other pseudoclasses are also available, and you can get more information on them at http://tinyurl.com/pseudoclasses. Beware of applying the focus pseudoclass to the universal selector, * , as shown in this example; Internet Explorer regards an unfo‐ cused document as having focus applied to the entire web page, and read more..

  • Page - 475

    The order in which the properties are placed in a shorthand rule can be important, and misplacing them is a common way to get unexpected results. Since there are far too many to detail in this chapter, if you wish to use shorthand CSS, you will need to look up the default properties and their order of application using a CSS manual or search engine. To get you read more..

  • Page - 476

    margin:1px 2px; /* Set top to 1 pixel, left and right to 2, and bottom to 3 */ margin:1px 2px 3px; /* Set top to 1 pixel, right to 2, bottom to 3, and left to 4 */ margin:1px 2px 3px 4px; Figure 18-13 shows Example 18-6 loaded into a browser, with the margin property rule (highlighted in bold) applied to a square element that has been placed inside a table read more..

  • Page - 477

    Figure 18-13. The outer table expands according to the margin widths Applying Borders The border level of the box model is similar to the margin except that there is no col‐ lapsing. It is the next level as we move into the box model. The main properties used to modify borders are border , border-left , border-top , border-right , and border-bottom , and each read more..

  • Page - 478

    Figure 18-14. Applying long- and shorthand border rule values The final element, under the previous ones, doesn’t use the shorthand rules; instead, it has each of the border widths set separately. As you can see, it takes a lot more typ‐ ing to achieve the same result. Adjusting Padding The deepest of the box model levels (other than the contents of an element) is read more..

  • Page - 479

    no dimensions so it will simply wrap as closely around the text as it can. As a conse‐ quence, there is padding of 10 pixels above the inner element, 20 pixels to its right, 30 pixels below it, and 40 pixels to its left. Example 18-7. Applying padding <!DOCTYPE html> <html> <head> <title>Padding</title> <style> read more..

  • Page - 480

    Object Contents Deep within the box model levels, at its center, lies an element that can be styled in all the ways discussed in this chapter, and which can (and usually will) contain further subelements, which in turn may contain sub-subelements, and so on, each with its own styling and box model settings. Questions 1. Which directive do you use to import one style sheet read more..

  • Page - 481

    CHAPTER 19 Advanced CSS with CSS3 The first implementation of CSS was drawn up in 1996, was released in 1999, and has been supported by all browser releases since 2001. The standard for this version, CSS1, was revised in 2008. Beginning in 1998, developers began drawing up the sec‐ ond specification, CSS2; its standard was completed in 2007 and revised in 2009. Development read more..

  • Page - 482

    Table 19-1. CSS selectors, pseudoclasses, and pseudoelements Selector type Example Universal selector * { color:#555; } Type selectors b { color:red; } Class selectors .classname { color:blue; } ID selectors #idname { background:cyan; } Descendant selectors span em { color:green; } Child selectors div > em { background:lime; } Adjacent sibling selectors i read more..

  • Page - 483

    For example, the following will match: <img src='photo.png'> But this will not: <img src='snapshot.jpg'> The * operator To match any substring anywhere in the attribute, you can use a selector such as the following to find any links on a page that have the string google anywhere within them: a[href*='google'] For example, the HTML segment <a href='http://google.com'> will read more..

  • Page - 484

    To accomplish these, both properties support the following values: border-box Refers to the outer edge of the border padding-box Refers to the outer edge of the padding area content-box Refers to the outer edge of the content area The background-clip Property The background-clip property specifies whether the background should be ignored (clipped) if it appears within either the border read more..

  • Page - 485

    Figure 19-1. Different ways of combining CSS3 background properties In the first row, the inner box (an image file that has been loaded into the top left of the element, with repeating disabled) is allowed to display anywhere in the element. You can also clearly see it displayed in the border area of the first box because the border has been set to dotted. In the read more..

  • Page - 486

    Then, in the third row, both the background shading and the image have been clip‐ ped to display only within the inner content area of each element (shown inside a light-colored, dotted box), using a background-clip property of content-box . The background-origin Property With the background-origin property, you can control where a background image will be located by specifying read more..

  • Page - 487

    Using the auto Value If you wish to scale only one dimension of a background image, and then have the other one scale automatically to retain the same proportions, you can use the value auto for the other dimension, like this: background-size:100px auto; This sets the width to 100 pixels, and the height to a value proportionate to the increase or decrease in width. read more..

  • Page - 488

    Example 19-1. Using multiple images in a background <!DOCTYPE html> <html> <!-- backgroundimages.html --> <head> <title>CSS3 Multiple Backgrounds Example</title> <style> .border { font-family:'Times New Roman'; font-style :italic; font-size :170%; text-align :center; read more..

  • Page - 489

    CSS3 Borders CSS3 also brings a lot more flexibility to the way borders can be presented, by allow‐ ing you to independently change the colors of all four border edges, to display images for the edges and corners, to provide a radius value for applying rounded corners to borders, and to place box shadows underneath elements. The border-color Property There are two ways you read more..

  • Page - 490

    text-align :center; padding :10px; width :380px; height :75px; border :10px solid #006; } .b1 { -moz-border-radius :40px; -webkit-border-radius:40px; read more..

  • Page - 491

    border-radius:40px 40px 20px 20px; </div> <div class='box b3'> border-top-left-radius &nbsp;&nbsp;&nbsp;:20px;<br> border-top-right-radius &nbsp;&nbsp;:40px;<br> border-bottom-left-radius :60px;<br> border-bottom-right-radius:80px; </div> <div class='box b4'> read more..

  • Page - 492

    So, for example, to create a rounded border with a radius of 19 pixels, you could sim‐ ply use the following declaration: border-radius:20px; Although most browsers will work fine with border radius proper‐ ties (including IE), some current (and many older) versions of the major browsers use different property names. So, if you wish to support them all, you will need to also read more..

  • Page - 493

    Figure 19-4. A box shadow displayed under an element You must use the WebKit and Mozilla prefixes to this property for those browsers. Element Overflow In CSS2, you can indicate what to do when one element is too large to be fully con‐ tained by its parent by setting the overflow property to hidden , visible , scroll , or auto . But with CSS3, you can now read more..

  • Page - 494

    Figure 19-5. Flowing text in multiple columns Example 19-3. Using CSS to create multiple columns <!DOCTYPE html> <html> <!-- multiplecolumns.html --> <head> <title>Multiple Columns</title> <style> .columns { text-align :justify; font-size :16pt; read more..

  • Page - 495

    To fright the souls of fearful adversaries, He capers nimbly in a lady's chamber To the lascivious pleasing of a lute. </div> </body> </html> Within the .columns class, the first two lines simply tell the browser to right-justify the text and to set it to a font size of 16pt . These declarations aren’t read more..

  • Page - 496

    All that’s left then is for you to decide how bright you want the color to be, by choos‐ ing a luminance value of between 0 and 100 percent. A value of 50% for the lumi‐ nance gives the fullest, brightest color; decreasing the value (down to a minimum of 0%) darkens the color until it displays as black; and increasing the value (up to a max‐ imum of 100%) read more..

  • Page - 497

    But even better than that, you don’t even have to think in amounts of up to 256 any‐ more, because you can specify percentage values, like this: color:rgb(100%, 100%, 0); In fact, you can now get very close to a desired color by simply thinking about its primary colors. For example, green and blue make cyan, so to create a color close to cyan, but with more blue read more..

  • Page - 498

    both horizontally and vertically, and displays the shadow in dark gray, with a blurring of 4 pixels: text-shadow:3px 3px 4px #444; The result of this declaration looks like Figure 19-6, and works in all recent versions of all major browsers (but not IE9 or lower). Figure 19-6. Applying a shadow to text The text-overflow Property When using any of the CSS overflow read more..

  • Page - 499

    The word-wrap Property When you have a really long word that is wider than the element containing it, it will either overflow or be truncated. But as an alternative to using the text-overflow property and truncating text, you can use the word-wrap property with a value of break-word to wrap long lines, like this: word-wrap:break-word; For example, in Figure 19-9 the word read more..

  • Page - 500

    To tell the browser the type of font, you can use the format function, like this (for OpenType fonts): @font-face { font-family:FontName; src:url('FontName.otf') format('opentype'); } Or this for TrueType fonts: @font-face { font-family:FontName; src:url('FontName.ttf') format('truetype'); } However, because Microsoft Internet Explorer accepts only EOT fonts, it ignores @font-face read more..

  • Page - 501

    Figure 19-11. It’s easy to include Google’s web fonts To show you how easy it is to use one of these fonts, here’s how you load a Google font (in this case, Lobster) into your HTML for use in <h1> headings: <!DOCTYPE html> <html> <head> <style> h1 { font-family:'Lobster', arial, serif; } </style> read more..

  • Page - 502

    Transformations Using transformations, you can skew, rotate, stretch, and squash elements in any of up to three dimensions (yes, 3D is supported, but only in WebKit-based browsers for now). This makes it easy to create great effects by stepping out of the uniform rectan‐ gular layout of <div> and other elements, because now they can be shown at a variety of angles read more..

  • Page - 503

    Figure 19-12. An object before and after transformation 3D Transformations You can also transform objects in three dimensions by using the following CSS3 3D transformation features: perspective Releases an element from 2D space and creates a third dimension within which it can move transform-origin Sets the location at which all lines converge to a single point translate3d Moves an read more..

  • Page - 504

    Figure 19-13. A figure rotated in 3D space For more information, please refer to the tutorial at http://tinyurl.com/3dcsstransforms (or use the direct URL http://24ways.org/2010/intro-to-css-3d-transforms). Transitions Also appearing on all the latest versions of the major browsers (including Internet Explorer 10, but not lower versions) is a dynamic new feature called transitions. These read more..

  • Page - 505

    Or, if you want absolutely everything about an element to transition (including col‐ ors), use the value all , like this: transition-property:all; Transition Duration The transition-duration property requires a value of 0 seconds or greater, like the following, which specifies that the transition should take 1.25 seconds to complete: transition-duration:1.25s; Transition Delay If the read more..

  • Page - 506

    For example, following are the declarations used to create the preceding five transi‐ tion types, illustrating how you can easily create your own: transition-timing-function:cubic-bezier(0.25, 0.1, 0.25, 1); transition-timing-function:cubic-bezier(0, 0, 1, 1); transition-timing-function:cubic-bezier(0.42, 0, 1, 1); transition-timing-function:cubic-bezier(0, 0, 0.58, 1); read more..

  • Page - 507

    #square:hover { background :yellow; -moz-transform :rotate(180deg); -webkit-transform :rotate(180deg); -o-transform :rotate(180deg); -ms-transform :rotate(180deg); transform :rotate(180deg); } read more..

  • Page - 508

    3. With which property can you specify the radius of a border? 4. How can you flow text over multiple columns? 5. Name the four functions with which you can specify CSS colors. 6. How would you create a gray text shadow under some text, offset diagonally to the bottom right by 5 pixels, with a blurring of 3 pixels? 7. How can you indicate with an ellipsis that read more..

  • Page - 509

    CHAPTER 20 Accessing CSS from JavaScript With a good understanding of the DOM and CSS now under your belt, you’ll learn in this chapter how to access both the DOM and CSS directly from JavaScript, enabling you to create highly dynamic and responsive websites. I’ll also show you how to use interrupts so you can create animations or provide any code that must continue read more..

  • Page - 510

    This alone saves 22 characters of typing each time it’s called. But I choose to extend the function a little by allowing either an ID name or an object to be passed to this function, as shown in the complete version of the function in Example 20-1. Example 20-1. The O() function function O(i) { return typeof i == 'object' ? i : document.getElementById(i) } If an read more..

  • Page - 511

    Now consider the case in which the object returned by calling O is stored in, for example, an object called fred , like this: fred = O('myobj') Because of the way function S works, we can still call it to change the text color to green, like this: S(fred).color = 'green' This means that whether you wish to access an object directly or via its ID, you can do so read more..

  • Page - 512

    Including the Functions I use the O and S functions in the examples for the remainder of this chapter, as they make the code shorter and easier to follow. Therefore, I have saved them in the file OSC.js (along with the C function, as I think you’ll find it extremely useful) in the Chapter 20 folder of the accompanying archive of examples, freely downloadable read more..

  • Page - 513

    Some Common Properties Using JavaScript, you can modify any property of any element in a web document, in a similar manner to using CSS. I’ve already shown you how to access CSS properties using either the JavaScript short form or the setAttribute function to use exact CSS property names, so I won’t bore you by detailing all of these hundreds of properties. Rather, read more..

  • Page - 514

    Figure 20-1. Modifying styles from JavaScript You gain nothing by modifying properties like this, because you could just as easily have included some CSS directly, but shortly we’ll be modifying properties in response to user interaction—and then you’ll see the real power of combining Java‐ Script and CSS. Other Properties JavaScript also opens up access to a very wide read more..

  • Page - 515

    Property Sets and/or returns navigator Returns the navigator object for the window opener Returns a reference to the window that created the window outerHeight Sets or returns the outer height of a window, including tool and scroll bars outerWidth Sets or returns the outer width of a window, including tool and scroll read more..

  • Page - 516

    Many of these properties can be invaluable when you’re targeting mobile phones and tablet devices, as they will tell you exactly how much screen space you have to work with, the type of browser being used, and more. These few items of information will get you started and already provide you with many new and interesting things you can do with JavaScript. But, in fact, read more..

  • Page - 517

    Figure 20-2. Inline mouse hover JavaScript example When supplied from an inline JavaScript call, the this keyword represents the calling object. When used in class methods, it repre‐ sents an object to which the method applies. Attaching Events to Objects in a Script The preceding code is the equivalent of providing an ID to the <img> tag, and then attaching the read more..

  • Page - 518

    Attaching to Other Events Whether you’re using inline or separate JavaScript, there are several events to which you can attach actions, providing a wealth of additional features you can offer your users. Table 20-2 lists these events and details when they will be triggered. Table 20-2. Events and when they are triggered Event Occurs onabort When an image’s loading is read more..

  • Page - 519

    Adding New Elements With JavaScript, you are not limited to manipulating the elements and objects sup‐ plied to a document in its HTML. In fact, you can create objects at will by inserting them into the DOM. For example, suppose you need a new <div> element. Example 20-8 shows one way you can add it to the web page. Example 20-8. Inserting an element into read more..

  • Page - 520

    Figure 20-3. Inserting a new element into the DOM After this, various properties are assigned to the element, including some text for its inner HTML. And then, in order to make sure the new element is instantly revealed, its offsetTop property is read into the throwaway variable tmp . This forces a DOM refresh and makes the element display in any browser that might read more..

  • Page - 521

    This first statement makes a copy of element.parentNode (the parent element of the object) in pnode , which (after the child element is removed) has its offsetTop prop‐ erty looked up (and discarded in the throwaway variable tmp ), thus ensuring that the DOM is fully refreshed. Alternatives to Adding and Removing Elements Inserting an element is intended for adding totally read more..

  • Page - 522

    Don’t forget other useful CSS properties you can access from Java‐ Script, such as opacity for setting the visibility of an object to somewhere between visible and invisible, or width and height for resizing an object. And, of course, using the position property with values of 'absolute' , 'static' , or 'relative' , you can even locate an object anywhere in (or read more..

  • Page - 523

    setTimeout("alert('Hello!')", 5000) In fact, you can provide as many lines of JavaScript code as you like, if you place a semicolon after each statement, like this: setTimeout("document.write('Starting'); alert('Hello!')", 5000) Repeating time-outs One technique some programmers use to provide repeating interrupts using the function setTimeout is to call the setTimeout function from read more..

  • Page - 524

    Example 20-9. A clock created using interrupts <!DOCTYPE html> <html> <head> <title>Using setInterval</title> <script src='OSC.js'></script> </head> <body> The time is: <span id='time'>00:00:00</span><br> <script> setInterval("showtime(O('time'))", 1000) function read more..

  • Page - 525

    The time is: <span id='time'>00:00:00</span> Then, from a <script> section of code, a call is placed to the setInterval function, like this: setInterval("showtime(O('time'))", 1000) It then passes a string to setInterval , containing the following statement, which is set to execute once a second (every 1,000 milliseconds): showtime(O('time')) In the rare situation where read more..

  • Page - 526

    position :absolute; background:orange; border :1px solid red; } </style> </head> <body> <div id='box'></div> <script> SIZE = LEFT = 0 setInterval(animate, 30) function animate() { SIZE read more..

  • Page - 527

    Then, in the animate function, the global variables SIZE and LEFT are continuously updated and then applied to the width , height , and left style attributes of the box object (with 'px' added after each to specify that the values are in pixels), thus ani‐ mating it at a frequency of once every 30 milliseconds—giving a rate of 33.33 frames per second (1,000/30 read more..

  • Page - 528

    read more..

  • Page - 529

    CHAPTER 21 Introduction to jQuery Powerful and flexible as JavaScript is, with a plethora of built-in functions, you still need additional layers of code for simple things that cannot be achieved natively or with CSS, such as animations, event handling, and Ajax. What’s more, as a consequence of the various browser wars over the years, frustrating and annoying browser read more..

  • Page - 530

    Why jQuery? There’s room to cover only one library in this book, however, so I have opted for the most widely used, jQuery, which is now installed on over 60 percent of all websites, according to http://w3techs.com, and (as far as I can tell from their graphs) is more used than all its major competitors combined. Incidentally, if you ever want to see how the various read more..

  • Page - 531

    Unlike most software, for which you simply download and install the newest avail‐ able, jQuery has evolved over time to take account of the changing dynamics in the market of differing browser versions, with different features and bugs. At the same time, improvements to jQuery have been made that might make newer versions operate differently on sites that have been specially read more..

  • Page - 532

    If you have never used jQuery before (and have no special require‐ ments), then just download the latest minified version, or link to it via a CDN, as described following. Using a Content Delivery Network Several CDNs support jQuery. If you use one of them, you can save yourself the has‐ sle of having to download new versions and then upload them to your server, read more..

  • Page - 533

    An added benefit of using a CDN is that most other websites also do this, so that jQuery may well already be cached in the user’s browser, and might not even require re-delivering. With 60 percent or more of websites using jQuery, this can be a lot of valuable bandwidth and time saved. Always Using the Latest Version Another advantage of CDNs is that you can choose read more..

  • Page - 534

    JavaScript, is short, and is different from customary variable, object, or function/ method names. It takes the place of making a call to the jQuery function (which you can also do if you wish). The idea is to keep your code short and sweet, and to save on unnecessary extra typing each time you access jQuery. It also immediately shows other developers new to your read more..

  • Page - 535

    Another way of issuing this command is by calling the jQuery function (which works in the same way as $ ), like this: jQuery('code').css('border', '1px solid #aaa') Figure 21-1. Modifying elements with jQuery Avoiding Library Conflict If you use other libraries alongside jQuery, you may find that they define their own $ function. To resolve this issue, you can call the read more..

  • Page - 536

    The css Method To explain jQuery’s use of selectors, let’s first look at one of the more fundamental jQuery methods, css , with which you can dynamically alter any CSS property. It takes two arguments: the property name to be accessed, and a value to be applied, like this: css('font-family', 'Arial') As you will see in the following sections, you cannot use this read more..

  • Page - 537

    $('blockquote').css('background', 'lime') The ID Selector You can also refer to elements by their IDs if you place a # character in front of the ID name. So, to add a border to the element with the ID of advert (for example), you could use this: $('#advert').css('border', '3px dashed red') The Class Selector And you can manipulate groups of elements according to the class read more..

  • Page - 538

    Figure 21-2. Manipulating multiple elements Handling Events If all jQuery could do was alter CSS styles, it wouldn’t be a great deal of help—but of course it can do far more than that. So let’s further investigate by seeing how it han‐ dles events. As you will recall, most events are triggered by user interaction: when a mouse passes over an element, the mouse read more..

  • Page - 539

    Example 21-3 fleshes out the idea (which you can see running in Figure 21-3). Example 21-3. Processing an event <!DOCTYPE html> <html> <head> <title>jQuery Events</title> <script src='jquery-1.11.1.min.js'></script> </head> <body> <button id='clickme'>Click Me</button> <p id='result'>I am a paragraph</p> read more..

  • Page - 540

    working on a page that much more quickly, and un-user-friendly delays are mini‐ mized. To make use of this feature, place your jQuery code within the following structure: $('document').ready(function() { // Your code goes here }) Now the code will wait there until the document is ready, and only then will it be called by the ready method. In fact, there’s a shorter read more..

  • Page - 541

    The blur and focus Events The blur event triggers when focus is removed from an element, causing it to blur, and is a good partner for the focus event. Both can be used to add a handler to the event, or they will trigger the event if you omit any arguments from the method’s parentheses. In Example 21-5, there are four input fields, and the first is given read more..

  • Page - 542

    Figure 21-4. Attaching to blur and focus events The this Keyword This example also serves to illustrate the use of the this keyword. When an event is called, the element on which it was triggered is passed in the object this , which can then be given to the $ method for processing. Or, since this is a standard JavaScript object (and not a jQuery object), it read more..

  • Page - 543

    the buttons to see how some disappear with an animation (using slideUp ), and some just vanish (using hide ), as shown in Figure 21-5. Example 21-6. Attaching to the click and dblclick events <!DOCTYPE html> <html> <head> <title>Events: click & dblclick</title> <script src='jquery-1.11.1.min.js'></script> </head> <body> read more..

  • Page - 544

    Example 21-7. Intercepting key presses <!DOCTYPE html> <html> <head> <title>Events: keypress</title> <script src='jquery-1.11.1.min.js'></script> </head> <body> <h2>Press some keys</h2> <div id='result'></div> <script> $(document).keypress(function(event) { read more..

  • Page - 545

    to do this because you can easily respond to ASCII values in your code. But this method is useful when you need to work with characters. When a key press is recognized, a simple statement to that effect is inserted into the innerHTML property of the div element with the ID of result . This is a good example of where the document.write function should not be used, read more..

  • Page - 546

    It’s time, I think, for a slightly more interesting example, so in Example 21-8 I have put together a rudimentary drawing program using jQuery in conjunction with an HTML5 canvas. Although the canvas is not fully explained until Chapter 23, don’t worry because the code is very simple. Example 21-8. Intercepting mouse movement and mouse key events <!DOCTYPE html> read more..

  • Page - 547

    Figure 21-7. Capturing mouse movement and mouse key events This is one way you can quickly take a jQuery object and extract a standard JavaScript element object. Another would be to use the get method, like this: canvas = $('#pad').get(0) The two are interchangeable with each other, but get has the edge because, without any argument passed, it will return all the read more..

  • Page - 548

    These values are taken from the jQuery properties pageX and pageY , which refer to the mouse pointer’s offset from the top lefthand corner of the containing document. Therefore, since the canvas is itself offset slightly from that location, the canvas offset values (in offsetLeft and offsetTop ) are subtracted from both pageX and pageY : var xpos = event.pageX - read more..

  • Page - 549

    <script> $('#test').mouseenter(function() { $(this).html('Hey, stop tickling!') } ) $('#test').mouseleave(function() { $(this).html('Where did you go?') } ) </script> </body> </html> Figure 21-8. Detecting when the mouse enters and leaves an element When the mouse enters the bounds of the selected element, that read more..

  • Page - 550

    The preceding examples show how to capture mouse click, mouse movement, and keyboard events, and therefore they are mostly suitable for desktop environments—which is what jQuery is pri‐ marily targeted at. However, there is a version of jQuery for mobile devices that provides all the touch-handling event control you could wish for (and much more), available at jquerymobile.com. read more..

  • Page - 551

    Figure 21-9. Checking user input upon submission The key parts of this example are where the event is attached to an anonymous func‐ tion, like this: $('#form').submit(function() And where the values of the two input fields are tested for being empty: if ($('#fname').val() == '' || $('#lname').val() == '') Here the jQuery val method is used to retrieve the value read more..

  • Page - 552

    The following section lists some of the more useful jQuery effects, each of which sup‐ ports up to three arguments, as follows: No Arguments When no arguments are given, the method is called immediately without being placed in the animation queue. Duration When a duration value is supplied, the effect will take place over the assigned time, which can be a value in read more..

  • Page - 553

    0 for hide , or reach their original values for show . When hiding, the display property of the element is set to none when fully hidden, and after calling show , its previous value is reassigned once the element is fully restored. Example 21-11 lets you try hide and show for yourself (as shown in Figure 21-10). Example 21-11. Hiding and showing an element read more..

  • Page - 554

    <script src='jquery-1.11.1.min.js'></script> </head> <body> <button id='toggle'>Toggle</button> <p id='text'>Click the Toggle button</p> <script> $('#toggle').click(function() { $('#text').toggle('slow', 'linear') }) </script> </body> </html> The toggle method takes the same arguments as read more..

  • Page - 555

    $('#fadeto') .click(function() { $('#text').fadeTo( 'slow', 0.5) }) </script> </body> </html> Figure 21-11. The text has been faded to 50 percent opacity Sliding Elements Up and Down Another way to make elements disappear and reappear is to alter their height over time to make them appear to slide up and down. There are read more..

  • Page - 556

    $('#slidedown') .click(function() { $('#para').slideDown( 'slow') }) $('#slidetoggle').click(function() { $('#para').slideToggle('slow') }) </script> </body> </html> Figure 21-12. The paragraph is sliding up These methods work well when you have menus and submenus that you want to open up or close dynamically, according to the sections read more..

  • Page - 557

    Example 21-15. Creating a bouncing ball animation <!DOCTYPE html> <html> <head> <title>Effects: Animation</title> <script src='jquery-1.11.1.min.js'></script> <style> #ball { position :relative; } #box { width :640px; height read more..

  • Page - 558

    Figure 21-13. The ball is bouncing around in the browser In the <style> section of this example, the position property of the ball is set rela‐ tive to its container, which is a <div> element that has been given a border and green background. Then the <script> section features a function called bounce , in which there are four calls to animate read more..

  • Page - 559

    .animate( { height:'hide', width:'toggle' }, 'slow', 'linear') If you wish to modify any hyphenated CSS properties and they’re not being passed within quotation marks (as with height and width in this example), you must convert their names to camelCase first, by removing the hyphens and capitalizing the letter following. For example, to animate the left-margin property of an read more..

  • Page - 560

    currently in progress, or the finish method will stop the currently running anima‐ tion, and remove any that are queued. So let’s turn the previous example into a sort of game by making the ball clickable, such that when the click event triggers, the animation will cease. To do this, all that’s required is to add the following single line of code underneath the read more..

  • Page - 561

    Figure 21-14. Retrieving and displaying the HTML of an element When you omit any argument from a call to this method the result is to read rather than set the HTML of the element. The Difference Between The text and html Methods When you are working with XML documents, you cannot use the html method because it simply won’t work (it’s designed for use read more..

  • Page - 562

    With the attr method, you can get and set the attributes of elements, as shown in Example 21-17, in which a link to the Google website has been completely replaced with one to Yahoo! Example 21-17. Modifying attributes with the attr method <!DOCTYPE html> <html> <head> <title>The DOM: attr</title> <script read more..

  • Page - 563

    Adding and Removing Elements While it is possible to insert elements into the DOM using the html method, this is suitable only for creating child elements of a particular element. Therefore, jQuery provides a number of methods for manipulating any part of the DOM. These methods are append , prepend , after , before , remove , and empty , and an example of each is included read more..

  • Page - 564

    Figure 21-16. A document with a variety of different elements The prepend method has been used to insert the string Link: before the inner text or HTML of all <a> elements, like this: $('a').prepend('Link: ') Then an attribute selector is used to select all elements that have an href attribute starting with http . The string http denotes links that are not read more..

  • Page - 565

    Then I added a little user-interaction with a couple of buttons. When clicked, using the remove method, the first button removes the <img> element containing the ball, like this: $('#a').click(function() { $('#ball').remove() } ) The image is now no longer in the DOM, which you can verify if you highlight the browser contents, right-click it, and use Inspect Element in read more..

  • Page - 566

    though, is that it does a great job of normalizing these types of values, so that your pages will look how you intend them to appear in all major browsers. There are three types of dimensions: element width and height, inner width and height, and outer width and height. Let’s look at these in turn. The width and height Methods Both the width and height methods read more..

  • Page - 567

    <head> <title>Dimensions</title> <script src='jquery-1.11.1.min.js'></script> </head> <body> <p> <button id='getdoc'>Get document width</button> <button id='getwin'>Get window width</button> <button id='getdiv'>Get div width</button> <button id='setdiv'>Set div width read more..

  • Page - 568

    At the start of the body, there are four buttons: three for reporting the widths of the document, window, and a <div> element that appears just below the buttons, and one to set the div’s width to a new value. In the script section, there are four jQuery state‐ ments, of which the first three simply fetch the widths of the objects given, and then report read more..

  • Page - 569

    DOM Traversal If you refer back to the section on the Document Object Model (DOM) in Chap‐ ter 13, you’ll recall that all web pages are constructed in much the same way as exten‐ ded families. There are parent and child objects, siblings, grandparents and grandchildren, and even element relationships that could be referred to as cousins, aunts, and so forth. For example, read more..

  • Page - 570

    Let’s now make something happen when the selector matches, such as changing the font-weight property of the parent element in the previous snippet to bold , like this: $('li').parent().css('font-weight', 'bold') Using a filter Optionally, a selector can be passed to parent , to filter out which of the parents the desired changes should apply to. To illustrate, Example 21-20 read more..

  • Page - 571

    the list-style-type property of the selected list to circle . Figure 21-18 shows these two statements in effect. Figure 21-18. Accessing parent elements with and without filters Selecting all ancestor elements We’ve just seen how to select direct parents of elements, but you can also select ances‐ tors, all the way back to the <html> root element by using the read more..

  • Page - 572

    <div> element. Then, in the script section, there is one example each of the parents and parentsUntil methods being called. Example 21-21. Using the parents and parentsUntil methods <!DOCTYPE html> <html> <head> <title>DOM Traversal: Parents</title> <script src='jquery-1.11.1.min.js'></script> </head> <body> read more..

  • Page - 573

    Figure 21-19. Comparing the parents and parentsUntil methods However, the second statement uses parentsUntil so that the selection stops at the first <div> element encountered. This means that when the underline styling is applied, it is applied only to the closest parent <div> that contains the <li> element with the ID of elem . The outer <div> is read more..

  • Page - 574

    The siblings method will return all the matching elements that are children of the same parent, except for the element used for selecting. So, taking the example of the following snippet, if you look up the siblings of the <li> element with the ID of two , it will return only the first and third <li> elements. <ul> <li>Item 1</li> read more..

  • Page - 575

    Item 2 also uses the class new (because the method is called on that element, and so it is excluded from the selection). Figure 21-20. Selecting sibling elements Since the siblings method omits the element on which it is called (which I will refer to as the callee), it cannot be used to select from all children of a parent element. However, to achieve that read more..

  • Page - 576

    <li >Item 4</li> <li >Item 5</li> </ul> So far, so simple. But what if you would like to reference all the siblings following a particular element? Well, you can do that with nextAll method, like this (which in the preceding snippet would style the last two items): $('#new').nextAll().css('font-weight', 'bold') When read more..

  • Page - 577

    For example, to style just the first element returned by a selection, you can use the first method, like this (to set the first list item in the first unordered list to display underlined): $('ul>li').first().css('text-decoration', 'underline') Or you can choose to style only the last item by using the last method, like this: $('ul>li').last().css('font-style', 'italic') Or, to read more..

  • Page - 578

    <li id='new'>Item 3</li> <li>Item 4 <ol type='a'> <li>Item 4a</li> <li>Item 4b</li> </ol></li> <li>Item 5</li> </ul> <script> $('ul>li').first() .css('text-decoration', read more..

  • Page - 579

    Example 21-24. Reporting the parent element with is <!DOCTYPE html> <html> <head> <title>Using is</title> <script src='jquery-1.11.1.min.js'></script> </head> <body> <div><button>Button in a div</button></div> <div><button>Button in a div</button></div> <span><button>Button in read more..

  • Page - 580

    The $.each Method Using $.each , you can iterate through arrays or array-like objects by simply attaching a function to be called for each iteration. Example 21-25 shows an array of pet names and types (called pets ), from which another array (called guineapigs ) needs to be extracted, containing only the names of the guinea pigs. Example 21-25. Calling the each method read more..

  • Page - 581

    separator. The result of loading this example into a browser is simply to display the text “The guinea pig names are: Scratchy & Squeeky.” The $.map Method Another way to achieve this is with the $.map method, which returns all the values that your function returns in an array, saving you from having to create an array, and then push matches onto it—as we had read more..

  • Page - 582

    Example 21-26. Sending a Post Ajax request <!DOCTYPE html> <html> <!-- jqueryajaxpost.htm --> <head> <title>jQuery Ajax Post</title> <script src='jquery-1.11.1.min.js'></script> </head> <body style='text-align:center'> <h1>Loading a web page into a DIV</h1> <div id='info'>This sentence will be replaced</div> read more..

  • Page - 583

    $('#info').html(data) } ) </script> </body> </html> The urlget.php program remains unchanged from Example 17-5, because this exam‐ ple and Example 17-4 are interchangeable. Remember that the security restrictions of Ajax require that the communication takes place with the same server that supplied the main web document. You must read more..

  • Page - 584

    jQuery Mobile If you are developing for mobile browsers, you will also want to take a look at jQuery mobile, which is more of a framework than a library, offering sophisticated, touch- optimized ways to navigate the wide range of different types of mobile hard and soft‐ ware, to provide the best possible user experience. The jQuery Mobile download is fully customizable read more..

  • Page - 585

    Questions 1. What is the symbol commonly used as the factory method for creating jQuery objects, and what is the alternative method name? 2. How would you link to the minified release 1.11.1 of jQuery from the Google CDN? 3. What types of argument does the jQuery factory method accept? 4. With which jQuery method can you get or set a CSS property value? 5. What read more..

  • Page - 586

    read more..

  • Page - 587

    CHAPTER 22 Introduction to HTML5 HTML5 represents a substantial leap forward in web design, layout, and usability. It provides a simple way to manipulate graphics in a web browser without resorting to plug-ins such as Flash, offers methods to insert audio and video into web pages (again without plug-ins), and irons out several annoying inconsistencies that crept into HTML during read more..

  • Page - 588

    as Apple’s Siri, Microsoft’s Cortana, OK Google, and IBM’s Watson, combined with wearable technology that uses visual and voice input—like Google Glass and the Gal‐ axy Gear watch—rather than keyboards. I look forward to covering these things in future editions of this book. But for now, having written about what’s to come in HTML5 for some years, and now that read more..

  • Page - 589

    context.fillStyle = 'red' S(canvas).border = '1px solid black' context.beginPath() context.moveTo(160, 120) context.arc(160, 120, 70, 0, Math.PI * 2, false) context.closePath() context.fill() </script> </body> </html> Figure 22-1. Drawing the Japanese flag using an HTML5 read more..

  • Page - 590

    other places; letting you know which friends are near you; directing you to the near‐ est gas station; and more. Example 22-2 will display a Google map of the user’s location, as long as the browser supports geolocation and the user grants access to his location (as shown in Figure 22-2). Otherwise, it will display an error. Example 22-2. Displaying the map at a read more..

  • Page - 591

    case 2: message = 'Position Unavailable'; break; case 3: message = 'Operation Timed Out'; break; case 4: message = 'Unknown Error'; break; } O('status').innerHTML = message } </script> </body> </html> Figure 22-2. The user’s location has read more..

  • Page - 592

    In Example 22-3, the same video file has been encoded in different formats to ensure that all major browsers are accounted for. Browsers will simply select the first type they recognize and play it, as shown in Figure 22-3. Example 22-3. Playing a video with HTML5 <!DOCTYPE html> <html> <head> <title>HTML5 Video</title> </head> read more..

  • Page - 593

    today has been detailed in Chapter 12, and future editions of this book will include other aspects of forms as they become adopted across the board. In the meantime, you can keep up-to-date with the latest developments on HTML5 forms at http:// tinyurl.com/h5forms. Local Storage With local storage, your ability to save data on a local device is substantially increased from the read more..

  • Page - 594

    Microdata Also in Chapter 25 I show how you can mark up your code with microdata to make it totally understandable to any browser or other technology that needs to access it. Microdata is sure to become more and more important to search engine optimization too, so it’s important that you begin to incorporate it or at least understand what information it can provide read more..

  • Page - 595

    CHAPTER 23 The HTML5 Canvas Although the collective term given to the new web technologies is HTML5, they are not all simply HTML tags and properties. Such is the case with the canvas element. Yes, you create a canvas by using the <canvas> tag, and maybe supply a width and height, and can modify it a little with CSS, but to actually write to (or read from) a read more..

  • Page - 596

    <script> canvas = O('mycanvas') context = canvas.getContext('2d') context.fillStyle = 'red' S(canvas).border = '1px solid black' context.beginPath() context.moveTo(160, 120) context.arc(160, 120, 70, 0, Math.PI * 2, false) read more..

  • Page - 597

    S(canvas).border = '1px solid black' With everything prepared, a path is opened on the context and the drawing position is moved to the location 160,120: context.beginPath() context.moveTo(160, 120) After that, an arc is drawn centered on that coordinate, with a radius of 70 pixels, beginning at an angle of 0 degrees (which is the righthand edge of the circle as you look at read more..

  • Page - 598

    This text is only visible in non-HTML5 browsers </canvas> <img id='myimage'> <script> canvas = O('mycanvas') context = canvas.getContext('2d') context.fillStyle = 'red' S(canvas).border = '1px solid black' context.beginPath() read more..

  • Page - 599

    Specifying an Image Type When creating an image from a canvas, you can specify the type of image you want out of .jpg and .png. The default is .png ('image/png'), but should you prefer .jpg, you can alter the call to toDataURL . At the same time, you can also specify the amount of compression to use between 0 (for lowest quality) and 1 (for highest quality). read more..

  • Page - 600

    The strokeRect Method When you want only an outlined rectangle, you can use a command such as the fol‐ lowing, which will use the default of black or the currently selected stroke color: context.strokeRect(60, 60, 520, 120) To change the color used, you can first issue a command such as the following, sup‐ plying any valid CSS color argument: context.strokeStyle = 'green' read more..

  • Page - 601

    Figure 23-2. Drawing concentric rectangles Later in this chapter, you’ll see how you can further modify output by changing stroke types and widths, but first let’s turn to modifying fills by applying gradients. The createLinearGradient Method There are a couple of ways to apply a gradient to a fill, but the simplest is with the createLinearGradient method. You specify read more..

  • Page - 602

    is halfway down the lefthand canvas edge, while the end of 640,80 is halfway down the right-hand edge. Then a couple of color stops are provided such that the very first color of the gradient is white, and the final color is black. The gradient will then transition smoothly between these colors across the canvas from left to right. With the gradient object now ready, it read more..

  • Page - 603

    gradient = context.createLinearGradient(320, 0, 480, 240) gradient.addColorStop(0, 'green') gradient.addColorStop(1, 'purple') context.fillStyle = gradient context.fillRect(330, 20, 135, 200) gradient = context.createLinearGradient(480, 240, 640, 0) gradient.addColorStop(0, 'orange') gradient.addColorStop(1, 'magenta') context.fillStyle = gradient context.fillRect(485, 20, 135, 200) Figure 23-4. A range of different read more..

  • Page - 604

    end position, as it is deduced from the start position of the next color stop, or the gradient end if there isn’t another color. In the preceding examples, only the two start and end values were chosen, but to cre‐ ate a rainbow effect, you could set up your color stops as shown in Example 23-6 (and displayed in Figure 23-5). Example 23-6. Adding multiple read more..

  • Page - 605

    What you need to do is pass the center location as a pair of x and y coordinates, along with a radius in pixels. These are used as the start of the gradient and outer circum‐ ference, respectively. Then you also pass another set of coordinates and a radius to specify the end of the gradient. So, for example, to create a gradient that simply starts at the read more..

  • Page - 606

    Figure 23-7. A stretched radial gradient By manipulating the figures supplied to this method, you can cre‐ ate a wide range of weird and wonderful effects—try it for yourself with the supplied examples. Using Patterns for Fills In a similar manner to gradient fills, you can also apply an image as a fill pattern. This can be an image anywhere in the current read more..

  • Page - 607

    Figure 23-8. Tiling an image by using it as a pattern fill We create the pattern by using the createPattern method, which also supports non‐ repeating patterns, or ones that just repeat in the x- or y-axes. We achieve this by passing one of the following values to it as the second argument after the image to use: repeat Repeat the image both read more..

  • Page - 608

    Writing Text to the Canvas As you would expect from a set of graphics features, writing to the canvas with text is fully supported with a variety of font, alignment, and fill methods. But why would you want to write text to the canvas when there’s already such good support for web fonts in CSS these days? Well, suppose you wish to display a graph or table read more..

  • Page - 609

    This method—using line drawing—is only one way of drawing text to the canvas. So, in addition to all the following properties that affect text, line-drawing properties such as lineWidth (detailed later in this chapter) will also affect how text displays. The textBaseLine Property The textBaseLine property can be given any of the following values: top Aligns to the top of the read more..

  • Page - 610

    left Aligns the text to the left. right Aligns the text to the right. center Centers the text. You use the property like this: context.textAlign = 'center' In the case of the current example, you need the text left-aligned so that it butts up neatly to the edge of the canvas, so the textAlign property is not used, and therefore the default left alignment occurs. The read more..

  • Page - 611

    For good measure, I also kept the strokeText call in this example to ensure a black outline to the text; without it, there wasn’t enough definition at the edges. A wide variety of other fill types or patterns can also be used here, and the simplicity of the canvas makes it easy to experiment. What’s more: if you wish, once you have the heading just right, read more..

  • Page - 612

    Also, when you are joining lines together that are wider than a single pixel, it is important to specify exactly how they should meet. You achieve this with the line Join property, which can have values of round , bevel , or miter , like this: context.lineJoin = 'bevel' Example 23-12 (shown here in full since it’s a little more complicated) applies all three values read more..

  • Page - 613

    context.closePath() } } </script> </body> </html> This code sets up a few properties and then nests a pair of loops: one for the line caps and one for the joins. Inside the central loop, the current values for the lineCap and lineJoin properties are first set, and then displayed in the canvas read more..

  • Page - 614

    The miterLimit Property If you find that your mitered joins get cut off too short, you can extend them by using the miterLimit property, like this: context.miterLimit = 15 The default value is 10 , so you can reduce the miter limit too. If miterLimit is not set to a sufficiently large enough value for a miter, then sharply mitered joins will simply bevel instead. So, read more..

  • Page - 615

    rent location and then moves it to a new one, while LineTo draws a line from the current location of the imaginary pen to the new one specified. Or, at least, a line will be drawn if the stroke method is called, but not otherwise. So let’s just say that LineTo creates a potential drawn line, but it could equally be part of the outline for a fill area, read more..

  • Page - 616

    Filling Areas Using paths, you can create complicated areas that can also be filled in with solid, gra‐ dient, or pattern fills. In Example 23-13, some basic trigonometry is used to create a complex star pattern. I won’t detail how the math works because that’s not important to the example (although if you want to play with the code, try changing the values read more..

  • Page - 617

    </script> </body> </html> Figure 23-12. Drawing and filling in a complex path With paths, it’s possible to create as complex an object as you like, either using formulae or loops (as in this example), or simply with a long string of moveTo and/or LineTo or other calls. The clip Method Sometimes when you are building a path, you may read more..

  • Page - 618

    Example 23-14. Creating a clip area context.beginPath() for (j = 0 ; j < 10 ; ++j) { context.moveTo(20, j * 48) context.lineTo(620, j * 48) context.lineTo(620, j * 48 + 30) context.lineTo(20, j * 48 + 30) } context.stroke() context.closePath() Figure 23-13. A path of horizontal bars To turn this example into a clipped area of the canvas, you read more..

  • Page - 619

    Now the outline of the bars won’t be seen, but the clipping area will be in place. To illustrate this, Example 23-15 makes this method substitution and then adds to the previous example by drawing a simple picture on the canvas, of green grass below a blue sky containing a shining sun (modified from Example 23-12), with the changes highlighted in bold, and as shown read more..

  • Page - 620

    Figure 23-14. Drawing occurs only within the allowed clipped area OK, we’re not going to win any competitions here, but you can see how powerful clip‐ ping can be when used effectively. The isPointInPath Method Sometimes you need to know whether a particular point lies in a path you’ve con‐ structed. However, you will probably want to use this function only if read more..

  • Page - 621

    A perfect use for the isPointInPath method is for creating games using the canvas in which you wish to check for a missile hitting a target, a ball hitting a wall or bat, or similar boundary conditions. Working with Curves In addition to straight paths, you can create an almost infinite variety of curved paths, with a selection of different methods, ranging from simple read more..

  • Page - 622

    context.arc(80 + j * 160, 80, 70, 0, arcs[j]) context.closePath() context.stroke() } context.strokeStyle = 'red' for (j = 0 ; j < 4 ; ++j) { context.beginPath() context.arc(80 + j * 160, 240, 70, 0, arcs[j]) context.stroke() context.closePath() } context.strokeStyle = 'green' for (j = 0 ; j < 4 ; ++j) { context.beginPath() context.arc(80 + j * 160, read more..

  • Page - 623

    Figure 23-15. A variety of arc types If you prefer to work with degrees instead of radians, you could create a new Math library function, like this: Math.degreesToRadians = function(degrees) { return degrees * Math.PI / 180 } And then replace the array-creating code, starting at the second line of Example 23-16, with the following: arcs = [ Math.degreesToRadians(180), read more..

  • Page - 624

    The arcTo Method Rather than creating a whole arc at once, you can choose to arc from the current loca‐ tion in the path to another one, like the following call to arcTo (which simply requires two pairs of x and y coordinates and a radius): context.arcTo(100, 100, 200, 200, 100) The locations you pass to the method represent the points where imaginary tangent read more..

  • Page - 625

    Figure 23-16. Drawing arcs of different radii Essentially, what you can best use arcTo for is to curve from one section of drawing to another, following an arc based on the previous and subsequent positions, as if they were tangential to the arc to be created. If this sounds complicated, don’t worry: you’ll soon get the hang of it and find it’s actually a read more..

  • Page - 626

    context.fill() context.closePath() Figure 23-17. Drawing with quadratic curves Incidentally, to achieve the dotted line around the cloud in this image, I used the stroke method in conjunction with the setLine Dash method, which takes a list representing the dash and space lengths. In this instance, I used setLineDash([2, 3]) , but you can create dash lines as complicated as read more..

  • Page - 627

    context.stroke() context.closePath() Figure 23-18. A Bézier curve w ith two attractors Attractors do not need to be at opposite sides of a canvas, because you can place them anywhere, and when they are near each other, they will exert a combined pull (rather than opposing pulls, as in the preceding example). Using these various types of curve methods, it’s possible for you read more..

  • Page - 628

    To ensure that an image has been loaded before you use it, best practice is to enclose your image-handling code within a function that is triggered only upon image load, like this: myimage = new Image() myimage.src = 'image.gif' myimage.onload = function() { context.drawImage(myimage, 20, 20) } Resizing an Image If you need to resize an image when it is placed on read more..

  • Page - 629

    context.drawImage(myimage, 30, 30, 40, 40, 20, 140) And to resize the grabbed portion to 100 pixels square, you would use the following: context.drawImage(myimage, 30, 30, 40, 40 , 20, 140, 100, 100) I find this very confusing and cannot think of a logical reason for why this method works this way. But, since it does, I’m afraid there’s nothing you can do other than read more..

  • Page - 630

    Copying from a Canvas You can also use a canvas as a source image for drawing to the same (or another) can‐ vas. Just supply the canvas object name in place of an image object, and use all the remaining arguments in the same way as you would with an image. At this point, I would have loved to show you how to use a <video> element (explained in the read more..

  • Page - 631

    orig = 95 points = 21 dist = Math.PI / points * 2 scale1 = 75 scale2 = 50 myimage.onload = function() { context.beginPath() for (j = 0 ; j < points ; ++j) { x = Math.sin(j * dist) y = Math.cos(j * dist) context.lineTo(orig + x * scale1, orig + y * scale1) context.lineTo(orig + x * scale2, orig + y * scale2) read more..

  • Page - 632

    Figure 23-20. Shadows under different types of drawing objects Editing at the Pixel Level Not only does the HTML5 canvas provide you with a powerful range of drawing methods, but it also lets you get your hands dirty and work under the hood directly at the pixel level with a trio of powerful methods. The getImageData Method With the getImageData method, you can grab read more..

  • Page - 633

    for (x = 0 ; x < myimage.width ; ++x) { average = ( idata.data[pos] + idata.data[pos + 1] + idata.data[pos + 2] ) / 3 idata.data[pos] = average + 50 idata.data[pos + 1] = average idata.data[pos + 2] = read more..

  • Page - 634

    idata.data[2] // Blue level idata.data[3] // Alpha level Location 1,0 then follows, like this: idata.data[4] // Red level idata.data[5] // Green level idata.data[6] // Blue level idata.data[7] // Alpha level In this image, everything continues in the same fashion until the rightmost pixel of the image in row 0 (which is the 320th pixel, at location 319,0) is reached. At that read more..

  • Page - 635

    idata.data[pos] = average + 50 idata.data[pos + 1] = average idata.data[pos + 2] = average - 50 The result is to increase the red and reduce the blue level of each pixel (of what would otherwise now become a monochrome image, if only the average value were written back to these colors), giving it a sepia cast. If you’re interested in performing more advanced read more..

  • Page - 636

    Advanced Graphical Effects Among the more advanced features available on the HTML5 canvas are the ability to assign various compositing and transparency effects, as well as to apply powerful transformations such as scaling, stretching, and rotating. The globalCompositeOperation Property There are 12 different methods available to fine-tune the way you place an object on the canvas, taking read more..

  • Page - 637

    destination-atop The source image displays where the destination is not displayed. Where the destina‐ tion and source overlap, the destination image is displayed. Any transparency in the source image prevents that area of the destination image being shown. lighter The sum of the source and destination is applied such that where they do not overlap, they display as normal; where read more..

  • Page - 638

    context.arc(50, 50, 50, 0, Math.PI * 2, false) context.fill() context.globalCompositeOperation = types[j] context.drawImage(image, 20, 20, 100, 100) } } As with some others in this chapter, this example (downloadable from the companion website) includes some HTML and/or CSS to enhance the display, which isn’t shown here because it’s not read more..

  • Page - 639

    The globalAlpha Property When drawing on the canvas, you can specify the amount of transparency to apply using the globalAlpha property, which supports values from 0 (fully transparent) to 1 (fully opaque). The following command sets the alpha to a value of 0.9 , such that future draw operations will be 90 percent opaque (or 10 percent transparent): context.globalAlpha = 0.9 read more..

  • Page - 640

    Figure 23-23. Scaling an image up and then down again If you look carefully, you may notice that the copy image under the original is a little bit fuzzy due to the scaling up and then down. If you use negative values for one or more scaling parameters, you can reverse an element in either the horizontal or vertical direction (or both), at the same time read more..

  • Page - 641

    Style , font , globalAlpha , globalCompositeOperation , lineCap , lineJoin , line Width , miterLimit , shadowBlur , shadowColor , shadowOffsetX , shadowOffsetY , strokeStyle , textAlign , and textBaseline . The properties of the following meth‐ ods are also managed by save and restore : scale , rotate , translate , and trans form . The rotate Method Using the rotate method, you can read more..

  • Page - 642

    Figure 23-24. An image at four different rotations The translate Method To change the origin of a rotation, you can call the translate method to shift it to somewhere else, which can be anywhere inside (or outside) the canvas or, more usu‐ ally, somewhere within the destination location of the object (usually its center). Example 23-26 performs this translation prior read more..

  • Page - 643

    tive values, such that its center matches the origin point. The result of this is shown in Figure 23-25. Figure 23-25. Rotating images in place To recap: when you wish to rotate or transform (described next) an object in place, you should perform the following actions: 1. Save the context. 2. Translate the canvas origin to the center of where the object is to be read more..

  • Page - 644

    4. Vertical scale 5. Horizontal translate 6. Vertical translate You can apply these values in many ways—for example, by emulating the scale method from Example 23-24 by replacing this call: context.scale(3, 2) with the following: context.transform(3, 0, 0, 2 , 0, 0) Or, in the same way, you can replace this call from Example 23-26: context.translate(20 + w / 2 + j * (w + read more..

  • Page - 645

    Figure 23-26. Horizontally skewing an object to the right You can even rotate an object with transform by supplying one negative and one opposite positive skew value. But beware: when you do this, you’ll modify the size of an element, and will therefore also need to adjust the scale arguments at the same time. Plus, you’ll also need to remember to translate read more..

  • Page - 646

    Questions 1. How do you create a canvas element in HTML? 2. How do you give JavaScript access to a canvas element? 3. How do you start and finish the creation of a canvas path? 4. What method can you use to extract data from a canvas into an image? 5. How can you create gradient fills of more than two colors? 6. How can you adjust the width of lines when read more..

  • Page - 647

    CHAPTER 24 HTML5 Audio and Video One of the biggest driving forces behind the growth of the Internet has been the insa‐ tiable demand from users for ever more multimedia in the form of audio and video. Initially, bandwidth was so precious that there was no such thing as live streaming, and it could take minutes or even hours to download an audio track, let alone a read more..

  • Page - 648

    types that all browsers should play natively, and these were introduced into the HTML5 specification. Finally, it is possible (as long as you encode your audio and video in a few different formats) to upload multimedia to a web server, place a couple of HTML tags in a web page, and have the media play on any major desktop browser, smartphone, or tablet device, without the read more..

  • Page - 649

    supported by Google Chrome, Mozilla Firefox, and Opera. Its mime type is audio/ ogg , or sometimes audio/oga . The following list summarizes the major operating systems and browsers, along with the audio types their latest versions support: • Apple iOS: AAC, MP3, PCM • Apple Safari: AAC, MP3, PCM • Google Android: 2.3+ AAC, MP3, Vorbis • Google Chrome: AAC, MP3, Vorbis read more..

  • Page - 650

    Figure 24-1. Playing an audio file In this example I included three different audio types, because that’s perfectly accepta‐ ble, and can be a good idea if you wish to ensure that each browser can locate its pre‐ ferred format rather than just one it knows how to handle. However, the example will still play on all platforms if one or the other (but not read more..

  • Page - 651

    Example 24-2. Playing audio using JavaScript <!DOCTYPE html> <html> <head> <title>Playing Audio with JavaScript</title> <script src='OSC.js'></script> </head> <body> <audio id='myaudio'> <source src='audio.m4a' type='audio/aac'> <source src='audio.mp3' type='audio/mp3'> <source read more..

  • Page - 652

    download at the http://lpmj.net companion website). The code to add is highlighted in bold. Example 24-3. Providing a Flash fallback for non-HTML5 browsers <audio controls> <object type="application/x-shockwave-flash" data="audioplayer.swf" width="300" height="30"> <param name="FlashVars" read more..

  • Page - 653

    As with many elements, you can easily resize the object to (for example) 300×30 pix‐ els by providing these values to its width and height attributes. The <video> Element Playing video in HTML5 is quite similar to audio; you just use the <video> tag and provide <source> elements for the media you are offering. Example 24-4 shows how you do this with read more..

  • Page - 654

    MP4 A license-encumbered, multimedia container format standard specified as a part of MPEG-4, supported by Apple, Microsoft, and, to a lesser extent Google, since it has its own WebM container format. Its mime type is video/mp4 . OGG A free, open container format maintained by the Xiph.Org Foundation. The creators of the OGG format state that it is unrestricted by software patents read more..

  • Page - 655

    • Opera: OGG, WebM/Theora, VP8 Looking at this list, it’s clear that MP4/H.264 is almost unanimously supported, except for the Opera browser. So if you’re prepared to ignore the 1 percent or so of users this comprises (and hope that Opera will soon have to adopt the format any‐ way), you need to supply your video using only one file type: MP4/H.264. But for read more..

  • Page - 656

    If you wish to control video playback from JavaScript, you can do so using code such as that in Example 24-5 (with the additional code required highlighted in bold), and shown in Figure 24-5. Example 24-5. Controlling video playback from JavaScript <!DOCTYPE html> <html> <head> <title>Playing Video with JavaScript</title> <script read more..

  • Page - 657

    Figure 24-5. JavaScript is being used to control the video This code is just like controlling audio from JavaScript. Simply call the play and/or pause methods of the myvideo object to play and pause the video. Supporting Older Browsers Also as with audio, older versions of browsers will still be in general use for a while to come, so it makes sense to offer read more..

  • Page - 658

    <source src='movie.webm' type='video/webm'> <source src='movie.ogv' type='video/ogg'> </video> Figure 24-6. Flash provides a handy fallback for non-HTML5 browsers This Flash video player is particular about security, so it won’t play videos from a local file system, only from a web server, so I have supplied a file on the Web (at tinyurl.com/html5video-mp4) for read more..

  • Page - 659

    Summary Using the information in this chapter, you will be able to embed any audio and video on almost all browsers and platforms without worrying about whether users may or may not be able to play it. In the following chapter, I’ll demonstrate the use of a number of other HTML5 fea‐ tures, including geolocation and local storage. Questions 1. Which two HTML element tags read more..

  • Page - 660

    read more..

  • Page - 661

    CHAPTER 25 Other HTML5 Features In this final chapter on HTML5, I explain how to use geolocation, local storage, and web workers; show you how to allow web apps to run offline; and demonstrate the use of in-browser dragging and dropping. Strictly speaking, most of these features (like much of HTML5) aren’t really exten‐ sions to HTML, because you access them with read more..

  • Page - 662

    any signals. In these cases, additional techniques may be used to attempt to determine your location. Other Location Methods If your device has mobile phone hardware but not GPS, it may attempt to triangulate its location by checking the timing of signals received from the various communica‐ tion towers with which it can communicate (and whose positions are very precisely known). read more..

  • Page - 663

    Example 25-1. Displaying a map of your current location <!DOCTYPE html> <html> <head> <title>Geolocation Example</title> <script src='OSC.js'></script> <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> </head> <body> <div id='status'></div> <div id='map'></div> read more..

  • Page - 664

    </body> </html> Let’s walk through this code and see how it works, starting with the <head> section, which displays a title; loads in the OSC.js file containing the O , S , and C functions I provided to make accessing HTML elements from JavaScript easier; and then also pulls in the JavaScript code for the Google Maps service, which is drawn on read more..

  • Page - 665

    var gopts = { center: new google.maps.LatLng(lat, long), zoom: 9, mapTypeId: google.maps.MapTypeId.ROADMAP } Last, in this function, we create a new map object by passing gmap and gopts to the Map method of the google.maps object (the code for which you will recall was loaded in just after the OSC.js file). var map = new google.maps.Map(gmap, gopts) If permission read more..

  • Page - 666

    The Google map will be fully interactive and zoomable by the user, who can also change the map type to satellite imagery. You can set a different zoom level or imagery type by providing different values to the gopts object. For example, a value of 1 for zoom will zoom out the furthest, and 20 will zoom in the most. A value of SATELLITE for the read more..

  • Page - 667

    course, you can never guarantee that a website or web app is totally secure, and should never work on highly sensitive documents using software (or hardware) that can go online. But for minimally private documents such as family photographs, you might feel more comfortable using a web app that saves locally than one that saves files to an external server. Using Local Storage read more..

  • Page - 668

    username = localStorage.getItem('username') password = localStorage.getItem('password') Unlike saving and reading cookies, you can call these methods at any time you like, not simply before any headers have been sent by the web server. The saved values will remain in local storage until erased in the following manner: localStorage.removeItem('username') localStorage.removeItem('password') Or, you read more..

  • Page - 669

    Figure 25-2. Two keys and their values are read from local storage You are not restricted to just storing usernames and passwords; you can include virtually any and all data, and as many key/value pairs as you like, up to the available storage limit for your domain. Web Workers With web workers, you can create sections of JavaScript code that will run in the back‐ read more..

  • Page - 670

    <span id='result'>0</span> <script> if (!!window.Worker) { var worker = new Worker('worker.js') worker.onmessage = function (event) { O('result').innerHTML = event.data; } } else { read more..

  • Page - 671

    This file assigns the value 1 to the variable n . It then loops continuously, incrementing n and checking it for primality by a brute-force method of testing all values from 1 to the square root of n to see if they divide exactly into n , with no remainder. Should a factor be found, the continue command stops the brute-force attack immediately because the read more..

  • Page - 672

    clock.html file, and followed by the OSC.js file, which is the same one used by many examples in this book. Example 25-6. The clock.html file <!DOCTYPE html> <html manifest='clock.appcache'> <head> <title>Offline Web Apps</title> <script src='OSC.js'></script> <script src='clock.js'></script> <link rel='stylesheet' read more..

  • Page - 673

    Example 25-8. The clock.css file output { font-weight:bold; } As long as the clock.appcache file lists them all, these four files (clock.html, OSC.js, clock.css, and clock.js) together make up a working offline web application, which will be downloaded and made available locally by any web browser that understands off‐ line web apps. When run, the output looks like this: The read more..

  • Page - 674

    function allow(event) { event.preventDefault() } function drag(event) { event.dataTransfer.setData('image/png', event.target.id) } function drop(event) { event.preventDefault() var data=event.dataTransfer.getData('image/png') read more..

  • Page - 675

    Figure 25-3. Two images have been dragged and dropped Other events you can attach to include ondragenter for when a drag operation enters an element, ondragleave for when one leaves an element, and ondragend for when a dragging operation ends, which you can use (for example) to modify the cursor dur‐ ing these operations. Cross-Document Messaging You’ve already seen read more..

  • Page - 676

    data The incoming message origin The origin of the sender document, including the scheme, hostname, and port source The source window of the sender document The code to send messages is just a single instruction, in which you pass the message to be sent and the domain to which it applies, as in Example 25-10. Example 25-10. Sending web messages to an iframe <!DOCTYPE read more..

  • Page - 677

    <title>Web Messaging (b)</title> <style> #output { font-family:"Courier New"; white-space:pre; } </style> <script src='OSC.js'></script> </head> <body> <div id='output'>Received messages will display here</div> <script> read more..

  • Page - 678

    O('frame').contentWindow.postMessage('Message ' + count++, '*' ) To direct messages only to documents originating from a particular domain, you can change this parameter. In the current case, a value of http://localhost would ensure that only documents loaded from the local server will be sent any messages: O('frame').contentWindow.postMessage('Message ' + count++, 'http://localhost' ) Likewise, read more..

  • Page - 679

    properties of an item such as a book, providing a range of information that a com‐ puter can use to understand, for example, its authors, publishers, contents, and so on. Or, more frequently these days, microdata is important for search engines and social networking sites. Example 25-12 creates a short bio for George Washington as if it were a profile on a social read more..

  • Page - 680

    Figure 25-5. This document contains microdata, which is not visible Browsers don’t yet really do anything with microdata, but it’s still very worth getting to know it. Using the right microdata gives lots of information to search engines like Google or Bing, and may help to promote clearly annotated pages in the rankings as compared to sites that don’t implement read more..

  • Page - 681

    { data = document.getItems('http://schema.org/Person')[0] alert(data.properties['jobTitle'][0].textContent) } } Browsers that support this feature will display as Figure 25-6, but other browsers will not trigger the pop-up window. Figure 25-6. Displaying the value for the ‘jobTitle’ microdata key Google has stated that it definitely uses microdata when it finds read more..

  • Page - 682

    Summary This concludes your introduction to HTML5. You now have a number of powerful new features with which to make even more dynamic and compelling websites. In the final chapter, I’ll show you how you can bring all the different technologies in this book together to create a mini–social networking site. Questions 1. What method do you call to request geolocation data read more..

  • Page - 683

    CHAPTER 26 Bringing It All Together Now that you’ve reached the end of your journey into learning the hows, whys, and wherefores of dynamic web programming, I want to leave you with a real example that you can sink your teeth into. In fact, it’s a collection of examples, because I’ve put together a simple social networking project comprising all the main features read more..

  • Page - 684

    • A logout facility • Session control • User profiles with uploaded thumbnails • A member directory • Adding members as friends • Public and private messaging between members • How to style the project I decided to name the project Robin’s Nest, but you have to modify only one line of code (in functions.php) to change this to a name of your choice. On read more..

  • Page - 685

    createTable Checks whether a table already exists and, if not, creates it queryMysql Issues a query to MySQL, outputting an error message if it fails destroySession Destroys a PHP session and clears its data to log users out sanitizeString Removes potentially malicious code or tags from user input showProfile Displays a user’s image and “about me” message if he has one All of read more..

  • Page - 686

    $result = $connection->query($query); if (!$result) die($connection->error); return $result; } function destroySession() { $_SESSION=array(); if (session_id() != "" || isset($_COOKIE[session_name()])) setcookie(session_name(), '', time()-2592000, '/'); session_destroy(); } function sanitizeString($var) { read more..

  • Page - 687

    that is actually included by the other files and it includes functions.php. This means that only a single require_once is needed in each file. header.php starts by calling the function session_start . As you’ll recall from Chap‐ ter 12, this sets up a session that will remember certain values we want stored across different PHP files. With the session started, the program read more..

  • Page - 688

    echo "<title>$appname$userstr</title><link rel='stylesheet' " . "href='styles.css' type='text/css'>" . "</head><body><center><canvas id='logo' width='624' " . "height='96'>$appname</canvas></center>" . read more..

  • Page - 689

    It is very likely that you will need to add many more columns to these tables if you choose to expand on this project. If so, you may need to issue a MySQL DROP TABLE command before re-creating a table. Example 26-3. setup.php <!DOCTYPE html> <html> <head> <title>Setting up database</title> </head> <body> <h3>Setting read more..

  • Page - 690

    For this example to work, you must first ensure that you have already created the database specified in the variable $dbname in Example 26-1, and also have granted access to it by the user given the name in $dbuser , with the password in $dbpass . index.php This file is a trivial file but necessary nonetheless to give the project a home page. All it does is read more..

  • Page - 691

    Figure 26-1. The main page of the site signup.php Now we need a module to enable users to join the new network, and that’s Example 26-5, signup.php. This is a slightly longer program, but you’ve seen all its parts before. Let’s start by looking at the end block of HTML. This is a simple form that allows a username and password to be entered. But note read more..

  • Page - 692

    Next a request is made to the program checkuser.php, which reports whether the user‐ name user is available. The returned result of the Ajax call, a friendly message, is then placed in the info span. After the JavaScript section comes some PHP code that you should recognize from the Chapter 16 discussion of form validation. This section also uses the sanitize String read more..

  • Page - 693

    if (this.readyState == 4) if (this.status == 200) if (this.responseText != null) O('info').innerHTML = this.responseText } request.send(params) } function ajaxRequest() { try { var read more..

  • Page - 694

    onBlur='checkUser(this)'><span id='info'></span><br> <span class='fieldname'>Password</span> <input type='text' maxlength='16' name='pass' value='$pass'><br> _END; ?> <span class='fieldname'>&nbsp;</span> <input type='submit' value='Sign up'> </form></div><br> </body> </html> Figure read more..

  • Page - 695

    checkuser.php To go with signup.php, here’s Example 26-6, checkuser.php, which looks up a username in the database and returns a string indicating whether it has already been taken. Because it relies on the functions sanitizeString and queryMysql , the program first includes the file functions.php. Then, if the $_POST variable user has a value, the function looks it up read more..

  • Page - 696

    You may be interested in the use of the die function upon successfully logging in. This is there because it combines an echo and an exit command in one, thus saving a line of code. For styling, this (and most of the files) applies the class main to indent the content from the left-hand edge. When you call this program up in your browser, it should look like read more..

  • Page - 697

    ?> <br> <span class='fieldname'>&nbsp;</span> <input type='submit' value='Login'> </form><br></div> </body> </html> Figure 26-3. The login page profile.php One of the first things that new users may want to do after signing up and logging in is to create a profile, which can be done via Example read more..

  • Page - 698

    an image as well as some text. There’s also an input type of file , which creates a Browse button that a user can press to select a file to be uploaded. When the form is submitted, the code at the start of the program is executed. The first thing it does is ensure that a user is logged in before allowing program execution to proceed. Only then is the page read more..

  • Page - 699

    Next, the function imagecreatetruecolor is called to create a new, blank canvas $tw wide and $th high in $tmp . Then imagecopyresampled is called to resample the image from $src , to the new $tmp . Sometimes resampling images can result in a slightly blurred copy, so the next piece of code uses the imageconvolution function to sharpen the image up a bit. Finally, the read more..

  • Page - 700

    } else $text = ""; } $text = stripslashes(preg_replace('/\s\s+/', ' ', $text)); if (isset($_FILES['image']['name'])) { $saveto = "$user.jpg"; move_uploaded_file($_FILES['image']['tmp_name'], $saveto); $typeok = TRUE; switch($_FILES['image']['type']) { case "image/gif": $src = read more..

  • Page - 701

    } showProfile($user); echo <<<_END <form method='post' action='profile.php' enctype='multipart/form-data'> <h3>Enter or edit your details and/or upload an image</h3> <textarea name='text' cols='50' rows='3'>$text</textarea><br> _END; ?> Image: <input type='file' name='image' size='14'> <input type='submit' value='Save Profile'> read more..

  • Page - 702

    members.php Using Example 26-9, members.php, your users will be able to find other members and choose to add them as friends (or drop them if they are already friends). This program has two modes. The first lists all members and their relationships to you, and the second shows a user’s profile. Viewing a User’s Profile The code for the latter mode comes first, read more..

  • Page - 703

    When you call Example 26-9 up in a browser, it will look like Figure 26-5. See how the user is invited to “follow” a nonfollowing member, but if the member is already following the user, a “recip” link to reciprocate the friendship is offered. In the case of a user already following another member, the user can select “drop” to end the follow‐ ing. Example 26-9. read more..

  • Page - 704

    $row = $result->fetch_array(MYSQLI_ASSOC); if ($row['user'] == $user) continue; echo "<li><a href='members.php?view=" . $row['user'] . "'>" . $row['user'] . "</a>"; $follow = "follow"; $result1 = queryMysql("SELECT * FROM friends WHERE user='" . $row['user'] . "' AND read more..

  • Page - 705

    Figure 26-5. Using the members module On a production server, there could be thousands or even hun‐ dreds of thousands of users, so you would probably substantially modify this program to include searching the “about me” text, sup‐ port paging of the output a screen at a time, and so on. friends.php The module that shows a user’s friends and followers is Example read more..

  • Page - 706

    The array_intersect function extracts all members common to both arrays and returns a new array containing only those people. This array is then stored in $mutual . Now it’s possible to use the array_diff function for each of the $followers and $following arrays to keep only those people who are not mutual friends, like this: $followers = array_diff($followers, $mutual); read more..

  • Page - 707

    $followers = array(); $following = array(); $result = queryMysql("SELECT * FROM friends WHERE user='$view'"); $num = $result->num_rows; for ($j = 0 ; $j < $num ; ++$j) { $row = $result->fetch_array(MYSQLI_ASSOC); $followers[$j] = $row['friend']; } $result = queryMysql("SELECT * FROM friends WHERE read more..

  • Page - 708

    if (!$friends) echo "<br>You don't have any friends yet.<br><br>"; echo "<a class='button' href='messages.php?view=$view'>" . "View $name2 messages</a>"; ?> </div><br> </body> </html> Figure 26-6. Displaying a user’s friends and followers messages.php The last of the main modules is Example 26-11, read more..

  • Page - 709

    whether a message is private or public. A 0 represents a public message, and 1 is pri‐ vate. Next, the user’s profile and a form for entering a message are displayed, along with radio buttons to choose between a private or public message. After this, all the mes‐ sages are shown, depending on whether they are private or public. If they are public, all users can read more..

  • Page - 710

    } echo "<div class='main'><h3>$name1 Messages</h3>"; showProfile($view); echo <<<_END <form method='post' action='messages.php?view=$view'> Type here to leave a message:<br> <textarea name='text' cols='40' rows='3'></textarea><br> Public<input type='radio' name='pm' value='0' read more..

  • Page - 711

    ?> </div><br> </body> </html> Figure 26-7. The messaging module logout.php The final ingredient in our social networking recipe is Example 26-12, logout.php, the logout page that closes a session and deletes any associated data and cookies. The result of calling up this program is shown in Figure 26-8, where the user is now asked to click a read more..

  • Page - 712

    Example 26-12. logout.php <?php require_once 'header.php'; if (isset($_SESSION['user'])) { destroySession(); echo "<div class='main'>You have been logged out. Please " . "<a href='index.php'>click here</a> to refresh the screen."; } else echo "<div class='main'><br>" . "You read more..

  • Page - 713

    body Sets the width of the project window, centers it horizontally, specifies a background color, and gives it a border. html Sets the background color of the HTML section. img Gives all images a border, shadow, and a righthand margin. li a and .button Remove underlines from hyperlinks in all <a> tags that are within a <li> element, and all elements employing the read more..

  • Page - 714

    Example 26-13. styles.css * { font-family:verdana,sans-serif; font-size :14pt; } body { width :700px; margin :20px auto; background:#f8f8f8; border :1px solid #888; } html { background:#fff } img { border :1px solid black; margin-right :15px; -moz-box-shadow :2px 2px 2px #888; read more..

  • Page - 715

    .info { background :lightgreen; color :blue; border :1px solid green; padding :5px 10px; margin-left:40px; } .menu li, .button { display :inline; padding :4px 6px; border :1px solid #777; background :#ddd; color read more..

  • Page - 716

    Example 26-14. javascript.js canvas = O('logo') context = canvas.getContext('2d') context.font = 'bold italic 97px Georgia' context.textBaseline = 'top' image = new Image() image.src = 'robin.gif' image.onload = function() { gradient = read more..

  • Page - 717

    APPENDIX A Solutions to the Chapter Questions Chapter 1 Answers 1. A web server (such as Apache), a server-side scripting language (PHP), a database (MySQL), and a client-side scripting language (JavaScript). 2. HyperText Markup Language: the web page itself, including text and markup tags. 3. Like nearly all database engines, MySQL accepts commands in Structured Query Language (SQL). read more..

  • Page - 718

    Chapter 2 Answers 1. WAMP stands for Windows, Apache, MySQL, and PHP. M in MAMP stands for Mac instead of Windows; and the L in LAMP stands for Linux. They all refer to a complete solution for hosting dynamic web pages. 2. Both and http://localhost are ways of referring to the local computer. When a WAMP or MAMP is properly configured, you can type read more..

  • Page - 719

    9. You cannot use spaces in variable names, as this would confuse the PHP parser. Instead, try using the _ (underscore). 10. To convert one variable type to another, reference it and PHP will automatically convert it for you. 11. There is no difference between ++$j and $j++ unless the value of $j is being tested, assigned to another variable, or passed as a parameter read more..

  • Page - 720

    4. The best way to force your own operator precedence is to place parentheses around subexpressions to which you wish to give high precedence. 5. Operator associativity refers to the direction of processing (left to right, or right to left). 6. You use the identity operator when you wish to bypass PHP’s automatic operand type changing (also called type casting). 7. The three read more..

  • Page - 721

    methods) as well as variables (which are called properties), all combined in a single unit. 7. To create a new object in PHP, use the new keyword like this: $object = new Class; 8. To create a subclass, use the extends keyword with syntax such as this: class Subclass extends Parentclass ... 9. To call a piece of initializing code when an object is created, create read more..

  • Page - 722

    2. To take the input string "Happy Birthday" and output the string "**Happy" , you could use a printf statement such as this: printf("%'*7.5s", "Happy Birthday"); 3. To send the output from printf to a variable instead of to a browser, you would use sprintf instead. 4. To create a Unix timestamp for 7:11 a.m. on May 2nd, 2016, you could read more..

  • Page - 723

    5. The purpose of a MySQL index is to substantially decrease database access times by maintaining indexes of one or more key columns, which can then be quickly searched to locate rows within a table. 6. A FULLTEXT index enables natural-language queries to find keywords, wherever they are in the FULLTEXT column(s), in much the same way as using a search engine. 7. A stopword read more..

  • Page - 724

    5. In a one-to-many relationship, the primary key from the table on the “one” side must be added as a separate column (a foreign key) to the table on the “many” side. 6. To create a database with a many-to-many relationship, you create an intermedi‐ ary table containing keys from two other tables. The other tables can then refer‐ ence each other via the third. read more..

  • Page - 725

    Chapter 11 Answers 1. The associative arrays used to pass submitted form data to PHP are $_GET for the GET method and $_POST for the POST method. 2. The register_globals setting was the default in versions of PHP prior to 4.2.0. It was not a good idea, because it automatically assigned submitted form-field data to PHP variables, thus opening up a security hole for read more..

  • Page - 726

    5. The hash function is a powerful security measure, because it is a one-way function that converts a string to a 32-character hexadecimal number that cannot be con‐ verted back, and is therefore almost uncrackable. 6. When a string is salted, extra characters (known only by the programmer) are added to it before hash conversion. This makes it nearly impossible for a read more..

  • Page - 727

    history.back() history.go(-1) 10. To replace the current document with the main page at the oreilly.com website, you could use the following command: document.location.href = 'http://oreilly.com' Chapter 14 Answers 1. The most noticeable difference between Boolean values in PHP and JavaScript is that PHP recognizes the keywords TRUE , true , FALSE , and false , whereas only true and read more..

  • Page - 728

    Chapter 15 Answers 1. JavaScript functions and variable name are case-sensitive. The variables Count , count , and COUNT are all different. 2. To write a function that accepts and processes an unlimited number of parameters, access parameters through the arguments array, which is a member of all func‐ tions. 3. One way to return multiple values from a function is to place read more..

  • Page - 729

    3. Regular expressions to match characters not in a word could be any of /[^\w]/ , / [\W]/ , /[^a-zA-Z0-9_]/ , and so on. 4. A regular expression to match either of the words fox or fix could be /f[oi]x/ . 5. A regular expression to match any single word followed by any nonword character could be /\w+\W/g . 6. A JavaScript function using regular expressions to test read more..

  • Page - 730

    8. To specify a callback function to handle Ajax responses, assign the function name to the XMLHttpRequest object’s onreadystatechange property. You can also use an unnamed, inline function. 9. To initiate an Ajax request, an XMLHTTPRequest object’s send method is called. 10. The main differences between an Ajax GET and POST request are that GET requests append the read more..

  • Page - 731

    Chapter 19 Answers 1. The CSS3 operators ^= , $= , and *= match the start, end, or any portion of a string, respectively. 2. The property you use to specify the size of a background image is background- size , like this: background-size:800px 600px; 3. You can specify the radius of a border using the border-radius property: border-radius:20px; 4. To flow text over multiple read more..

  • Page - 732

    transition:all .5s linear; Chapter 20 Answers 1. The O function returns an object by its ID, the S function returns the style prop‐ erty of an object, and the C function returns an array of all objects that access a given class. 2. You can modify a CSS attribute of an object using the setAttribute function, like this: myobject.setAttribute('font-size', '16pt') You can read more..

  • Page - 733

    Chapter 21 Answers 1. The symbol commonly used as the factory method for creating jQuery objects is $ . Alternatively, you can use the method name jQuery . 2. To link to minified release 1.11.1 of jQuery from the Google CDN, you could use HTML such as this: <script src='http://ajax.googleapis.com/ajax/libs/jquery/ 1.11.1/jquery.min.js'></script> 3. The jQuery $ factory method read more..

  • Page - 734

    2. You need to use JavaScript to access many of the new HTML5 technologies such as the canvas and geolocation. 3. To incorporate audio or video in a web page, you use the <audio> or <video> tags. 4. In HTML5, local storage offers far greater access to local user space than cookies, which are limited in the amount of data they can hold. 5. In HTML5, you read more..

  • Page - 735

    6. To adjust the width of drawn lines, assign a value to the lineWidth property of the context, like this: context.lineWidth = 5 7. To ensure that future drawing takes place only within a certain area, you can create a path and then call the clip method. 8. A complex curve with two imaginary attractors is called a Bézier curve. T o create one, call the bezierCurveTo read more..

  • Page - 736

    2. To determine whether or not a browser supports local storage, test the typeof property of the localStorage object, like this: if (typeof localStorage == 'undefined') // Local storage is not available} 3. To erase all local storage data for the current domain, you can call the localStor age.clear method. 4. Web workers communicate with a main program most easily using read more..

  • Page - 737

    APPENDIX B Online Resources This appendix lists useful websites where you can get the material used in this book, or other resources that will enhance your web programs. PHP Resource Sites • http://codewalkers.com • http://developer.yahoo.com/php/ • http://easyphp.org • http://forums.devshed.com • http://free-php.net • http://hotscripts.com/category/php/ • http://htmlgoodies.com/beyond/php/ • read more..

  • Page - 738

    MySQL Resource Sites • http://launchpad.net/mysql • http://mysql.com • http://php.net/mysql • http://planetmysql.org • http://oracle.com/us/sun • http://w3schools.com/PHP/php_mysql_intro.asp JavaScript Resource Sites • http://developer.mozilla.org/en/JavaScript • http://dynamicdrive.com • http://javascript.about.com • http://javascript.internet.com • http://javascript.com • http://javascriptkit.com • read more..

  • Page - 739

    • http://html5readiness.com • http://html5demos.com • http://html5-demos.appspot.com • http://modernizr.com • http://html5doctor.com AJAX Resource Sites • http://ajax.asp.net • http://ajaxian.com • http://ajaxmatters.com • http://developer.mozilla.org/en/AJAX • http://dojotoolkit.org • http://jquery.com • http://mochikit.com • http://mootools.net • http://openjs.com • http://prototypejs.org • read more..

  • Page - 740

    • http://putty.org O’Reilly Resource Sites • http://onlamp.com • http://onlamp.com/php • http://onlamp.com/onlamp/general/mysql.csp • http://oreilly.com/ajax • http://oreilly.com/javascript • http://oreilly.com/mysql • http://oreilly.com/php • http://oreillynet.com/javascript 710 | Appendix B: Online Resources read more..

  • Page - 741

    APPENDIX C MySQL’s FULLTEXT Stopwords This appendix contains the more than 500 stopwords referred to in the section “Creat‐ ing a FULLTEXT index” on page 191 in Chapter 8. Stopwords are words that are con‐ sidered so common as to not be worth searching for, or storing, in a FULLTEXT index. Theoretically, ignoring these words makes little difference to the read more..

  • Page - 742

    E each, edu, eg, eight, either, else, elsewhere, enough, entirely, especially, et, etc, even, ever, every, everybody, everyone, everything, everywhere, ex, exactly, example, except F far, few, fifth, first, five, followed, following, follows, for, former, formerly, forth, four, from, further, furthermore G get, gets, getting, given, gives, go, goes, going, gone, got, gotten, greetings H had, read more..

  • Page - 743

    R rather, rd, re, really, reasonably, regarding, regardless, regards, relatively, respectively, right S said, same, saw, say, saying, says, second, secondly, see, seeing, seem, seemed, seeming, seems, seen, self, selves, sensible, sent, serious, seriously, seven, several, shall, she, should, shouldn’t, since, six, so, some, somebody, somehow, someone, something, sometime, sometimes, somewhat, read more..

  • Page - 744

    read more..

  • Page - 745

    APPENDIX D MySQL Functions Having functions built into MySQL substantially reduces the speed of performing complex queries, as well as their complexity. If you wish to learn more about the available functions, you can visit the following URLs: • String functions: tinyurl.com/phpstringfuncs • Date and time: tinyurl.com/phpdateandtime But, for easy reference, here are some of the most read more..

  • Page - 746

    LEFT( str, len) Returns the leftmost len characters from the string str (or NULL if any argument is NULL ). The following code returns the string "Chris" : SELECT LEFT('Christopher Columbus', '5'); RIGHT( str, len) Returns the rightmost len characters from the string str (or NULL if any argu‐ ment is NULL ). This code returns the string "Columbus" : read more..

  • Page - 747

    SELECT RPAD('Hi', '5', '!'); LOCATE( substr, str, pos) Returns the position of the first occurrence of substr in the string str . If the parameter pos is passed, the search begins at position pos . If substr is not found in str , a value of 0 is returned. This code returns the values 5 and 11 , because the first function call returns the first encounter of read more..

  • Page - 748

    SELECT REPLACE('Cheeseburger and Fries', 'Fries', 'Soda'); TRIM([ specifier remove FROM] str) Returns the string str with all prefixes or suffixes removed. The specifier can be one of BOTH , LEADING , or TRAILING . If no specifier is supplied, then BOTH is assumed. The remove string is optional and, if omitted, spaces are removed. This code returns the strings "No read more..

  • Page - 749

    rectly interpret them. If you are ever in doubt, adding the quotes will always work. Table D-1. Expected expr values Type Expected expr value Example MICROSECOND MICROSECONDS 111111 SECOND SECONDS 11 MINUTE MINUTES 11 HOUR HOURS 11 DAY DAYS 11 WEEK WEEKS 11 MONTH MONTHS 11 QUARTER QUARTERS 1 YEAR YEARS 11 SECOND_MICROSECOND 'SECONDS.MICROSECONDS' 11.22 MINUTE_MICROSECOND 'MINUTES.MICROSECONDS' 11.22 read more..

  • Page - 750

    Notice how the last two commands use date arithmetic directly without recourse to functions. DATE_FORMAT( date, format) This returns the date value formatted according to the format string. Table D-2 shows the specifiers that can be used in the format string. Note that the % charac‐ ter is required before each specifier, as shown. This code returns the given date and read more..

  • Page - 751

    Specifier Description %w Day of the week (0=Sunday–6=Saturday) %X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V %x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v %Y Year, numeric, four digits %y Year, numeric, read more..

  • Page - 752

    MAKEDATE( year, dayofyear) Returns a date given year and dayofyear values. If dayofyear is 0, the result is NULL . This code returns the date 2016-10-01 : SELECT MAKEDATE(2018,274); MONTH( date) Returns the month for date in the range 1 through 12 for January through December. Dates that have a zero month part, such as 0000-00-00 or 2016-00-00, return 0 . This code returns read more..

  • Page - 753

    Mode First day of week Range Where week 1 is the first week... 2 Sunday 1–53 with a Sunday in this year 3 Monday 1–53 with more than three days this year 4 Sunday 0–53 with more than three days this year 5 Monday 0–53 with a Monday in this year 6 Sunday 1–53 with more than three days this year 7 Monday 1–53 read more..

  • Page - 754

    SELECT MAKETIME(11, 56, 23); TIMEDIFF( expr1, expr2) Returns the difference between expr1 and expr2 (expr1 – expr2 ) as a time value. Both expr1 and expr2 must be TIME or DATETIME expressions of the same type. This code returns the value 01:37:38 . SELECT TIMEDIFF('2000-01-01 01:02:03', '1999-12-31 23:24:25'); UNIX_TIMESTAMP([ date]) If called without the optional date read more..

  • Page - 755

    APPENDIX E jQuery Selectors, Objects, and Methods Chapter 21 gives you a good grounding in using the jQuery JavaScript Library. To help get you started with using jQuery to the best effect, here’s a comprehensive list of the selectors, objects, and methods it uses, a number of which there wasn’t room to introduce in this book, but you are ready for them, because read more..

  • Page - 756

    ('prev + next') Selects all next elements matching next that are immediately preceded by a sibling prev . ('prev ~ siblings') Selects all sibling elements that follow after the prev element, have the same parent, and match the filtering siblings selector. ('parent > child') Selects all direct child elements specified by child of elements specified by parent . [name] Selects read more..

  • Page - 757

    :button Selects all button elements and elements of type button . :checkbox Selects all elements of type checkbox . :checked Matches all elements that are checked or selected . :contains( text) Selects all elements that contain the specified text . :disabled Selects all elements that are disabled. :empty Selects all elements that have no children (including text nodes). :enabled Selects all read more..

  • Page - 758

    :header Selects all elements that are headers, like h1 , h2 , h3 , and so on. :hidden Selects all elements that are hidden. :input Selects all inpu t, textarea , select , and button elements. :lang( language) Selects all elements of the specified language . :last-child Selects all elements that are the last child of their parent. :last-of-type Selects all elements that are the last read more..

  • Page - 759

    :only-of-type Selects all elements that have no siblings with the same element name. :parent Selects all elements that have at least one child node (either an element or text). :password Selects all elements of type password . :radio Selects all elements of type radio . :reset Selects all elements of type reset . :root Selects the element that is the root of the document. :selected read more..

  • Page - 760

    event.namespace The namespace specified when the event was triggered. event.pageX The mouse position relative to the left edge of the document. event.pageY The mouse position relative to the top edge of the document. event.relatedTarget The other DOM element involved in the event, if any. event.result The last value returned by an event handler that was triggered by this event, unless read more..

  • Page - 761

    jQuery Methods $ Returns a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. add Adds elements to the set of matched elements. addBack Adds the previous set of elements on the stack to the current set, optionally filtered by a selector. addClass Adds the specified class(es) to each of the set of matched read more..

  • Page - 762

    attr Gets the value of an attribute for the first element in the set of matched elements or sets one or more attributes for every matched element. before Inserts content, specified by the parameter, before each element in the set of matched elements. bind Attaches a handler to an event for the elements. blur Binds an event handler to the blur JavaScript event, or triggers read more..

  • Page - 763

    dblclick Binds an event handler to the dblclick JavaScript event, or triggers that event on an element. callbacks.add Adds a callback or a collection of callbacks to a callback list. callbacks.disable Disables a callback list from doing anything more. callbacks.disabled Determines if the callback list has been disabled. callbacks.empty Removes all of the callbacks from a list. callbacks.fire read more..

  • Page - 764

    deferred.notifyWith Calls the progressCallbacks on a Deferred object with the given context and argu‐ ments. deferred.progress Adds handlers to be called when the Deferred object generates progress notifica‐ tions. deferred.promise Returns a Deferred ’s Promise object. deferred.reject Rejects a Deferred object and calls any failCallbacks with the given arguments. deferred.rejectWith read more..

  • Page - 765

    empty Removes all child nodes of the set of matched elements from the DOM. end Ends the most recent filtering operation in the current chain and returns the set of matched elements to its previous state. eq Reduces the set of matched elements to the one at the specified index. event.isDefaultPrevented Returns whether preventDefault was ever called on this event object. read more..

  • Page - 766

    finish Stops the currently running animation, removes all queued animations, and com‐ pletes all animations for the matched elements. first Reduces the set of matched elements to the first in the set. focus Binds an event handler to the focus JavaScript event, or triggers that event on an ele‐ ment. Selects element if it is currently focused. focusin Binds an event handler to read more..

  • Page - 767

    innerWidth Gets the current computed inner width (including padding but not border) for the first element in the set of matched elements or sets the inner width of every matched element. insertAfter Inserts every element in the set of matched elements after the target. insertBefore Inserts every element in the set of matched elements before the target. is Checks the current matched read more..

  • Page - 768

    jQuery.Deferred A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. jQuery.dequeue Executes the next function on the queue for the matched element. jQuery.each A generic iterator function, which can be used to read more..

  • Page - 769

    jQuery.inArray Searches for a specified value within an array and returns its index (or -1 if not found). jQuery.isArray Determines whether the argument is an array. jQuery.isEmptyObject Checks to see if an object is empty (contains no enumerable properties). jQuery.isFunction Determines if the argument passed is a JavaScript function object. jQuery.isNumeric Determines whether its argument is read more..

  • Page - 770

    jQuery.parseJSON Takes a well-formed JSON string and returns the resulting JavaScript object. jQuery.parseXML Parses a string into an XML document. jQuery.post Loads data from the server using an HTTP POST request. jQuery.queue Shows or manipulates the queue of functions to be executed on the matched element. jQuery.removeData Removes a previously stored piece of data. jQuery.trim Removes the read more..

  • Page - 771

    map Passes each element in the current matched set through a function, producing a new jQuery object containing the return values. mousedown Binds an event handler to the mousedown JavaScript event, or triggers that event on an element. mouseenter Binds an event handler to be fired when the mouse enters an element, or triggers that handler on an element. mouseleave Binds an event read more..

  • Page - 772

    offset Gets the current coordinates of the first element, or sets the coordinates of every ele‐ ment, in the set of matched elements, relative to the document. offsetParent Gets the closest ancestor element that is positioned. on Attaches an event handler function for one or more events to the selected elements. one Attaches a handler to an event for the elements. The handler read more..

  • Page - 773

    prevAll Gets all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. prevUntil Gets all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. promise Returns a Promise object to observe when all actions of a certain type bound to the collection, queued or read more..

  • Page - 774

    resize Binds an event handler to the resize JavaScript event, or triggers that event on an element. scroll Binds an event handler to the scroll JavaScript event, or trigger that event on an ele‐ ment. scrollLeft Gets the current horizontal position of the scroll bar for the first element in the set of matched elements or sets the horizontal position of the scroll bar for read more..

  • Page - 775

    submit Binds an event handler to the submit JavaScript event, or triggers that event on an element. text Gets the combined text contents of each element in the set of matched elements, including their descendants, or sets the text contents of the matched elements. toArray Retrieves all the elements contained in the jQuery set, as an array. toggle Displays or hides the matched read more..

  • Page - 776

    wrapAll Wraps an HTML structure around all elements in the set of matched elements. wrapInner Wraps an HTML structure around the content of each element in the set of matched elements. 746 | Appendix E: jQuery Selectors, Objects, and Methods read more..

  • Page - 777

    Index Symbols ! (Not) logical operator in JavaScript, 319, 334, 336 in PHP, 47, 68, 73, 89 != (inequality) operator in JavaScript, 319, 334 in PHP, 46, 68, 68, 71 !== (not identical) operator in JavaScript, 319, 334 in PHP, 68, 71 " (quotation marks, double) enclosing multiple-line commands in PHP, 50 enclosing strings in JavaScript, 316 enclosing strings in PHP, 40, 49 escaping in read more..

  • Page - 778

    parameter in MySQL commands, 192 regular expression metacharacter, 378 wildcard or universal selector in CSS, 424, 444 * (multiplication) operator in JavaScript, 318, 334 in PHP, 45, 67, 68 *= (attribute selector) operator in CSS, 453 *= (multiplication and assignment) operator in JavaScript, 318 in PHP, 68 + (addition) operator in JavaScript, 318, 334 in PHP, 45, 67, 68 + (plus sign) read more..

  • Page - 779

    in PHP, 68 <<< (heredoc) operator in PHP, 51 <<= (bitwise left shift and assignment) operator in JavaScript, 334 in PHP, 68 <= (less than or equal to) operator in JavaScript, 319, 334, 336 in PHP, 46, 68, 72 <> (not equal) operator (PHP), 68 = (assignment) operator, 318 in JavaScript, 318, 334 not confusing with == operator, 335 in PHP, 45, 68, 70, 70 == (equality) operator in read more..

  • Page - 780

    A AAC (audio) codec, 618 absolute positioning of elements, 440 active pseudo-class (CSS), 443 ActiveX, 395 addClass method (jQuery), 535 addition operator (+) in JavaScript, 318 in PHP, 45, 68 after method (jQuery), 533, 534 Ajax, xxiii, 5 about, 395 checking for username availability on email account, 12-14 defined, 9 GET request, 403-406 sending XML requests, 406-410 using frameworks for, read more..

  • Page - 781

    multidimensional, 129 walking through, using foreach, 127 associativity (operator), 69, 334 attr method (jQuery), 532 attribute selectors (CSS), 451 matching parts of strings, 452 $= operator, 452 *= operator, 453 ^= operator, 452 attribute seletors (CSS), 423, 426 attributes, HTML elements, 423 microdata attributes, 648 modifying using attr method, 532 audio and video (HTML5), 617-629 <audio> read more..

  • Page - 782

    in default statement for PHP switch state‐ ments, 81 in JavaSript switch statements, 343 in PHP switch statements, 81 browsers, 1 accessing JavaScript error messages, 313 audio types supported, 619 background property names, 457 border radius properties, 462 box shadows, 463 browser/server request/response dialog with cookies, 288 canvas element support, 558, 615 creating XMLHttpRequest object, read more..

  • Page - 783

    character classes in regular expressions, 380, 382 example of, 381 negation of, 380 charAt method (JavaScript), 354 checkboxes, 271 checkdate function (PHP), 146 checkuser.php (social networking site), 665 child selectors (CSS), 421 children method (jQuery), 543 class attribute (HTML), 415 class selectors (CSS), 423, 426 classes, 106 dynamically applying to element using jQuery, 535 in CSS, 415 read more..

  • Page - 784

    += (string concatenation and assignment) operator in JavaScript, 320 . (string concatenation) operator in PHP, 49 .= (string concatenation and ssignment) operator in PHP, 49 CSS properties into a shorthand assignment, 444 conditional operator (see ? : (ternary) operator) conditionals in JavaScript, 341-344 else statement, 341 if statement, 341 switch statement, 342 ternary operator (? :), 344 in read more..

  • Page - 785

    backgrounds, 453-457 borders, 459-462 box shadows, 462 box-sizing property, 453 colors and opacity, 465-467 element overflow, 463 multiple backgrounds, 457-458 multiple-column layout, 463-465 transformations, 472 transitions, 474-477 web fonts, 469 CSV (comma-separated values) format, 227 mysqldump program, dumping data in, 231 cubic-bezier function (CSS), 475 curly braces (see { } in Symbols section) read more..

  • Page - 786

    outerWidth and outerHeight methods, 538 width and height methods, 536 dir system command (Windows), 160 display property (CSS), 491 DISTINCT keyword (MySQL), 193 DISTINCTROW keyword (MySQL), 193 <div> tags class attribute, 415 foreground color of text, 437 id attribute, 415 inserting new div element into the DOM, 489 style settings within, 415 versus <span> elemen ts, 429 division read more..

  • Page - 787

    closing if...else or if...elseif...else, 79 elseif statements (PHP), 78 em (CSS measurement), 431 email address, validating on forms, 376 embedded styles (CSS), 415 order of precedence, 426 empty method (jQuery), 533, 535 encapsulation, 106 end function (PHP), 136 _END ... _END tags in heredoc construct in PHP, 51 endswitch command in PHP switch statement, 81 ENGINE MyISAM (MySQL), 175 eq read more..

  • Page - 788

    FireFTP, 29 first method (jQuery), 547 First Normal Form, 212 fixed positioning of elements, 440 Flash, 617 fallback video player for non-HTML5 browsers, 627 providing for non-HTML5 browsers, 621 flat files, 7 float property (CSS), 442 flock function (PHP), 153 focus pseudo-class (CSS), 443 universal selector (*) and, 444 font property (context object), 579 @font-face directive (CSS), 469 read more..

  • Page - 789

    function_exists function (PHP), 105 fuzzy character mapping, 378 fwrite function (PHP), 148 G GD (Graphics Draw) library, 11 geolocation, 559-561, 631-636 $_GET array (PHP), 244 assigning to PHP global variable, security issues, 268 security concerns, 277 $.get method (jQuery), 517, 552 GET method (HTTP), 243, 265 Ajax GET request, 403-406 getElementById function (JavaScript), 326, 401, 423 read more..

  • Page - 790

    HTML injection, preventing in MySQL, 259 <html> tags, manifest file in, 642 HTML5, 10, 558 (see also canvas) about, 557 audio and video, 617-629 <audio> and <video> elemen ts, 561 browser support for, 615 cross document messaging, 645-648 DOCTYPE declaration, 413 drag and drop, 643-645 form handling enhancements, 281-285 features awaiting full implementation, 283-285 forms, 562 read more..

  • Page - 791

    index.php (social networking site), 660 indexes array, 44, 317 associative arrays in PHP, 126 MySQL, 186-192 purposes of, 214 indexOf function (JavaScript), 376 inequality operator (!=) in JavaScript, 334 in PHP, 46, 68, 71 inheritance, 107 in PHP, 118-121 ini_set function (PHP), 303, 306 inline JavaScript, 486-489 inline styles (CSS), 420 order of precedence, 426 innerHeight method (jQuery), 538 read more..

  • Page - 792

    looping in, 344-348 objects, 356, 361 onerror event, 339 operators, 318-321, 333-338 placing at end of HTML pages, 510 playing HTML5 audio with, 620 removing elements from the DOM, 490 semicolons (;) ending statements, 315 social networking site file (javascript.js), 685 try ... catch construct, 340 using in dynamic web content, 8 using regular expressions in, 386 validating user input, read more..

  • Page - 793

    Linux, Apache, MySQL, and PHP (see LAMPs) list attribute, <input> elemen t, 284 list function (PHP), using with each function, 128 literals in JavaScript, 332 in PHP, 65 local storage (HTML5), 563, 636-639 localStorage object, 637 local variables, 103 in JavaScript, 323, 355 in PHP, 57 localhostt in URLs, 25 LOCK TABLES command (MySQL), 228, 230 locks file locking with flock function read more..

  • Page - 794

    final methods, 121 overriding and using parent operator, 119 scope, 115 static methods, 113, 117 writing, 112 microdata, 564, 648-651 Microsoft CDN, jQuery on, 502 millimeters (CSS measurement), 431 min and max attributes, <input> elemen t, 284 miterLimit property (context object), 584 mktime function (PHP), 144 mobile devices, Apple iOS and Google Android, 15 modifiers (general) for regular read more..

  • Page - 795

    naming rules variables in JavaScript, 316 variables in PHP, 44 NATURAL JOIN keyword (MySQL), 203, 255 new keyword (PHP), 108 next method (jQuery), 545 nextAll method (jQuery), 546 nextUntil method (jQuery), 546 noConflict method (jQuery), 505 non-looping conditionals, 74 normalization First Normal Form, 212 Second Normal Form, 214 Third Normal Form, 217 when not to use, 219 <noscript> tags, read more..

  • Page - 796

    escaping characters, 320 logical operators, 319, 336 precedence, 334 relational operators, 335-338 string concatenation, 320 types of, 333 in PHP, 45, 66-74 arithmetic operators, 45 assignment operators, 45 associativity, 69 comparison operators, 46 logical operators, 46 precedence, 67 relational operators, 70 types of, 66 or (low precedence) logical operator (PHP), 47, 68, 73 Or (||) logical operator read more..

  • Page - 797

    symbiosis with MySQL, 5 syntax $ symbol, 39 semicolons (;), 39 system calls, 160 using, 6 using for dynamic web content, 11 using regular expressions in, 386 validating form data, 387-391 variable assignment, 48 variable scope, 56-62 variable typing, 52 variables, 40-45 working with MySQL, JavaScript, CSS, and HTML5, 12 XHTML or HTML5, 162 <?php and ?> tags, 234 <?php> <?> tags, read more..

  • Page - 798

    protected keyword (PHP), 116 prototype keyword (JavaScript), 358, 361 pseudo-classes (CSS), 442, 451 pseudo-elements (CSS), 442, 451 pseudofunctions, 96 public keyword (PHP), 107, 116 Pulse Coded Modulation (PCM) codec, 618 push method (JavaScript), 361, 366 putImageData method, context object, 605 PuTTY, 28 Q quadraticCurveTo method, context object, 595 querying MySQL databases using PHP, 233-240, read more..

  • Page - 799

    REVOKE command (MySQL), 175 RGB colors, 437, 465 in CSS3, 466 rgb function (CSS), 437, 466 RGBA colors, 465, 467 rgba function (CSS), 467 ROLLBACK command (MySQL), 225 rotate function (CSS), 472 rotate method, context object, 611, 615 rotate3d function (CSS), 473 rows (database), 165 rows (MySQL), fetching results as, 239 rsort function (PHP), 133 rules (CSS), 416 calculating specificity read more..

  • Page - 800

    repeating timeouts, 493 setTransform method, context object, 615 setup.php (social networking site), 658 sha1 and sha2 hashing algorithms, 294 shadows, adding to images in HTML5 canvas, 600 SHOW comand (MySQL), 185 SHOW command (MySQL), 170 show method (jQuery), 522 shuffle function (PHP), 133 siblings method (jQuery), 543 selecting and filtering sibling elements, 544 using andSelf method with, read more..

  • Page - 801

    creators and order of precedence, 426 external, 419 importing, 414 methods of creation and order of prece‐ dence, 426 styles.css (social networking site), 682 <style> tags, 9 CSS @import directive within, 414 internal styles within, 419 style types (CSS), 418 default styles, 418 external style sheets, 419 inline styles, 420 internal styles, 419 user styles, 418 subclasses, 107 constructors, read more..

  • Page - 802

    Third Normal Form, 217 third-party cookies, 287 this keyword (JavaScript), 357, 401, 486 $this variable (PHP), 113 TIME data type (MySQL), 180 time function (PHP), 56, 143 time functions (MySQL), 723-724 timeouts canceling, 493 repeating with setTimeout, 493 setting for sessions, 303 setting with setTimeout, 492 TIMESAMP data type (MySQL), 180 timestamps creating, 144 fetching, 143 toDataURL read more..

  • Page - 803

    form data using PHP, 387-392 form input with JavaScript, 371-377 value attribute, <input> elemen t, 392 VALUES keyword (MySQL), 183 var keyword in JavaScript, 323, 324 in PHP, 116 VARCHAR data type (MySQL), 177, 185 versus TEXT type, 178 variable substitution, 49 variables in JavaScript, 316-318 arrays, 317 expressions as variables, 332 incrementing and decrementing, 320 naming rules, 316 read more..

  • Page - 804

    Windows, Apache, MySQL, and PHP (see WAMPs) with statement (JavaScript), 338 word-spacing property (CSS), 435 word-wrap property (CSS), 469 WordPress blogging platform, 92 World Wide Web Consortium (W3C), 10 X XAMPP accessing MySQL via phpMyAdmin, 205-206 configuring from control panel, 21 installing on Linux, 28 installing on Mac OS X, 27 installing on Windows, 16 likely locations for mysqldump read more..

  • Page - 805

    About the Author Robin Nixon has over 30 years of experience with writing software and developing websites and apps. He also has an extensive history of writing about computers and technology, with a portfolio of over 500 published magazine articles and almost 30 books, many of which have been translated into other languages. He is also a prolific Internet video course read more..

  • Page - 806

    their distinctive scents can be bothersome to humans; as they are nocturnal creatures, they will bark, hiss, run, and glide all night long; it’s not uncommon for them to lose control of their bowels while playing or eating; and in some states and countries, it is illegal to own sugar gliders as household pets. The cover image is from Dover’s Animals. The cover fonts read more..

Write Your Review