Learning PHP, MySQL, JavaScript, CSS & HTML5

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

Robin Nixon

729 Pages

38060 Reads



PDF Format

20.2 MB

Java Script

Download PDF format

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

    read more..

  • Page - 2

    read more..

  • Page - 3

    Robin Nixon THIRD EDITION Learning PHP, MySQL, JavaScript, CSS & HTML5 read more..

  • Page - 4

    Learning PHP, MySQL, JavaScript, CSS & HTML5, Thir d Edition by Robin Nixon Copyright © 2014 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 available for most read more..

  • Page - 5

    For Julie read more..

  • Page - 6

    read more..

  • Page - 7

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

  • Page - 8

    Using a Program Editor 40 Using an IDE read more..

  • Page - 9

    Implicit and Explicit Casting 98 PHP Dynamic Linking read more..

  • Page - 10

    Using Array Functions 140 is_array read more..

  • Page - 11

    Data Types 183 Indexes read more..

  • Page - 12

    Connecting to MySQL 243 A Practical Example read more..

  • Page - 13

    The required Attribute 296 Override Attributes read more..

  • Page - 14

    Assignment Operators 332 Comparison Operators read more..

  • Page - 15

    Defining a Function 363 The arguments Array read more..

  • Page - 16

    Using Semicolons 426 CSS Rules read more..

  • Page - 17

    Relative Positioning 450 Fixed Positioning read more..

  • Page - 18

    Transitions 483 Properties to Transition read more..

  • Page - 19

    Questions 516 23. The HTML5 Canvas. . . . . . . . . . . . . . . . . . . . . . . . . read more..

  • Page - 20

    Adding Shadows 552 Editing at the Pixel Level read more..

  • Page - 21

    Summary 601 Questions read more..

  • Page - 22

    read more..

  • Page - 23

    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 - 24

    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 devel‐ opment 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, cov‐ ering the read more..

  • Page - 25

    • Dynamic HTML: The Definitive Reference by Danny Goodman • PHP in a Nutshell by Paul Hudson • MySQL in a Nutshell by Russell J.T. Dyer • JavaScript: The Definitive Guide by David Flanagan • CSS: The Definitive Guide by Eric A. Meyer • HTML5: The Missing Manual by Matthew MacDonald Conventions Used in This Book The following typographical conventions are used read more..

  • Page - 26

    Using Code Examples Supplemental material (code examples, exercises, etc.) is available at http://lpmj.net. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For read more..

  • Page - 27

    For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Safari® Books O nline Safari Books Online ( www.safaribooksonline.com) is an on- demand digital library that delivers read more..

  • Page - 28

    read more..

  • Page - 29

    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 problem. 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 producing read more..

  • Page - 30

    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 read more..

  • Page - 31

    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 - 32

    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 Here are the steps for a dynamic client/server request/response sequence: 1. You enter http://server.com into your browser’s address bar. 2. Your browser looks up the IP address for read more..

  • Page - 33

    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 - 34

    anything a website would need in order to find and serve up data to browsers. When PHP allies with MySQL to store and retrieve this data, you have the fundamental 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 building highly dynamic and interactive read more..

  • Page - 35

    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 much point to being able to change HTML output dynamically 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 “flat” read more..

  • Page - 36

    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 returned from earlier ones, to drill right down to the item of data you need. For even more power, as you’ll read more..

  • Page - 37

    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 control over the various elements within an HTML document, and that is still its read more..

  • Page - 38

    And Then There’s HTML5 As useful as all these additions to the web standards became, they were not enough for ever more ambitious developers. For example, there was still no simple way to manip‐ ulate graphics in a web browser without resorting to plug-ins such as Flash. And the same went for inserting audio and video into web pages. Plus, several annoying incon‐ read more..

  • Page - 39

    One of the little things I like about the HTML5 specification is that XHTML syntax is no longer required for self-closing elements. In the past you could display a line break using the <br> element. Then, to ensure future compatibility with XHTML (the planned replacement for HTML that never happened), read more..

  • Page - 40

    About Open Source Whether the open source quality of these technologies is the reason they are so popular has often been debated, but PHP, MySQL, and Apache are the three most commonly used tools in their categories. What can be said definitively, though, is that their being open source means that they have been developed in the community by teams of programmers writing read more..

  • Page - 41

    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 necessary details, such as username, first name, last name, and email address. 2. At the same time, the server attaches some JavaScript to the HTML to read more..

  • Page - 42

    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 read more..

  • Page - 43

    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 - 44

    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 - 45

    Throughout this book, whenever there’s a long URL to type, I use the TinyURL web address shortening service to save you time and re‐ duce typos. For example, the URLs http://tinyurl.com/zendfree and http://tinyurl.com/zenddocs are much shorter than the URLs that they lead to: • http://www.zend.com/en/products/server/free-edition • read more..

  • Page - 46

    Once you’ve downloaded the installer, run it to bring up the window shown in Figure 2-2. Figure 2-2. The main installation window of the installer Click Next and accept the license agreement that follows to move on to the Setup Type screen (see Figure 2-3), then select the Custom option so that the MySQL server can also be installed. 18 | Chapter 2: Setting Up a read more..

  • Page - 47

    Figure 2-3. Choose the Custom install option When the Custom Setup window appears, scroll down the list of options to the bottom and ensure that MySQL Server is checked, as shown in Figure 2-4, then click Next. Installing a WAMP on Windows | 19 read more..

  • Page - 48

    Figure 2-4. Check MySQL Server before continuing On the following screen (see Figure 2-5), even if you already have an IIS web server installed, I recommend that you choose to install the Apache web server, because the examples in this book are for Apache. Then click Next. 20 | Chapter 2: Setting Up a Development Server read more..

  • Page - 49

    Figure 2-5. Install the Apache web server Now accept the default values of 80 for the Web Server Port, and 10081 for the Zend Server Interface Port (see Figure 2-6) and click Next. If either of the ports offered states that it is occupied (generally this will be because you have another web server running) and doesn’t allow you to read more..

  • Page - 50

    Figure 2-6. Accept the default values offered for the ports Once the ports have been assigned, you will reach the screen in Figure 2-7, where you should click Install to start the installation. 22 | Chapter 2: Setting Up a Development Server read more..

  • Page - 51

    Figure 2-7. Now you are ready to click Install to proceed During installation some extra files may be downloaded, so it may take a few minutes for the programs to get set up. During installation you might also see a pop-up dialog box from Windows Firewall. If so, accept the request to give it access. When the files have been installed, you will be notified and prompted read more..

  • Page - 52

    Figure 2-8. You must agree to the terms in order to use the server Next, you are asked how you will be using the server. I recommend that you select the Development option for the purposes of working through the exercises in this book (see Figure 2-9). 24 | Chapter 2: Setting Up a Development Server read more..

  • Page - 53

    Figure 2-9. Select the Development option Now you are ready to set a password for the user admin (see Figure 2-10). You do not need to enter a password for the user developer. Make sure you choose a password you will remember and click Next. After the library packages show as deployed, click Next again to proceed to the screen shown in Figure 2-11, where you can read more..

  • Page - 54

    Figure 2-10. Choose your password and enter it twice 26 | Chapter 2: Setting Up a Development Server read more..

  • Page - 55

    Figure 2-11. Click Submit to complete setup After a short wait, your browser will show the Dashboard screen in Figure 2-12, which is where you can administer the server. Installing a WAMP on Windows | 27 read more..

  • Page - 56

    Figure 2-12. The Zend Server administration screen You can return to this screen at any time by entering http://localhost:10081 into your browser. Or, if you entered a value other than 10081 for the Zend Server Interface Port (or 10088 on a Mac), then you can get to this screen by using that value after the colon instead. Testing the Installation The first thing to do read more..

  • Page - 57

    Figure 2-13. How the 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 during installation (e.g., 8080), then you must read more..

  • Page - 58

    By default, Zend Server uses one of the following locations for this directory (the former for 32-bit computers, and the latter for 64-bit): C:/Program Files/Zend/Apache2/htdocs C:/Program Files (x86)/Zend/Apache2/htdocs If you are not sure whether your computer is 32-bit or 64-bit, try to navigate to the first directory and, if it exists, you have read more..

  • Page - 59

    Figure 2-14. Your first web page Alternative WAMPs When software is updated, it sometimes works differently than you’d expected, and bugs can even be introduced. So if you encounter difficulties that you cannot resolve, you may prefer to choose one of the various other solutions available on the Web instead. You will still be able to make use of all the examples in this read more..

  • Page - 60

    Figure 2-15. You can download the server from the Zend website Once the installer is downloaded, double-click the .dmg file and wait for the download to verify, and then you should see the window shown in Figure 2-16. 32 | Chapter 2: Setting Up a Development Server read more..

  • Page - 61

    Figure 2-16. Double-click Zend Server to install it Here you can double-click the README file for instructions, or double-click Zend Server to open up the installation window shown in Figure 2-17. Installing a MAMP on Mac OS X | 33 read more..

  • Page - 62

    Figure 2-17. The Zend Server installer Now click Continue, read the instructions that are displayed, and then click Continue again to reach the screen shown in Figure 2-18, where you can decide where to put the installed software (the default being Macintosh HD). Click Install when you are ready, and enter your password if prompted for it. During installation, you may be asked read more..

  • Page - 63

    Figure 2-18. Choosing the destination for installation Configuring MySQL Unfortunately, the installer doesn’t set up the commands needed to be able to start, stop, and restart the MySQL server, so you’re going to have to do this manually by opening the Terminal and entering the following command: sudo nano /usr/local/zend/bin/zendctl.sh After entering your password you will now be read more..

  • Page - 64

    Then below it, you’ll see an indented line that reads: $0 stop-apache % Just after this line, insert a new one that reads as follows: $0 stop-MySQL % This will allow MySQL to be stopped. Now you can press Ctrl-X to exit from edit mode, press the Y key when prompted to save the changes, and read more..

  • Page - 65

    If you are sure that there isn’t another web server running on your Mac, you can edit the configuration file at the following URL (ensur‐ ing you have permission to do so), changing the command (at around line 40) that reads Listen 10088 to Listen 80 : /usr/local/zend/apache2/conf/httpd.conf You will then read more..

  • Page - 66

    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 slightly different way, so I can’t cover them all in this book. Nonetheless, many Linux versions come preinstalled with a read more..

  • Page - 67

    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 into 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 - 68

    Figure 2-19. 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 in‐ corporate very handy features such as colored syntax highlighting. Today’s program editors are smart and can show you where you have read more..

  • Page - 69

    Figure 2-20. 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 environ‐ read more..

  • Page - 70

    Figure 2-21. When you’re using an IDE such as phpDesigner, PHP development be‐ comes much quicker and easier There are several IDEs available for different platforms, most of which are commercial, but there are some free ones too. Table 2-1 lists some of the most popular PHP IDEs, along with their download URLs. Choosing an IDE can be a very personal thing, so if you read more..

  • Page - 71

    You should take the time to install a program editor or IDE you are comfortable with and you’ll then be ready to try out the examples in the coming chapters. Armed with these tools, you are now ready to move on to Chapter 3, where we’ll start exploring PHP in further depth and find out how to get HTML and PHP to work together, as well as how the PHP read more..

  • Page - 72

    read more..

  • Page - 73

    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 re‐ quests a page. In this chapter, you’ll start learning this simple but powerful language; it will be the topic of the following chapters up through Chapter 7. I encourage you read more..

  • Page - 74

    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 such as an index.html file and save it as index.php, and it will display identically to the original. To trigger the PHP commands, you need to learn read more..

  • Page - 75

    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 ?> . This can be a good practice, as it will ensure that you have no excess whitespace leaking from your PHP files (especially read more..

  • Page - 76

    which you’ll find all the examples I suggest you save using a specific filename (such as the upcoming Example 3-4, which should be saved as test1.php). The Structure of PHP We’re going to cover quite a lot of ground in this section. It’s not too difficult, but I recommend that you work your way through it carefully, as it sets the foundation for everything else in read more..

  • Page - 77

    A common error is to use /* and */ to comment out a large sec‐ tion 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 read more..

  • Page - 78

    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. String read more..

  • Page - 79

    If you are keen to start trying out PHP for yourself, you could try entering 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 read more..

  • Page - 80

    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 - 81

    The reason the previous statement has the number 3, not 4, is because the first element of a PHP array is actually the zeroth element, so the player numbers will therefore 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 or can even read more..

  • Page - 82

    Once again, we’ve moved up a step in complexity, but it’s easy to understand if you have a grasp of 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 read more..

  • Page - 83

    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 do read more..

  • Page - 84

    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 read more..

  • Page - 85

    As the previous example shows, you generally use a logical operator to combine the results of two of the comparison operators shown in the previous section. A logical operator can also be input to another logical operator (“If the time is later than 12 p.m. and earlier than 2 p.m., or if the smell of a roast is permeating the hallway and there are plates on the read more..

  • Page - 86

    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 instance, the value 10 ) to the variable $x . Likewise, we could subtract as follows: $y −= 10; Variable incrementing and decrementing Adding or subtracting 1 is such a common read more..

  • Page - 87

    You have 5 messages. Just as you can add a value to a numeric variable with the += operator, you can append one string to another using .= like this: $bulletin .= $newsflash; In this case, if $bulletin contains a news bulletin and $newsflash has a news flash, the command appends the news flash to the news bulletin so that $bulletin now comprises both strings of read more..

  • Page - 88

    Additionally, you can use escape characters to insert various special characters into strings such as tabs, newlines, and carriage returns. These are represented, as you might guess, by \t , \n , and \r . Here is an example using tabs to lay out a heading; it is included here merely to illustrate escapes, because in web pages there are always better ways to do layout: read more..

  • Page - 89

    Example 3-8. Alternative multiline echo statement <?php $author = "Brian W. Kernighan"; echo <<<_END Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - $author. _END; ?> This code tells PHP to output read more..

  • Page - 90

    The variable $out will then be populated with the contents between the two tags. If you were appending, rather than assigning, you could also have used .= in place of = to append the string to $out . Be careful not to place a semicolon directly after the first occurrence of _END , because that would terminate the multiline block before it had even started and read more..

  • Page - 91

    zero). To do this, PHP turns $number into a nine-character string, so that substr can access it and return the character, which in this case is 1. The same goes for turning a string into a number, and so on. In Example 3-11, the variable $pi is set to a string value, which is then automatically turned into a floating- point number in the third line by the read more..

  • Page - 92

    Predefined Constants PHP comes ready-made with dozens of predefined constants that you generally will be unlikely to use as a beginner to PHP. However, there are a few—known as the magic constants—that you will find useful. The names of the magic constants always have two underscores at the beginning and two at the end, so that you won’t accidentally try to name one read more..

  • Page - 93

    has a return value (which is always 1 ), whereas echo is purely a PHP language construct. Because both commands are constructs, neither requires the use of parentheses. By and large, the echo command will be a tad faster than print in general text output, because it doesn’t set a return value. On the other hand, because it isn’t implemented like a function, echo read more..

  • Page - 94

    then calls the PHP date function with the correct format string to return a date in the format Tuesday May 2nd 2017. Any number of parameters can be passed between the initial parentheses; we have chosen to accept just one. The curly braces enclose all the code that is executed when you later call the function. To output today’s date using this function, place read more..

  • Page - 95

    Example 3-13. An expanded version of the longdate function <?php function longdate($timestamp) { $temp = date("l F jS Y", $timestamp); return "The date is $temp"; } ?> Here we have assigned the value returned by the date function to the temporary variable $temp , which is then inserted into the string returned by the function. As read more..

  • Page - 96

    Example 3-15 moves the reference to $temp out of the function. The reference appears in the same scope where the variable was defined. The solution in Example 3-16 passes $temp to the longdate function as an extra argu‐ ment. longdate reads it into a temporary variable that it creates called $text and outputs the desired result. Example 3-16. An alternative read more..

  • Page - 97

    in which you discover that a global variable has the wrong value at some point, how long will it take you to find the code that set it incorrectly? Also, if you have too many global variables, you run the risk of using one of those names again locally, or at least thinking you have used it locally, when in fact it has already been declared as global. All read more..

  • Page - 98

    Example 3-18. Allowed and disallowed static variable declarations <?php static $int = 0; // Allowed static $int = 1+2; // Disallowed (will produce a Parse error) static $int = sqrt(144); // Disallowed ?> Superglobal variables Starting with PHP 4.1.0, several predefined variables are available. These are known as superglobal variables, read more..

  • Page - 99

    Superglobals and security A word of caution is in order before you start using superglobal variables, because they are often used by hackers trying to find exploits to break into your website. What they do is load up $_POST , $_GET , or other superglobals with malicious code, such as Unix or MySQL commands that can damage or display sensitive data if you naïvely access them. read more..

  • Page - 100

    9. Can you use spaces in variable names? 10. How do you convert one variable type to another (say, a string to a number)? 11. What is the difference between ++$j and $j++ ? 12. Are the operators && and and interchangeable? 13. How can you create a multiline echo or assignment? 14. Can you redefine a constant? 15. How do you escape a quotation mark? 16. read more..

  • Page - 101

    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 - 102

    (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 read more..

  • Page - 103

    Example 4-2. Outputting the values of TRUE and FALSE <?php // test2.php echo "a: [" . TRUE . "]<br>"; echo "b: [" . FALSE . "]<br>"; ?> which outputs the following: a: [1] b: [] By the way, in some languages FALSE may be defined as 0 or even −1 , so it’s worth checking on its definition in each language. read more..

  • Page - 104

    expression 366 - $day_number to the variable $days_to_new_year , and the second outputs a friendly message only if the expression $days_to_new_year < 30 evaluates to TRUE . Example 4-4. An expression and a statement <?php $days_to_new_year = 366 - $day_number; // Expression if ($days_to_new_year < 30) { echo "Not long now till new year"; // read more..

  • Page - 105

    Operator Precedence If all operators had the same precedence, they would be processed in the order in which they are encountered. In fact, many operators do have the same precedence, so let’s look at a few in Example 4-5. Example 4-5. Three equivalent expressions 1 + 2 + 3 − 4 + 5 2 − 4 + 5 + 3 + 1 5 + 2 − 4 + 1 + 3 Here you will see that read more..

  • Page - 106

    The final results of these expressions are −13 , −57 , and 6 , respectively (quite different from the results of 25 , −29 , and 12 that we would have seen had there been no operator precedence). Of course, you can override the default operator precedence by inserting your own parentheses and forcing the original results that we would have seen had there been no read more..

  • Page - 107

    this direction of processing is called the operator’s associativity. For some operators there is no associativity. Associativity becomes important in cases in which you do not explicitly force prece‐ dence, so you need to be aware of the default actions of operators, as detailed in Table 4-3, which lists operators and their associativity. Table 4-3. Operator associativity Operator read more..

  • Page - 108

    This multiple assignment is possible only if the rightmost part of the expression is eval‐ uated first and then processing continues in a right-to-left direction. As a beginner to PHP, you should avoid the potential pitfalls of op‐ erator associativity by always nesting your subexpressions within parentheses to force the order of evaluation. read more..

  • Page - 109

    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 both strings were first converted to numbers, and 1000 is the same numerical value as +1000 . In contrast, the second if statement uses the identity operator—three equals signs in a row—which prevents PHP from read more..

  • Page - 110

    In this example, where $a is 2 and $b is 3 , the following is output: 2 is less than 3 2 is less than or equal to 3 Try this example yourself, altering the values of $a and $b , to see the results. Try setting them to the same value and see what happens. Logical operators Logical operators produce true-or-false results, and therefore are also known as Boolean read more..

  • Page - 111

    The OR operator can cause unintentional problems in if statements, because the second operand will not be evaluated if the first is evaluated as TRUE . In Example 4-17, the function getnext will never be called if $finished has a value of 1 . Example 4-17. A statement using the OR operator <?php if ($finished == 1 OR getnext() == 1) exit; ?> If you need read more..

  • Page - 112

    Conditionals Conditionals alter program flow. They enable you to ask questions about certain things and respond to the answers you get in different ways. Conditionals are central to dy‐ namic web pages—the goal of using PHP in the first place—because they make it easy to create different output each time a page is viewed. There are three types of non-looping conditionals: read more..

  • Page - 113

    The actions to take when an if condition is TRUE are generally placed inside curly braces, { } . However, you can ignore the braces if you have only a single statement to execute. But if you always use curly braces, you’ll avoid having to hunt down difficult-to-trace bugs, such as when you add an extra line to a condition and it doesn’t get evaluated due to read more..

  • Page - 114

    Figure 4-2. The highway now has an if detour and an else detour With an if ... else statement, the first conditional statement is executed if the con‐ dition is TRUE . But if it’s FALSE , the second one is executed. One of the two choices must be executed. Under no circumstance can both (or neither) be executed. Example 4-20 shows the use of the if ... else read more..

  • Page - 115

    In this example, now that you’ve ascertained that you have $100 or more in the bank, the else statement is executed, by which you place some of this money into your savings account. 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 read more..

  • Page - 116

    Figure 4-3. The highway with if, elseif, and else detours An else statement closes either an if ... else or an if ... else if ... 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. read more..

  • Page - 117

    News, Login, and Links, and we set the variable $page to one of these, according 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 == read more..

  • Page - 118

    Breaking out If you wish to break out of the switch statement because a condition has been fulfilled, use the break command. This command tells PHP to break out of the switch and jump to the following statement. If you were to leave out the break commands in Example 4-23 and the case of Home evaluated to be TRUE , all five cases would then be executed. Or read more..

  • Page - 119

    case "Links": echo "You selected Links"; break; endswitch; ?> The ? Operator One way of avoiding the verbosity of if and else statements is to use the more compact ternary operator, ? , which is unusual in that it takes three operands rather than the typical two. We briefly came across this in Chapter 3 read more..

  • Page - 120

    $saved = // Set the value of $saved to... $saved >= $new // Check $saved against $new ? // Yes, comparison is true ... $saved // ... so assign the current value of $saved : // read more..

  • Page - 121

    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 "There's enough fuel"; } ?> Actually, you might prefer to keep a read more..

  • Page - 122

    Inside the loop, a string is printed along with the value of $count multiplied by 12. For neatness, this is also followed with a <br> tag to force a new line. Then $count is in‐ cremented, ready for the final curly brace that tells PHP to return to the start of the loop. At this point, $count is again tested to see whether it is greater than 12. read more..

  • Page - 123

    Notice how we are back to initializing $count to 1 (rather than 0 ) because the code is being executed immediately, without an opportunity to increment the variable. Other than that, though, the code looks pretty similar. Of course, if you have more than a single statement inside a do ... while loop, re‐ member to use curly braces, as in Example 4-32. Example 4-32. read more..

  • Page - 124

    expression is executed. In the case of the times table code, the variable $count is incre‐ mented. All this structure neatly removes any requirement to place the controls for a loop within its body, freeing it up just for the statements you want the loop to perform. Remember to use curly braces with a for loop if it will contain more than one statement, as in read more..

  • Page - 125

    Breaking Out of a Loop Just as you saw how to break out of a switch statement, you can also break out of a for loop using the same break command. This step can be necessary when, for example, one of your statements returns an error and the loop cannot continue executing safely. One case in which this might occur is when writing a file returns an error, possibly read more..

  • Page - 126

    The break command is even more powerful than you might think because if you have code nested more than one layer deep that you need to break out of, you can follow the break command with a number to indicate how many levels to break out of, like this: break 2; The continue Statement The continue statement is a little like a break statement, except that it read more..

  • Page - 127

    Example 4-37. This expression returns a floating-point number <?php $a = 56; $b = 12; $c = $a / $b; echo $c; ?> But what if we had wanted $c to be an integer instead? There are various ways in which we could achieve this, one of which is to force the result of $a /$b to be cast to an integer value using the integer cast type (int) , read more..

  • Page - 128

    Although it is possible to build an entire website this way, it’s not recommended, because your source code will grow and grow and start to become unwieldy, as it has to account for every possible action a user could take. Instead, it’s much more sensible to split your website development into different parts. For example, one distinct process is signing up for a read more..

  • Page - 129

    Figure 4-5. The WordPress blogging platform is written in PHP 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 knowl‐ edge on the following questions. Questions 1. What read more..

  • Page - 130

    8. What command can you use to skip the current iteration of a loop and move on to the next one? 9. Why is a for loop more powerful than a while loop? 10. How do if and while statements interpret conditional expressions of different data types? See “Chapter 4 Answers” on page 641 in Appendix A for the answers to these questions. 102 | Chapter 4: read more..

  • Page - 131

    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 evalu‐ ation, 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 read more..

  • Page - 132

    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 function 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 a read more..

  • Page - 133

    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 example read more..

  • Page - 134

    Defining a Function The general syntax for a function is: 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 that: • A definition starts with the word function . • A name follows, which must start with a letter or underscore, followed by any read more..

  • Page - 135

    The output is: 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 the order in which code read more..

  • Page - 136

    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 forget capitals altogether. The output from this example is: William Henry Gates Returning an Array We just saw a function returning a single value. There are also ways of getting multiple values from a read more..

  • Page - 137

    Figure 5-2. Imagining a reference as a thread attached to a variable Now the function can follow the thread to find the data to be accessed. This avoids all the overhead of creating a copy of the variable just for the function’s use. What’s more, the function can now modify the variable’s value. This means you can rewrite Example 5-3 to pass references to all read more..

  • Page - 138

    Now the variables $n1 , $n2 , and $n3 are attached to “threads” that lead to the values of $a1 , $a2 , and $a3 . In other words, there is one group of values, but two sets of variable names are allowed to access them. Therefore, the function fix_names only has to assign new values to $n1 , $n2 , and $n3 to update the values of $a1 , $a2 , and $a3 . The output read more..

  • Page - 139

    In order to retain as much local scope as possible, you should try returning arrays or using variables by association. Otherwise, you will begin to lose some of the benefits of functions. Recap of Variable Scope A quick reminder of what you know from Chapter 3: • Local variables are accessible just from the part of code where read more..

  • Page - 140

    Using include_once Each time you issue the include directive, it includes the requested file again, even if you’ve already inserted it. For instance, suppose that library.php contains a lot of useful functions, so you include it in your file, but also include another library that includes library.php. Through nesting, you’ve inadvertently included library.php twice. This will read more..

  • Page - 141

    PHP Version Compatibility PHP is in an ongoing process of development, and there are multiple versions. If you need to check whether a particular function is available to your code, you can use the function_exists function, which checks all predefined and user-created functions. Example 5-9 checks for the function array_combine , which is specific to PHP version 5. Example 5-9. read more..

  • Page - 142

    required for handling users and all the variables needed for manipulating the data within the class. Then, whenever you need to manipulate a user’s data, you could simply create a new object with the User class. You could treat this new object as if it were the actual user. For example, you could pass the object a name, password, and email address; ask it whether read more..

  • Page - 143

    Figure 5-3. A jukebox: a great example of a self-contained object In our jukebox example, if you invent a new jukebox that can play a video along with the music, you can inherit all the properties and methods from the original jukebox superclass and add some new properties (videos) and new methods (a movie player). An excellent benefit of this system is that if you read more..

  • Page - 144

    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 about a variable in human-readable form. The _r stands for “in human- readable format.” In the case of read more..

  • Page - 145

    Example 5-11. Creating and interacting with an object <?php $object = new User; print_r($object); echo "<br>"; $object->name = "Joe"; $object->password = "mypass"; print_r($object); echo "<br>"; $object->save_user(); class User { public $name, $password; function save_user() { read more..

  • Page - 146

    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 method save_user was executed via the call to that method. It printed the string reminding us to create some code. You can place functions and class definitions anywhere in your code, before or after read more..

  • Page - 147

    To avoid this confusion, you can use the clone operator, which creates a new instance of the class and copies the property values from the original instance to the new instance. Example 5-13 illustrates this usage. Example 5-13. Cloning an object <?php $object1 = new User(); $object1->name = "Alice"; $object2 = clone $object1; read more..

  • Page - 148

    Example 5-15. Creating a constructor method in PHP 5 <?php class User { function __construct($param1, $param2) { // Constructor statements go here public $username = "Guest"; } } ?> PHP 5 Destructors Also new in PHP 5 is the ability to create destructor methods. This ability is useful when code has read more..

  • Page - 149

    } } ?> get_password uses the $this variable to access the current object and then return the value of that object’s password property. Note how the preceding $ of the property $password is omitted when we use the -> operator. Leaving the $ in place is a typical error you may run into, particularly when you first use this feature. Here’s read more..

  • Page - 150

    Declaring Properties It is not necessary to explicitly declare properties within classes, as they can be implicitly defined when first used. To illustrate this, in Example 5-19 the class User has no prop‐ erties and no methods but is legal code. Example 5-19. Defining a property implicitly <?php $object1 = new User(); $object1->name = "Alice"; read more..

  • Page - 151

    Example 5-21. Defining constants within a class <?php Translate::lookup(); class Translate { const ENGLISH = 0; const SPANISH = 1; const FRENCH = 2; const GERMAN = 3; // ... static function lookup() { echo self::SPANISH; } } ?> You can reference constants directly, using the read more..

  • Page - 152

    Here’s how to decide which you need to use: • Use public when outside code should access this member and extending classes should also inherit it. • Use protected when outside code should not access this member but extending classes should inherit it. • Use private when outside code should not access this member and extending classes also should not read more..

  • Page - 153

    Example 5-23. Defining a class with a static property <?php $temp = new Test(); echo "Test A: " . Test::$static_property . "<br>"; echo "Test B: " . $temp->get_sp() . "<br>"; echo "Test C: " . $temp->static_property . "<br>"; class Test { static $static_property = "I'm static"; read more..

  • Page - 154

    Example 5-24. Inheriting and extending a class <?php $object = new Subscriber; $object->name = "Fred"; $object->password = "pword"; $object->phone = "012 345 6789"; $object->email = "fred@bloggs.com"; $object->display(); class User { public $name, $password; read more..

  • Page - 155

    Example 5-25. Overriding a method and using the parent operator <?php $object = new Son; $object->test(); $object->test2(); class Dad { function test() { echo "[Class Dad] I am your Father<br>"; } } class Son extends Dad { function test() { echo "[Class Son] read more..

  • Page - 156

    Example 5-26. Calling the parent class constructor <?php $object = new Tiger(); echo "Tigers have...<br>"; echo "Fur: " . $object->fur . "<br>"; echo "Stripes: " . $object->stripes; class Wildcat { public $fur; // Wildcats have fur function __construct() { $this->fur = "TRUE"; read more..

  • Page - 157

    Example 5-27. Creating a final method <?php class User { final function copyright() { echo "This class was written by Joe Smith"; } } ?> Once you have digested the contents of this chapter, you should have a strong feel for what PHP can do for you. You should be able to use functions with ease and, if you wish, read more..

  • Page - 158

    read more..

  • Page - 159

    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 - 160

    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 - 161

    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 seen read more..

  • Page - 162

    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 into an associative array whose names reflect the page’s structure: $html['title'] = "My web page"; $html['body'] = "... body of web page ..."; read more..

  • Page - 163

    You can verify that $p1 and $p2 are different types of array, because both of the following commands, when appended to the code, will cause an Undefined index or Undefined offset error, as the array identifier for each is incorrect: echo $p1['inkjet']; // Undefined index echo $p2[3]; // Undefined offset The foreach ... as Loop The creators of PHP have read more..

  • Page - 164

    foreach($paper as $item => $description) echo "$item: $description<br>"; ?> Remember that associative arrays do not require numeric indexes, so the variable $j is not used in this example. Instead, each item of the array $paper is fed into the key/value pair of variables $item and $description , from which they are printed out. The dis‐ played read more..

  • Page - 165

    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 looping system. Multidimensional Arrays A simple design feature in PHP’s array syntax makes it possible to create arrays of more than one dimension. In fact, they can be as read more..

  • Page - 166

    echo "</pre>"; ?> To make things clearer now that the code is starting to grow, I’ve renamed some of the elements. For example, because the previous array $paper is now just a subsection of a larger array, the main array is now called $products . Within this array, there are three items—paper, pens , and misc —each of which contains another read more..

  • Page - 167

    Example 6-11. Creating a multidimensional numeric array <?php $chessboard = array( array('r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'), array('p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'), array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), array(' ', ' ', ' ', ' ', ' ', read more..

  • Page - 168

    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 PHP comes with numerous other functions for handling arrays. The full list is at http://tinyurl.com/arraysinphp. However, some of these functions are so read more..

  • Page - 169

    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 might wish to use force sorting to be made either numerically or as strings, like this: sort($fred, SORT_NUMERIC); sort($fred, read more..

  • Page - 170

    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 code in Example 6-13 prints out the following: Array ( [0] => A [1] => read more..

  • Page - 171

    whose keys could be controlled by the user, because malicious users could submit keys chosen deliberately to overwrite commonly used variable names and compromise your website. compact There are also times when you want to use compact , the inverse of extract , to create an array from variables and their values. Example 6-14 shows how you might use this function. Example 6-14. read more..

  • Page - 172

    This works by using the explode function to extract all the words from the string into an array, which is then passed to the compact function, which in turn returns an array to print_r , which finally shows its contents. If you copy and paste the print_r line of code, you only need to alter the variables named there for a quick printout of a group of read more..

  • Page - 173

    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 PHP’s internal pointer into an array back to the first element of the array? See “Chapter 6 Answers” on page 643 in Appendix A for the answers to these questions. Questions | 145 read more..

  • Page - 174

    read more..

  • Page - 175

    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 - 176

    Specifier Conversion action on argument arg Example (for an arg of 123) 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 in uppercase hexadecimal. 7B You can have as read more..

  • Page - 177

    The output from this command is: The result is $10.29 But you actually have even more control than that, because you can also specify whether to pad output with either zeros or spaces by prefacing the specifier with certain values. Example 7-1 shows four possible combinations. Example 7-1. Precision setting <?php echo "<pre>"; // Enables viewing of the spaces read more..

  • Page - 178

    of spaces. If a pad character other than zero or a space is required, you can use any one of your choice as long as you preface it with a single quotation mark, like this: '# . • On the left is the % symbol, which starts the conversion. Table 7-2. Conversion specifier components Start conversion Pad character Number of pad characters Display precision Conversion read more..

  • Page - 179

    [ Rasmus L] [Rasmus Lerdo] [Rasmus Ler@@] When you are specifying a padding value, if a string is already of equal or greater length than that value it will be ignored, unless a cutoff value is given that shortens the string back to less than the padding value. Table 7-3 shows a breakdown of the components available to string conversion specifiers. Table 7-3. String read more..

  • Page - 180

    If you wish to create a timestamp for a given date, you can use the mktime function. Its output is the timestamp 946684800 for the first second of the first minute of the first hour of the first day of the year 2000: echo mktime(0, 0, 0, 1, 1, 2000); The parameters to pass are, in order from left to right: • The number of the hour (0–23) • The number read more..

  • Page - 181

    Table 7-4. The major date function format specifiers Format Description Returned value Day specifiers d Day of month, two digits, with leading zeros 01 to 31 D Day of the week, three letters Mon to Sun j Day of the month, no leading zeros 1 to 31 l Day of week, full names Sunday to Saturday N Day of week, numeric, Monday read more..

  • Page - 182

    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 more commonly used constants are: DATE_ATOM This is the format for Atom feeds. The PHP format is "Y-m-d\TH:i:sP" and read more..

  • Page - 183

    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 might need to do this are modifying images such as uploaded user avatars, or log files that you wish to process. First, though, a note read more..

  • Page - 184

    folder in which you saved the testfile.php program. Try opening the file in a text or program editor—the contents will look like this: Line 1 Line 2 Line 3 This simple example shows the sequence that all file handling takes: 1. Always start by opening the file. You do this through a call to fopen . 2. Then you can call other functions; here we write to the file read more..

  • Page - 185

    Mode Action Description 'w' Write from file start and truncate file. Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file doesn’t exist, attempt to create it. 'w+' Write from file start, truncate file, and allow reading. Open for reading and read more..

  • Page - 186

    Copying Files Let’s try out the PHP copy function to create a clone of testfile.txt. Type in Example 7-7 and save it as copyfile.php, and then call up the program in your browser. Example 7-7. Copying a file <?php // copyfile.php copy('testfile.txt', 'testfile2.txt') or die("Could not copy file"); echo "File successfully copied to 'testfile2.txt'"; ?> If you read more..

  • Page - 187

    Whenever you access files on your hard disk directly, you must also always ensure that it is impossible for your filesystem to be compro‐ mised. For example, if you are deleting a file based on user input, you must make absolutely certain it is a file that can be safely de‐ leted and that read more..

  • Page - 188

    The first line has successfully been copied and then appended to the file’s end. As used here, in addition to the $fh file handle, the fseek function was passed two other parameters, 0 and SEEK_END . SEEK_END tells the function to move the file pointer to the end of the file and 0 tells it how many positions it should then be moved backward from that read more..

  • Page - 189

    } fclose($fh); echo "File 'testfile.txt' successfully updated"; ?> There is a trick to file locking to preserve the best possible response time for your website visitors: perform it directly before a change you make to a file, and then unlock it im‐ mediately afterward. Having a file locked for any longer than this will slow down your application unnecessarily. read more..

  • Page - 190

    Reading an Entire File A handy function for reading in an entire file without having to use file handles is file_get_contents . It’s very easy to use, as you can see in Example 7-13. Example 7-13. Using file_get_contents <?php echo "<pre>"; // Enables display of line feeds echo file_get_contents("testfile.txt"); echo "</pre>"; // read more..

  • Page - 191

    a special type of encoding called multipart/form-data, and your browser will handle the rest. To see how this works, type the program in Example 7-15 and save it as upload.php. When you run it, you’ll see a form in your browser that lets you upload a file of your choice. Example 7-15. Image uploader upload.php <?php // upload.php echo <<<_END read more..

  • Page - 192

    whether $_FILES contains anything is sufficient to determine whether the user has up‐ loaded a file. This is done with the statement if ($_FILES) . The first time the user visits the page, before uploading a file, $_FILES is empty, so the program skips this block of code. When the user uploads a file, the program runs again and discovers an element in the $_FILES read more..

  • Page - 193

    Table 7-6. The contents of the $_FILES array Array element Contents $_FILES[' file']['name'] The name of the uploaded file (e.g., smiley.jpg) $_FILES[' file']['type'] The content type of the file (e.g., image/jpeg) $_FILES[' file']['size'] The file’s size in bytes $_FILES[' file']['tmp_name'] The name of the temporary file stored on the server $_FILES[' read more..

  • Page - 194

    switch($_FILES['filename']['type']) { case 'image/jpeg': $ext = 'jpg'; break; case 'image/gif': $ext = 'gif'; break; case 'image/png': $ext = 'png'; break; case 'image/tiff': $ext = 'tif'; break; default: $ext = ''; break; } if ($ext) { read more..

  • Page - 195

    Don’t worry about having to delete the temporary file that PHP cre‐ ates during the upload process, because if the file has not been moved or renamed, it will be automatically removed when the program exits. After the if statement there is a matching else , which is executed only if an unsupported image type was read more..

  • Page - 196

    first line and uncomment the second to use the ls system command. You may wish to type this program, save it as exec.php, and call it up in your browser. Example 7-17. Executing a system command <?php // exec.php $cmd = "dir"; // Windows // $cmd = "ls"; // Linux, Unix & Mac exec(escapeshellcmd($cmd), $output, $status); if ($status) read more..

  • Page - 197

    You should also note the use of the escapeshellcmd function. It is a good habit to always use this when issuing an exec call, because it sanitizes the command string, preventing the execution of arbitrary commands, should you supply user input to the call. The system calling functions are typically disabled on shared web hosts, as they pose a read more..

  • Page - 198

    3. To send the output from printf to a variable instead of to a browser, what alternative function would you use? 4. How would you create a Unix timestamp for 7:11 a.m. on May 2, 2016? 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 read more..

  • Page - 199

    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 - 200

    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 Non-Fiction 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 - 201

    Starting the Command-Line Interface The following sections describe relevant instructions for Windows, OS X, and Linux. Windows users If you installed the Zend Server Free Edition WAMP (as explained in Chapter 2), you will be able to access the MySQL executable from one of the following directories (the first on 32-bit computers, and the second on 64-bit machines): C:\Program read more..

  • Page - 202

    Figure 8-1. Accessing MySQL from a Windows Command Prompt If this has not worked and you get an error, make sure that you have correctly installed MySQL along with Zend Server (as described in Chapter 2). Otherwise, you are ready to move on to the next section, “Using the Command-Line Interface” on page 177. OS X users To proceed with this chapter, you should have read more..

  • Page - 203

    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 haven’t started up the MySQL server, so make sure you followed the advice in Chapter 2 about configuring MySQL to start when OS X starts. You should now be ready to move on to the next section, “Using the read more..

  • Page - 204

    Figure 8-3. Accessing MySQL using Linux If this procedure fails at any point, refer to the section “Installing a LAMP on Linux” on page 38 in 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 177. MySQL on a remote server If you are accessing read more..

  • Page - 205

    Therefore, if you have any problems, talk with your system administrator, who will get you sorted out. Just let the sysadmin know that you need a username and password. You should also ask for the ability to create new databases or, at a minimum, to have at least one database created for you ready to use. You can then create all the tables you require within that read more..

  • Page - 206

    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 enter that line, MySQL read more..

  • Page - 207

    Command Action 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 commands and keywords are case-insensitive. CREATE , create , and CrEaTe all mean the same read more..

  • Page - 208

    All 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 contains, such as tables (see Table 8-4). Table 8-4. Example parameters for the GRANT command Arguments Meaning *.* All databases and all their objects database.* Only the database called database and all its read more..

  • Page - 209

    You can grant only privileges that you already have, and you must also have the privilege to issue GRANT commands. There is a whole range of privileges you can choose to grant if you are not granting all priv‐ ileges. For further details, visit http://tinyurl.com/mysqlgrant, which also covers the REVOKE read more..

  • Page - 210

    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 - 211

    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, as read more..

  • Page - 212

    Table 8-6. MySQL’s CHAR data types Data type Bytes used Examples CHAR( n) exactly n (< 256) CHAR(5) “Hello” uses 5 bytes CHAR(57) “Goodbye” uses 57 bytes VARCHAR( n) up to n (< 65,536) 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 - 213

    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 Bytes used Attributes TINYBLOB( n) up to n (< 256) Treated as binary data—no character set BLOB( n) up to n (<= 65,536) Treated as binary data—no character set MEDIUMBLOB( n) up read more..

  • Page - 214

    When creating a numeric field, you can also pass an optional number as a parameter, like this: CREATE TABLE tablename (fieldname INT(4)); But you must remember that, unlike BINARY and CHAR data types, this parameter does not indicate the number of bytes of storage to use. It may seem counterintuitive, but what the number actually represents is the display width of the read more..

  • Page - 215

    frequently duplicated, and so on. It would be hard to guarantee that you have no du‐ plicate rows. The general solution is to use an extra column just for this purpose. In a while, we’ll look at using a publication’s ISBN (International Standard Book Number), but first I’d like to introduce the AUTO_INCREMENT data type. As its name implies, a column given this read more..

  • Page - 216

    Example 8-6. Adding the auto-incrementing id column at table creation CREATE TABLE classics ( author VARCHAR(128), title VARCHAR(128), type VARCHAR(16), year CHAR(4), id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY) ENGINE MyISAM; If you wish to check whether the column has been added, use the following command to view the table’s columns and data types: DESCRIBE classics; Now read more..

  • Page - 217

    Figure 8-4. Populating the classics table and viewing its contents Let’s go back and look at how we used the INSERT command. The first part, INSERT INTO classics , tells MySQL where to insert the following data. Then, within parentheses, the four column names are listed— author, title, type, and year—all separated by com‐ mas. This tells MySQL that these are the read more..

  • Page - 218

    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 of column year from CHAR(4) to SMALLINT (which requires only two bytes of storage and so will save disk space), enter the following: ALTER TABLE classics MODIFY year SMALLINT; When you read more..

  • Page - 219

    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); Note the addition of VARCHAR(16) on the end of this command. That’s read more..

  • Page - 220

    Figure 8-6. Creating, viewing, and deleting a table Indexes As things stand, the table classics works and can be searched without problem by MySQL—until it grows to more than a couple of hundred rows, that is. At that point, database accesses will get slower and slower with every new row added, because MySQL has to search through every row whenever a query is issued. read more..

  • Page - 221

    If we imagine the searches that may be made on the classics table, it becomes apparent that all of the columns may need to be searched. However, if the pages column created in the section “Adding a new column” on page 190 had not been deleted, it would prob‐ ably not have needed an index, as most people would be unlikely to search for books by the number read more..

  • Page - 222

    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 to create a PRIMARY KEY (see the section “Primary keys” on page 195). The format of this command is shown in the second line of Example read more..

  • Page - 223

    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 something missing. All the publications in the table can be searched, but there is no single unique key for each publication to enable instant accessing of read more..

  • Page - 224

    Once you have typed these commands, the results should look like Figure 8-8. Note that the keywords PRIMARY KEY replace the keyword INDEX in the ALTER TABLE syntax (compare Examples 8-10 and 8-13). Figure 8-8. Retrospectively adding a primary key to the classics table To have created a primary key when the table classics was created, you could have used the commands read more..

  • Page - 225

    Actually, it’s not strictly true that MySQL stores all the words in a FULLTEXT index, because it has a built-in list of more than 500 words that it chooses to ignore because they are so common that they aren’t very helpful for searching anyway. This list, called stopwords, in‐ cludes the, as, is, read more..

  • Page - 226

    Querying a MySQL Database So far, we’ve created a MySQL database and tables, populated them with data, and added indexes to make them fast to search. Now it’s time to look at how these searches are performed, and the various commands and qualifiers available. SELECT As you saw in Figure 8-4, the SELECT command is used to extract data from a table. In that section, read more..

  • Page - 227

    parameter, which means “all rows.” As you’d expect, the result returned is 5 , as there are five publications in the table. Example 8-17. Counting rows SELECT COUNT(*) FROM classics; SELECT DISTINCT This qualifier (and its synonym DISTINCTROW ) allows you to weed out multiple entries when they contain the same data. For instance, suppose that you want a list of all authors read more..

  • Page - 228

    DELETE When you need to remove a row from a table, use the DELETE command. Its syntax is similar to the SELECT command and allows you to narrow down the exact row or rows to delete using qualifiers such as WHERE and LIMIT . Now that you’ve seen the effects of the DISTINCT qualifier, if you entered Example 8-18, you should remove Little Dorrit by entering the read more..

  • Page - 229

    Example 8-22. Using the LIKE qualifier SELECT author,title FROM classics WHERE author LIKE "Charles%"; SELECT author,title FROM classics WHERE title LIKE "%Species"; SELECT author,title FROM classics WHERE title LIKE "%and%"; Figure 8-11. Using WHERE with the LIKE qualifier The first command outputs the publications by both Charles Darwin and Charles Dickens because read more..

  • Page - 230

    last command returns a single row starting at position 3 (skipping the first three rows). Figure 8-12 shows the results of issuing these three commands. Example 8-23. Limiting the number of results returned SELECT author,title FROM classics LIMIT 3; SELECT author,title FROM classics LIMIT 1,2; SELECT author,title FROM classics LIMIT 3,1; Figure 8-12. Restricting the rows returned with read more..

  • Page - 231

    columns. The second query asks for any rows that contain both of the words old and shop anywhere in them, in any order, to be returned. And the last query applies the same kind of search for the words tom and sawyer. Figure 8-13 shows the results of these queries. Example 8-24. Using MATCH ... AGAINST on FULLTEXT indexes SELECT author,title FROM classics WHERE read more..

  • Page - 232

    double quotes to request that all rows containing the exact phrase origin of be returned. Figure 8-14 shows the results of these queries. Example 8-25. Using MATCH ... AGAINST ... IN BOOLEAN MODE SELECT author,title FROM classics WHERE MATCH(author,title) AGAINST('+charles -species' IN BOOLEAN MODE); SELECT author,title FROM classics WHERE MATCH(author,title) AGAINST('"origin read more..

  • Page - 233

    Example 8-26. Using UPDATE ... SET UPDATE classics SET author='Mark Twain (Samuel Langhorne Clemens)' WHERE author='Mark Twain'; UPDATE classics SET category='Classic Fiction' WHERE category='Fiction'; 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 read more..

  • Page - 234

    Figure 8-16. Sorting the results of requests As you can see, the first query returns the publications by author in ascending alpha‐ betical order (the default), and the second returns them by title in descending order. If you wanted to sort all the rows by author and then by descending year of publication (to view the most recent first), you would issue the read more..

  • Page - 235

    +-----------------+---------------+ | category | COUNT(author) | +-----------------+---------------+ | Classic Fiction | 3 | | Non-Fiction | 1 | | Play | 1 | +-----------------+---------------+ 3 rows in set (0.00 sec) Joining Tables Together It is quite read more..

  • Page - 236

    There’s also a shortcut for inserting multiple rows of data, as in Ex‐ ample 8-28, in which you can replace the three separate INSERT INTO queries with a single one listing the data to be inserted, separated by commas, like this: INSERT INTO customers(name,isbn) VALUES ('Joe Bloggs','9780099533474'), ('Mary read more..

  • Page - 237

    Using AS You can also save yourself some typing and improve query readability by creating aliases using the AS keyword. Follow a table name with AS and the alias to use. The following code, therefore, is also identical in action to Example 8-29. Aliases can be particularly useful when you have long queries that reference the same table names many times. SELECT read more..

  • Page - 238

    you would first have to extract raw data from MySQL, manipulate it, and then perform the database query you first wanted. Having functions built into MySQL substantially reduces the time needed for perform‐ ing 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: • read more..

  • Page - 239

    Now click on the left and right arrows to the right of the DEPLOY SAMPLE APPS section until you see the phpMyAdmin logo and click it to initiate the download; then click Next when you’re finished. Click Next again, after you have viewed the README information, to call up the Application Details screen (see Figure 8-19). Figure 8-19. Configuring phpMyAdmin for Zend Here you read more..

  • Page - 240

    Figure 8-20. Entering phpMyAdmin user parameters Now click Next, review the summary displayed, and when ready, click the Deploy but‐ ton. After a few seconds, you should see that the application was successfully deployed, at which point you’ll be ready to access phpMyAdmin by entering the following into your browser: http://localhost/phpmyadmin This will bring up the dialog shown read more..

  • Page - 241

    Figure 8-21. Logging into phpMyAdmin Your browser should now look like Figure 8-22, and you’re ready to use phpMyAdmin in place of the MySQL command line. Figure 8-22. The phpMyAdmin main screen Accessing MySQL via phpMyAdmin | 213 read more..

  • Page - 242

    Full details on this installation process are on the Zend website at the following (shortened) URL: http://tinyurl.com/installpma. Using phpMyAdmin In the lefthand pane of the main phpMyAdmin screen, you can click on the drop-down menu that says “(Databases)” to select an y database you wish to work with. This will open the database and display its tables. read more..

  • Page - 243

    9. Using the SELECT ... WHERE construct, how would you return only rows contain‐ ing the word Langhorne somewhere in the author column of the classics table used in this chapter? 10. What needs to be defined in two tables to make it possible for you to join them together? See “Chapter 8 Answers” on page 644 in Appendix A for the answers to these read more..

  • Page - 244

    read more..

  • Page - 245

    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 databases for maximum read more..

  • Page - 246

    • Which books did a certain customer buy? • Which books have been purchased together? 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 be combined into one table, because they are closely linked (we’ll read more..

  • Page - 247

    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 primary key. Don’t choose a key that could possibly have the same value for different read more..

  • Page - 248

    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 - 249

    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, Los Angeles, CA 90014 Mar 03 2009 Dynamic HTML 0596527403 59.99 Darren Ryder 4758 Emily Drive, Richmond, VA 23219 Dec 19 2008 PHP and MySQL 0596005436 44.95 read more..

  • Page - 250

    Keys (also called indexes) have several purposes in MySQL. The fun‐ damental reason for defining a key is to make searches faster. You’ve seen examples in Chapter 8 in which keys are used in WHERE clauses for searching. But a key can also be useful to uniquely identify an item. Thus, a unique read more..

  • Page - 251

    Table 9-5. The Customer details from Table 9-2 ISBN Customer Name Customer Address Purchase Date 0596101015 Emma Brown 1565 Rainbow Road, Los Angeles, CA 90014 Mar 03 2009 0596527403 Darren Ryder 4758 Emily Drive, Richmond, VA 23219 Dec 19 2008 0596005436 Earl B. Thurston 862 Gregory Lane, Frankfort, KY 40601 Jun 22 2009 0596101015 Darren read more..

  • Page - 252

    The CustNo column can be a useful key in the Purchases table, but it’s not a primary key. A single customer can buy multiple books (and even multiple copies of one book), so the CustNo column is not a primary key. In fact, the Purchases table has no primary key. That’s all right, because we don’t expect to need to keep track of unique purchases. If read more..

  • Page - 253

    Therefore, to satisfy Third Normal Form for Table 9-6, you would need to split it into Tables 9-8 through 9-11. Table 9-8. Third Normal Form Customers table CustNo Name Address Zip 1 Emma Brown 1565 Rainbow Road 90014 2 Darren Ryder 4758 Emily Drive 23219 3 Earl B. Thurston 862 Gregory Lane 40601 4 David Miller 3647 Cedar Lane 02154 Table 9-9. Third Normal Form read more..

  • Page - 254

    Table 9-10 could also contain even more localized demographics that could be useful to you and/or your customers. By splitting up these pieces of data, you can make it easier to maintain your database in the future, should it be necessary to add columns. Deciding whether to use the Third Normal Form can be tricky. read more..

  • Page - 255

    You see, if you have data duplicated across your tables, you can substantially reduce the number of additional requests that need to be made, because most of the data you want is available in each table. This means that you can simply add an extra column to a query and that field will be available for all matching results. Of course, you have to deal with the read more..

  • Page - 256

    Figure 9-1. The Customers table, Table 9-8, split into two tables Usually, when two items have a one-to-one relationship, you just include them as col‐ umns in the same table. There are two reasons for splitting them into separate tables: • You want to be prepared in case the relationship changes later. • The table has a lot of columns and you think that performance read more..

  • Page - 257

    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 relationship, add a third table containing the same key column from each of the other tables. This third table contains nothing else, as its sole purpose is to link up the other tables. Table read more..

  • Page - 258

    If it seems to you that this is really combining multiple one-to-many relationships, then you are absolutely correct. To illustrate, Figure 9-3 brings three tables together. Figure 9-3. Creating a many-to-many relationship via a third table Follow any zip code in the lefthand table to associated customer IDs. From there, you can link to the middle table, which joins the left read more..

  • Page - 259

    • You add the funds to the second account, but when you try to subtract them from the first account the update fails, and now both accounts have the funds. • You subtract the funds from the first bank account, but the update request to add them to the second account fails, and the funds have now disappeared into thin air. As you can see, not only is the order read more..

  • Page - 260

    Example 9-2. Populating the accounts table INSERT INTO accounts(number, balance) VALUES(12345, 1025.50); INSERT INTO accounts(number, balance) VALUES(67890, 140.00); SELECT * FROM accounts; The third line displays the contents of the table to confirm that the rows were correctly inserted. The output should look like this: +--------+---------+ | number | balance | +--------+---------+ | 12345 | read more..

  • Page - 261

    This feature gives you the opportunity to cancel a transaction by not sending a COMMIT but by issuing a ROLLBACK command instead. Using ROLLBACK Using the ROLLBACK command, you can tell MySQL to forget all the queries made since the start of a transaction and to end the transaction. See this in action by entering the funds transfer transaction in Example 9-4. Example 9-4. read more..

  • Page - 262

    Using EXPLAIN MySQL comes with a powerful tool for investigating how the queries you issue to it are interpreted. Using EXPLAIN , you can get a snapshot of any query to find out whether you could issue it in a better or more efficient way. Example 9-6 shows how to use it with the accounts table you created earlier. Example 9-6. Using the EXPLAIN command EXPLAIN SELECT read more..

  • Page - 263

    Whenever you have a query that seems to be taking longer than you think it should to execute, try using EXPLAIN to see where you can optimize it. You will discover which keys (if any) are being used, their lengths, and so on, and will be able to adjust your query or the design of your table(s) accordingly. When you have finished experimenting with the read more..

  • Page - 264

    The basic format of the mysqldump command is: mysqldump -u user -p password database However, before you can dump the contents of a database, you must make sure that mysqldump is in your path, or that you specify its location as part of your command. Table 9-13 shows the likely locations of the program for the different installations and operating systems covered in read more..

  • Page - 265

    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 user read more..

  • Page - 266

    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 - 267

    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 - 268

    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 hand, it is not updated very often, you read more..

  • Page - 269

    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 - 270

    The Process The process of using MySQL with PHP is: 1. Connect to MySQL. 2. Select the database to use. 3. Build a query string. 4. Perform the query. 5. Retrieve the results and output them to a web page. 6. Repeat Steps 3 to 5 until all desired data has been retrieved. 7. Disconnect from MySQL. We’ll work through these sections in turn, but first it’s important read more..

  • Page - 271

    The $db_hostname variable will tell PHP which computer to use when connecting to a database. This is required, because you can access MySQL databases on any computer connected to your PHP installation, and that potentially includes any host anywhere on the Web. However, the examples in this chapter will be working on the local server. So, in place of specifying a domain read more..

  • Page - 272

    The die message explains that it was not possible to connect to the MySQL database, and—to help identify why this happened—includes a call to the mysql_error function. This function outputs the error text from the last called MySQL function. The database server pointer $db_server will be used in some of the following examples to identify the MySQL server to be queried. read more..

  • Page - 273

    Building and executing a query Sending a query to MySQL from PHP is as simple as issuing it using the mysql_query function. Example 10-4 shows you how to use it. Example 10-4. Querying a database <?php $query = "SELECT * FROM classics"; $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); ?> First, the variable read more..

  • Page - 274

    $query = "SELECT * FROM classics"; $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); $rows = mysql_num_rows($result); for ($j = 0 ; $j < $rows ; ++$j) { echo 'Author: ' . mysql_result($result,$j,'author') . '<br>'; echo 'Title: ' . mysql_result($result,$j,'title') . read more..

  • Page - 275

    Figure 10-1. The output from the query.php program in Example 10-5 Fetching a row It was important to show how you can fetch a single cell of data from MySQL, but now let’s look at a much more efficient method. Replace the for loop of query.php (in Example 10-5) with the new loop in Example 10-6, and you will find that you get exactly the same result that read more..

  • Page - 276

    In this modified code, only one-fifth of the calls are made to a MySQL-calling function (a full 80% less), because each row is fetched in its entirety via the mysql_fetch_row function. This returns a single row of data in an array, which is then assigned to the variable $row . All that’s necessary, then, is to reference each element of the array $row in turn read more..

  • Page - 277

    Example 10-8. Inserting and deleting using sqltest.php <?php // sqltest.php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); mysql_select_db($db_database, $db_server) or die("Unable to select database: " . mysql_error()); if (isset($_POST['delete']) && read more..

  • Page - 278

    $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); $rows = mysql_num_rows($result); for ($j = 0 ; $j < $rows ; ++$j) { $row = mysql_fetch_row($result); echo <<<_END <pre> Author $row[0] Title $row[1] Category $row[2] Year $row[3] ISBN $row[4] read more..

  • Page - 279

    Figure 10-2. The output from Example 10-8, sqltest.php The $_POST Array I mentioned in an earlier chapter that a browser sends user input through either a GET request or a POST request. The POST request is usually preferred, and we use it here. The web server bundles up all of the user input (even if the form was filled out with a hundred fields) and puts in into read more..

  • Page - 280

    forget about $_POST after that. This is normal in PHP programs: they retrieve all the fields from $_POST at the beginning of the program and then ignore it. There is no reason to write to an element in the $_POST array. Its only purpose is to communicate information from the browser to the pro‐ gram, and you’re better read more..

  • Page - 281

    Instead of the echo command, the program could also drop out of PHP using ?> , issue the HTML, and then reenter PHP processing with <?php . Whichever style used is a matter of programmer preference, but I always recommend staying within PHP code for these reasons: • It makes it very clear when read more..

  • Page - 282

    Finally, you see the definition for the function get_post , which we’ve already looked at. And that’s it—our first PHP program to manipulate a MySQL database. So, let’s check out what it can do. Once you have typed the program (and corrected any typing errors), try entering the following data into the various input fields to add a new record for the book Moby Dick read more..

  • Page - 283

    Now let’s look at how deleting a record works by creating a dummy record. So try entering just the number 1 in each of the five fields and click on the ADD RECORD button. If you now scroll down, you’ll see a new record consisting just of 1s. Obviously this record isn’t useful in this table, so now click on the DELETE RECORD button and scroll down again read more..

  • Page - 284

    $query = "CREATE TABLE cats ( id SMALLINT NOT NULL AUTO_INCREMENT, family VARCHAR(32) NOT NULL, name VARCHAR(32) NOT NULL, age TINYINT NOT NULL, PRIMARY KEY (id) )"; $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); ?> As you can see, the MySQL query looks pretty similar read more..

  • Page - 285

    for ($k = 0 ; $k < 4 ; ++$k) echo "<td>$row[$k]</td>"; echo "</tr>"; } echo "</table>"; ?> The output from the program should look like this: Column Type Null Key id smallint(6) NO PRI family varchar(32) NO name varchar(32) NO age tinyint(4) NO Dropping a read more..

  • Page - 286

    if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); mysql_select_db($db_database) or die("Unable to select database: " . mysql_error()); $query = "INSERT INTO cats VALUES(NULL, 'Lion', 'Leo', 4)"; $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); ?> You may wish to add a couple more read more..

  • Page - 287

    $row = mysql_fetch_row($result); echo "<tr>"; for ($k = 0 ; $k < 4 ; ++$k) echo "<td>$row[$k]</td>"; echo "</tr>"; } echo "</table>"; ?> This code simply issues the MySQL query SELECT * FROM cats and then displays all the rows returned. Its output is as follows: Id read more..

  • Page - 288

    Deleting Data Growler the cougar has been transferred to another zoo, so it’s time to remove him from the database; see Example 10-15. Example 10-15. Removing Growler the cougar from the cats table <?php require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); read more..

  • Page - 289

    echo "The Insert Id was: " . mysql_insert_id(); if (!$result) die ("Database access failed: " . mysql_error()); ?> The contents of the table should now look like the following (note how the previous id value of 2 is not reused, as this could cause complications in some instances): Id Family Name Age 1 Lion Leo 4 3 Cheetah read more..

  • Page - 290

    5. Insert data into the second table. You can safely release the lock before inserting data into the second table, because the insert ID has been retrieved and is stored in a program variable. You could also use a transaction instead of locking, but that slows down the MySQL server even more. Performing Additional Queries OK, that’s enough feline fun. To explore some read more..

  • Page - 291

    This program uses an initial query to the customers table to look up all the customers and then, given the ISBN of the book each customer purchased, makes a new query to the classics table to find out the title and author for each. The output from this code should be as follows: Mary Smith purchased ISBN 9780582506206: 'Pride and Prejudice' by Jane Austen Jack read more..

  • Page - 292

    makes as admin. But what about the case in which your application code removes a user from the database? The code might look something like this: $user = $_POST['user']; $pass = $_POST['pass']; $query = "DELETE FROM users WHERE user='$user' AND pass='$pass'"; Again, this looks quite normal at first glance, but what if someone entered the following for $user ? anything' read more..

  • Page - 293

    function mysql_fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return mysql_real_escape_string($string); } ?> Remember that you can use mysql_real_escape_string only when a MySQL database is actively open; otherwise, an error will occur. Using Placeholders Another way—this one virtually bulletproof—to prevent read more..

  • Page - 294

    In PHP, the code for this procedure looks like Example 10-21 (assuming that you have created login.php with the correct details to access the database). Example 10-21. Using placeholders with PHP <?php require 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); read more..

  • Page - 295

    But preventing this is as simple as calling the htmlentities function, which strips out all HTML markup codes and replaces them with a form that displays the characters, but does not allow a browser to act on them. For example, consider the following HTML: <script src='http://x.com/hack.js'> </script><script>hack();</script> This code loads in a JavaScript program and read more..

  • Page - 296

    if (get_magic_quotes_gpc()) $string = stripslashes($string); return mysql_real_escape_string($string); } ?> Now that you have learned how to integrate PHP with MySQL and avoid malicious user input, the next chapter will explain how to use the improved MySQLi extension for your MySQL queries. Questions 1. What is the standard PHP function for connecting to a read more..

  • Page - 297

    CHAPTER 11 Using the mysqli Extension Now that you understand how to access a MySQL database using PHP and the proce‐ dural mysql extensions, it’s time to learn how to do this with the improved mysqli extension. This is an object-oriented system, but there is a procedural version available if you prefer, and I’ll show you how to use both. Querying a MySQL Database read more..

  • Page - 298

    Connecting to MySQL With the login.php file saved, you access the database with the require_once statement, and connect to the server in the manner shown in Example 11-2. Example 11-2. Connecting to a MySQL server with mysqli <?php require_once 'login.php'; $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database); if ($connection->connect_error) read more..

  • Page - 299

    yourself to retrieve these results (as depicted in Figure 11-1). I suggest that you save this script using the filename query-mysqli.php. Example 11-4. Fetching results with mysqli, one cell at a time <?php // query-mysqli.php require_once 'login.php'; $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database); if ($connection->connect_error) read more..

  • Page - 300

    Figure 11-1. The result of running Example 11-4 Fetching a row To fetch one row at a time, replace the for loop from Example 11-4 with the one high‐ lighted in bold in Example 11-5, and you will find that you get exactly the same result that was displayed in Figure 11-1. You may wish to save this revised file as fetchrow- mysqli.php. Example 11-5. Fetching read more..

  • Page - 301

    for ($j = 0 ; $j < $rows ; ++$j) { $result->data_seek($j); $row = $result->fetch_array(MYSQLI_ASSOC); echo 'Author: ' . $row['author'] . '<br>'; echo 'Title: ' . $row['title'] . '<br>'; echo 'Category: ' . $row['category'] . '<br>'; echo 'Year: ' . $row['year'] . read more..

  • Page - 302

    amounts of data, it can be a good idea to free the memory you have been using to prevent problems later in your script. This becomes particularly important on higher traffic pages, because the amount of memory consumed in a session can rapidly grow. Therefore, note the calls to the close methods of the objects $result and $connection in the preceding scripts, as soon read more..

  • Page - 303

    $year = get_post($connection, 'year'); $isbn = get_post($connection, 'isbn'); $query = "INSERT INTO classics VALUES" . "('$author', '$title', '$category', '$year', '$isbn')"; $result = $connection->query($query); if (!$result) echo "INSERT failed: $query<br>" . $connection->error . read more..

  • Page - 304

    { return $connection->real_escape_string($_POST[$var]); } ?> How this code works is explained in Chapter 10, so all we need to examine here are the differences between Examples 10-8 and 11-6. Let’s work through them in order. The first couple of lines pull in the code from login.php and create a $connection object to gain access to the database. Then read more..

  • Page - 305

    And to make a MySQL query, you would use code such as the following: $result = mysqli_query($link, "SELECT * FROM classics"); Upon return, $result will contain the data. You can find out the number of rows re‐ turned as follows: $rows = mysqli_num_rows($result)); An integer is returned in $rows . You can fetch the actual data one row at a time in the following read more..

  • Page - 306

    read more..

  • Page - 307

    CHAPTER 12 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 - 308

    Example 12-1. formtest.php—a simple PHP form handler <?php // formtest.php echo <<<_END <html> <head> <title>Form Test</title> </head> <body> <form method="post" action="formtest.php"> What is your name? <input read more..

  • Page - 309

    Retrieving Submitted Data Example 12-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 12-2 expands on the previous program to include data read more..

  • Page - 310

    Figure 12-2. formtest.php with data handling 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 read more..

  • Page - 311

    If you 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 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 read more..

  • Page - 312

    Figure 12-3. Using default values for selected form fields Input Types HTML forms are very versatile and allow you to submit a wide range of input types, from text boxes and text areas to checkboxes, radio buttons, and more. Text boxes The input type you will probably use most often is the text box. It accepts a wide range of alphanumeric text and other characters in read more..

  • Page - 313

    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, like this: <textarea name=" name" cols="width" rows="height" wrap="type"> This is some default text. </textarea> To control the width and height, use the cols read more..

  • Page - 314

    If you want to allow groups of items to be selected at one time, assign them all the same name. However, only the last item checked will be submitted, unless you pass an array as the name. For example, Example 12-4 allows the user to select his favorite ice creams (see Figure 12-4 for how it displays in a browser). Example 12-4. Offering multiple checkbox choices read more..

  • Page - 315

    for one, two, or all three selections. In each case, an array of one, two, or three items is created. Table 12-2. The seven possible sets of values for the array $ice One value submitted Two values submitted Three values submitted $ice[0] => Vanilla $ice[0] => Chocolate $ice[0] => Strawberry $ice[0] => Vanilla $ice[1] => Chocolate $ice[0] read more..

  • Page - 316

    Figure 12-5. Selecting a single value with radio buttons Hidden fields Sometimes it is convenient to have hidden form fields so that you can keep track of the state of form entry. For example, you might wish to know whether a form has already been submitted. You can achieve this by adding some HTML in your PHP code, such as the following: echo '<input read more..

  • Page - 317

    for his or her favorite vegetable from a choice of five, you might use HTML as in Example 12-7, which offers a single selection. Example 12-7. Using select Vegetables <select name="veg" size="1"> <option value="Peas">Peas</option> <option value="Beans">Beans</option> <option value="Carrots">Carrots</option> <option read more..

  • Page - 318

    size attribute if you wish, and the output will be the same; however, with a larger list, the drop-down box might take up too much screen space, so I recommend that you pick a suitable number of rows and stick with it. I also recommend against multiple select boxes smaller than two rows in height—some browsers may not correctly display the scroll bars needed to read more..

  • Page - 319

    Sanitizing Input Now we return to PHP programming. It can never be emphasized enough that handling user data is a security minefield, and that it is essential to learn to treat all such data with utmost caution from the word go. It’s actually not that difficult to sanitize user input from potential hacking attempts, but it must be done. The first thing to remember is read more..

  • Page - 320

    Example 12-9. The sanitizeString and sanitizeMySQL functions <?php function sanitizeString($var) { $var = stripslashes($var); $var = htmlentities($var); $var = strip_tags($var); return $var; } function sanitizeMySQL($connection, $var) { // Using the mysqli extension $var = $connection->real_escape_string($var); $var = read more..

  • Page - 321

    { $c = intval((5 / 9) * ($f - 32)); $out = "$f °f equals $c °c"; } elseif($c != '') { $f = intval((9 / 5) * $c + 32); $out = "$c °c equals $f °f"; } else $out = ""; echo <<<_END <html> <head> <title>Temperature Converter</title> read more..

  • Page - 322

    Figure 12-8. The temperature conversion program in action So, having either submitted values or empty strings in both $f and $c , the next portion of code constitutes an if ... elseif ... else structure that first tests whether $f has a value. If not, it checks $c ; otherwise, the variable $out is set to the empty string (more on that in a moment). If $f is read more..

  • Page - 323

    different values into the fields; for a bit of fun, can you find a value for which Fahrenheit and Celsius are the same? All the examples in this chapter have used the POST method to send form data. I recommend this, as it’s the neatest and most secure method. However, the forms can easily be changed to use the GET read more..

  • Page - 324

    Because this feature will cause the focus to move in to an input element, the backspace key will no longer take the user back a web page (although Alt-Left and Alt-Right will still move backward and forward within the browsing history). The placeholder Attribute The placeholder attribute lets you place into any blank input field a helpful hint to explain to users what they read more..

  • Page - 325

    The width and height Attributes Using these new attributes, you can alter the dimensions of an input image, like this: <input type='image' src='picture.png' width='120' height='80'> Features Awaiting Full Implementation Because HTML5 is still in its early days (even though it’s been around for many years), browser developers have been implementing features according to their own schedules, read more..

  • Page - 326

    The min and max Attributes With the min and max attributes you can specify minimum and maximum values for inputs, but currently not in Firefox or IE. You use the attributes like this: <input type='time' name='alarm' value='07:00' min='05:00' max='09:00'> The browser will then either offer up and down selectors for the range of values allowed, or simply disallow values outside of read more..

  • Page - 327

    However, without support from IE or Firefox, these pickers are probably not worth using in your web pages yet. There are a few other form-related enhancements to HTML5 that are still under de‐ velopment, and you can keep abreast of them at http://tinyurl.com/h5forms. The next chapter will show you how to use cookies and authentication to store users’ preferences and keep read more..

  • Page - 328

    read more..

  • Page - 329

    CHAPTER 13 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 rec‐ ognize people when they return to your site. Several read more..

  • Page - 330

    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 - 331

    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 transferred, you can call the setcookie function, which has the following syntax (see Table 13-1): read more..

  • Page - 332

    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 - 333

    Although it is usually installed with Apache, HTTP authentication may not necessarily be installed on the server you use. So attempt‐ ing to run these examples may generate an error telling you that the feature is not enabled, in which case you must install the module, change the configuration file to read more..

  • Page - 334

    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 Examples 13-1 through 13-5, you may prefer to test them on a different serv‐ er. To determine the read more..

  • Page - 335

    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 re‐ opens all browser windows, as the web browser will keep returning the same username and password to PHP. You may need to close and reopen your browser a few read more..

  • Page - 336

    mised 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 of text into a seemingly random string. Due to their one-way nature, such functions are virtually impossible to reverse, so their output can be safely stored in a database—and anyone who steals it will read more..

  • Page - 337

    Here some random characters have been placed both before and after the password. Given just the database, and without access to your PHP code, it should now be next to impossible to work out the stored passwords. All you have to do when verifying someone’s login password is to add these same random strings back in before and after it, and then check the resulting read more..

  • Page - 338

    $result = $connection->query($query); if (!$result) die($connection->error); } ?> This program will create the table users within your publications database (or whichever database you set up for the login.php file in Chapter 10). In this table, it will create two users: Bill Smith and Pauline Jones. They have the usernames and passwords of bsmith/ read more..

  • Page - 339

    die ("Please enter your username and password"); } $connection->close(); function mysql_entities_fix_string($connection, $string) { return htmlentities(mysql_fix_string($connection, $string)); } function mysql_fix_string($connection, $string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return read more..

  • Page - 340

    Figure 13-4. Bill Smith has now been authenticated By sanitizing input immediately after it is encountered, you will block any malicious HTML, JavaScript, or MySQL attacks before they can get any further, and will not have to sanitize this data again. Remem‐ ber, however, that if a user has characters such as < read more..

  • Page - 341

    $_SESSION['variable'] = $value; They can then be read back just as easily in later program runs, like this: $variable = $_SESSION['variable']; Now assume that you have an application that always needs access to the username, password, first name, and last name of each user, as stored in the table users, which you should have created a little earlier. So let’s further modify read more..

  • Page - 342

    $_SESSION['surname'] = $row[1]; echo "$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'"; die ("<p><a href=continue.php>Click here to continue</a></p>"); } read more..

  • Page - 343

    else echo "Please <a href='authenticate2.php'>click here</a> to log in."; ?> Now you are ready to call up authenticate2.php into your browser. Enter a username of bsmith and password of mysecret (or pjones and acrobat ) when prompted, and click the link to load in continue.php. When your browser calls it up, the result should be something like Figure 13-5. read more..

  • Page - 344

    Example 13-7. A handy function to destroy a session and its data <?php function destroy_session_and_data() { session_start(); $_SESSION = array(); setcookie(session_name(), '', time() - 2592000, '/'); session_destroy(); } ?> To see this in action, you could modify continue.php as in Example 13-8. Example 13-8. Retrieving session variables read more..

  • Page - 345

    Setting a Timeout There are other times when you might wish to close a user’s session yourself, such as when the user has forgotten or neglected to log out, and you want the program to do so for his for her own security. You do this by setting the timeout after which a logout will automatically occur if there has been no activity. To do this, use the ini_set read more..

  • Page - 346

    is a problem for you, use SSL. You can also store a copy of the browser user agent string (a string that developers put in their browsers to identify them by type and ver‐ sion), which might also distinguish users due to the wide variety of browser types, versions, and computer platforms. Use the following to store the user agent: $_SESSION['ua'] = read more..

  • Page - 347

    Press Reload a few times here, and you should see it count up again from 0. Leave the counter on a different number than the first URL and then go back to the first URL and see how the number changes back. You have created two different sessions of your own choosing here, and you could easily create as many as you needed. The reason this approach is so read more..

  • Page - 348

    With that setting, the ?PHPSESSID= trick will be completely ignored. If you use this security measure, I also recommend you inform your users that your site requires cookies, so they know what’s wrong if they don’t get the results they want. Using a shared server On a server shared with other accounts, you will not want to have all your session data saved into the read more..

  • Page - 349

    9. What is session hijacking? 10. What is session fixation? See “Chapter 13 Answers” on page 648 in Appendix A for the answers to these questions. Questions | 321 read more..

  • Page - 350

    read more..

  • Page - 351

    CHAPTER 14 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 - 352

    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 14-1. Example 14-1. “Hello World” displayed using JavaScript <html> read more..

  • Page - 353

    When Example 14-1 is loaded, a web browser with JavaScript enabled will output the following (see Figure 14-1): Hello World Figure 14-1. JavaScript, enabled and working A browser with JavaScript disabled will display the message in Figure 14-2. Figure 14-2. JavaScript has been disabled Using Scripts Within a Document Head In addition to placing a script within the body of a read more..

  • Page - 354

    Example 14-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 the read more..

  • Page - 355

    Or, to pull a file in from the Internet, use: <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 read more..

  • Page - 356

    To try out whichever Error Console you are using, let’s create a script with a minor error. Example 14-3 is much the same as Example 14-1, but the final double quotation mark has been left off the end of the string "Hello World" —a common syntax error. Example 14-3. A JavaScript “Hello World” script with an error <html> <head><title>Hello read more..

  • Page - 357

    If you will be entering the following code snippets to try them out, don’t forget to surround them with <script> and </script> tags. Using Comments Due to their shared inheritance from the C programming language, PHP and JavaScript have many similarities, one of which is commenting. First, there’s the single-line com‐ ment, like this: read more..

  • Page - 358

    Variables No particular character identifies a variable in JavaScript as the dollar sign does in PHP. Instead, variables use the following naming rules: • A variable may include only the letters a–z , A–Z , 0–9 , the $ symbol, and the under‐ score (_). • No other characters, such as spaces or punctuation, are allowed in a variable name. • The first character read more..

  • Page - 359

    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. To assign values to an array, use the following syntax (which in this case creates an array of strings): toys = ['bat', 'ball', 'whistle', 'puzzle', 'doll'] To create a multidimensional array, nest smaller arrays within a larger read more..

  • Page - 360

    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 + 2) The following sections teach you about the various operators. Arithmetic Operators Arithmetic operators are read more..

  • Page - 361

    Table 14-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 operators are generally used inside a construct such as an if read more..

  • Page - 362

    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 handles string concatenation slightly differently from PHP. Instead of the . (period) operator, it uses the plus sign (+), like this: document.write("You have read more..

  • Page - 363

    Character Meaning \\ 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 00 and FF that represents the Latin-1 character equivalent (such as \xA9 for the © symbol) \u XXXX A hexadecimal number between 0000 read more..

  • Page - 364

    If there is ever any doubt about the type of a variable, or you need to ensure that a variable has a particular type, you can force it to that type using statements such as the following (which respectively turn a string into a number and a number into a string): n = "123" n *= 1 // Convert 'n' into a number n = 123 n += "" // read more..

  • Page - 365

    To define a local variable that has scope only within the current function, and has not been passed as a parameter, use the var keyword. Example 14-10 shows a function that creates one variable with global scope and two with local scope. Example 14-10. A function creating variables with global and local scope <script> function test() { a = read more..

  • Page - 366

    The Document Object Model The designers of JavaScript were very smart. Rather than just creating yet another scripting language (which would have still been a pretty good improvement at the time), they had the vision to build it around the Document Object Model, or DOM. This breaks down the parts of an HTML document into discrete objects, each with its own proper‐ ties read more..

  • Page - 367

    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 central column down. The first part, document , read more..

  • Page - 368

    url = document.links.mylink.href with the following: url = mylink.href But It’s Not That Simple If you tried Example 14-12 in Safari, Firefox, Opera, or Chrome, it will have worked just great. But in Internet Explorer it will fail, because Microsoft’s implementation of JavaScript, called JScript, has many subtle differences from the recognized standards. Welcome to the world of read more..

  • Page - 369

    can replace code such as: document.getElementById('mylink').href Using the DOM The links object is actually an array of URLs, so the mylink URL in Example 14-12 can also be safely referred to on all browsers in the following way (because it’s the first, and only, link): url = document.links[0].href If you want to know how many links there are in an entire document, you read more..

  • Page - 370

    Questions 1. Which tags do you use to enclose JavaScript code? 2. By default, to which part of a document will JavaScript code output? 3. How can you include JavaScript code from another source in your documents? 4. Which JavaScript function is the equivalent of echo or print in PHP? 5. How can you create a comment in JavaScript? 6. What is the JavaScript string read more..

  • Page - 371

    CHAPTER 15 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 control the program flow of your scripts using conditional statements. Expressions JavaScript expressions are very similar to those in PHP. As you learned in read more..

  • Page - 372

    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 evaluate to true with the exception of the following, which read more..

  • Page - 373

    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 15-3 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 read more..

  • Page - 374

    Operator Precedence As with PHP, JavaScript utilizes operator precedence, in which some operators in an expression are considered more important than others and are therefore evaluated first. Table 15-2 lists JavaScript’s operators and their precedences. Table 15-2. The precedence of JavaScript operators (high to low) Operator(s) Type(s) () [] . Parentheses, call, and member ++ read more..

  • Page - 375

    Table 15-3. Operators and associativity Operator Description Associativity ++ −− Increment and decrement None new Create a new object Right + − ~ ! Unary and bitwise Right ?: Ternary Right = *= /= %= += −= Assignment Right <<= >>= >>>= &= ^= |= Assignment Right , Separator Left + − * / % Arithmetic Left << >> >>> read more..

  • Page - 376

    Example 15-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 - 377

    Table 15-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 15-7, which outputs 0 , 1 , and true . Example 15-7. The read more..

  • Page - 378

    Table 15-5. All possible logical expressions Inputs Operators and results a b && || 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 you’ve seen in earlier chapters on PHP, because it’s exclusive to JavaScript. With it (if you see what I mean), you can simplify some types of read more..

  • Page - 379

    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 - 380

    Figure 15-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 se‐ lected section of code, rather than all scripts in a document. However, they do not catch syntax errors, for which read more..

  • Page - 381

    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 - 382

    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") } As you can see, you can use another else after the new if , which could equally be followed by another if statement, and so on. Although I have shown braces on the statements, read more..

  • Page - 383

    case "Home": document.write("You selected Home") break case "About": document.write("You selected About") break case "News": document.write("You selected News") break case "Login": document.write("You selected Login") read more..

  • Page - 384

    Example 15-16 shows a ternary operator being used to print out whether the variable a is less than or equal to 5, and prints something either way. Example 15-16. Using the ternary operator <script> document.write( a <= 5 ? "a is less than or equal to 5" : "a is greater than 5" ) </script> The statement has been read more..

  • Page - 385

    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 easy to ter‐ minate with Escape or the Stop button. So be careful with your JavaScript loops. do ... read more..

  • Page - 386

    These are separated by semicolons, like this: for ( expr1 ; expr2 ; expr3) . At the start of the first iteration of the loop, the initialization expression is executed. In the case of the code for the multiplication table for 7, count would be initialized to the value 1 . Then, each time around the loop, the condition expression (in this case, count <= 7 ) read more..

  • Page - 387

    } else document.write(j + ", ") } </script> This script outputs the following: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - Found at location 17 The continue Statement Sometimes you don’t want to entirely exit from a loop, but instead wish to skip the remaining statements just for this iteration of the loop. In such read more..

  • Page - 388

    Explicit Casting Unlike PHP, JavaScript has no explicit casting of types such as (int) or (float) . Instead, when you need a value to be of a certain type, use one of JavaScript’s built-in functions, shown in Table 15-6. Table 15-6. JavaScript’s type-changing functions Change to type Function to use Int, Integer parseInt() Bool, Boolean Boolean() Float, Double, Real read more..

  • Page - 389

    9. Why is a for loop more powerful than a while loop? 10. What is the purpose of the with statement? See “Chapter 15 Answers” on page 649 in Appendix A for the answers to these questions. Questions | 361 read more..

  • Page - 390

    read more..

  • Page - 391

    CHAPTER 16 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 - 392

    • The parentheses are required. • 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 func‐ tions: getInput , GETINPUT , and getinput . In JavaScript there is a general naming convention for functions: the read more..

  • Page - 393

    wasteful programming. Luckily, the arguments array gives you the flexibility to handle a variable number of arguments. Example 16-2 shows how you can use it to rewrite the example in a much more efficient manner. Example 16-2. Modifying the function to use the arguments array <script> function displayItems() { for (j = 0 ; j < displayItems.arguments.length read more..

  • Page - 394

    When called with the parameters the , DALLAS , and CowBoys , for example, the function 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, isolating the parameter’s first character using the charAt read more..

  • Page - 395

    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 statement, we made its value available to the caller, which could store or use it any way it wanted. But s itself disappears at the end of the function. Although we could make a function operate on global read more..

  • Page - 396

    JavaScript Objects A JavaScript object is a step up from a variable, which can contain only one value at a time, in that objects can contain multiple values and even functions. An object groups data together with the functions needed to manipulate it. Declaring a Class When creating a script to use objects, you need to design a composite of data and code called a class. read more..

  • Page - 397

    • A new function named showUser is created within the function. The syntax shown here is new and rather complicated, but its purpose is to tie showUser to the User class. Thus, showUser comes into being as a method of the User class. The naming convention I have used is to keep all properties in lowercase and to use at least one uppercase character in method read more..

  • Page - 398

    details.greeting = "Hello" You can verify that adding such new properties works with the following statement: document.write(details.greeting) Accessing Objects To access an object, you can refer to its properties, as in the following two unrelated example statements: name = details.forename if (details.username == "Admin") loginAsAdmin() So, to access the showUser method of an read more..

  • Page - 399

    document.write("Username: " + this.username + "<br>") document.write("Password: " + this.password + "<br>") } } </script> This works because all functions have a prototype property, designed to hold properties and methods that are not replicated in any objects created from a class. Instead, they are passed to its read more..

  • Page - 400

    Extending JavaScript objects The prototype keyword even lets you add functionality to a built-in object. For example, suppose that you would like to add the ability to replace all spaces in a string with nonbreaking spaces in order to prevent it from wrapping around. You can do this by adding a prototype method to JavaScript’s default String object definition, like this: read more..

  • Page - 401

    Numeric Arrays To create a new array, use the following syntax: arrayname = new Array() Or you can use the shorthand form, as follows: arrayname = [] Assigning element values In PHP, you could add a new element to an array by simply assigning it without speci‐ fying the element offset, like this: $arrayname[] = "Element 1"; $arrayname[] = "Element 2"; But in read more..

  • Page - 402

    Assignment using the array keyword You can also create an array together with some initial elements using the Array key‐ word, like this: numbers = Array("One", "Two", "Three") There is nothing stopping you from adding more elements afterward as well. So now you have a couple of ways you can add items to an array, and one way of refer‐ encing read more..

  • Page - 403

    Multidimensional Arrays To create a multidimensional array in JavaScript, just place arrays inside other arrays. For example, to create an array to hold the details of a two-dimensional checkerboard (8×8 squares), you could use the code in Example 16-10. Example 16-10. Creating a multidimensional numeric array <script> checkerboard = Array( Array(' ', 'o', ' ', 'o', ' ', 'o', read more..

  • Page - 404

    You can also directly access any element within this array using square brackets, as follows: document.write(checkerboard[7][2]) This statement outputs the uppercase letter O , the eighth element down and the third along—remember that array indexes start at 0, not 1. Using Array Methods Given the power of arrays, JavaScript comes ready-made with a number of methods for manipulating read more..

  • Page - 405

    } </script> In this case, the function passed to forEach is called output . It takes three parameters: the element , its index , and the array . These can be used as required by your function. In this example, just the element and index values are displayed using the function document.write . Once an array has been populated, the method is called like this: read more..

  • Page - 406

    push and pop You already saw how the push method can be used to insert a value into an array. The inverse method is pop . It deletes the most recently inserted element from an array and returns it. Example 16-13 shows an example of its use. Example 16-13. Using the push and pop methods <script> sports = ["Football", "Tennis", read more..

  • Page - 407

    The output from this example is: Pushed 0 Pushed 1 Pushed 2 Popped 2 Popped 1 Popped 0 Using reverse The reverse method simply reverses the order of all elements in an array. Example 16-15 shows this in action. Example 16-15. Using the reverse method <script> sports = ["Football", "Tennis", "Baseball", "Hockey"] sports.reverse() read more..

  • Page - 408

    document.write(numbers + "<br>") </script> The first of the four example sections is the default sort method, alphabetical sort, while the second uses the default sort and then applies the reverse method to get a reverse alphabetical sort. The third and fourth sections are a little more complicated; they use a function to com‐ pare the relationships read more..

  • Page - 409

    CHAPTER 17 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 validation to ensure that the data is as complete and correct as it can read more..

  • Page - 410

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

  • Page - 411

    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, save it as validate.html, and when you call it up in your browser, it will look like Figure read more..

  • Page - 412

    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 open‐ ing <form> tag. Using onSubmit , you can cause a function of your choice to be called when a form is read more..

  • Page - 413

    !/[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" else if (field < 18 || field > 110) return "Age must be between 18 and 110.\n" return "" } function validateEmail(field) { read more..

  • Page - 414

    Validating the username The validateUsername function is a little more interesting, because it has a more com‐ plicated job. It has to allow through only the characters a–z , A–Z , 0–9 , _ and - , and ensure that usernames are at least five characters long. The if ... else statements commence by returning an error if field has not been filled in. If it’s read more..

  • Page - 415

    and the _ , - , period and @ characters, as detailed in the regular expression passed to the test method. If no errors are found, the empty string is returned to indicate successful validation. On the last line, the script and document are closed. Figure 17-2 shows the result of the user clicking on the Signup button without having completed any fields. Figure 17-2. read more..

  • Page - 416

    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 as‐ terisk (*) has a meaning similar to what you have seen if you use a shell or Windows Command Prompt (but not quite the same). An asterisk means, “the text you’re trying to read more..

  • Page - 417

    Unfortunately, the plus sign keeps on matching up to the last > on the line, so you might end up with: <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 * , then read more..

  • Page - 418

    The space after the + character indicates that the match must end when a space is en‐ countered. Without it, 1,000,00 would incorrectly match because only the first 1,000 would be taken into account, and the remaining ,00 would be ignored. Requiring a space afterward ensures that matching will continue right through to the end of a number. Character classes Sometimes you read more..

  • Page - 419

    The character class consists of a single character—an exclamation point—but it is in‐ verted by the preceding ^ . This is actually not a great solution to the problem—for instance, it fails if “Yahoo” is a t the end of the line, because then it’s not followed by anything, whereas the brackets must match a character. A better solution involves neg‐ ative lookahead read more..

  • Page - 420

    > 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, return‐ ing the longest match possible. Nongreedy matching finds the short‐ est read more..

  • Page - 421

    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 (^) appears at the beginning of the read more..

  • Page - 422

    Metacharacters Description element+ Matches element one or more times element? Matches element zero or one times [ characters] Matches a character out of those contained within the brackets [^ characters] Matches a single character that is not contained within the brackets ( regex) Treats the regex as a group for counting or a read more..

  • Page - 423

    Table 17-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 or reciive) rec(ei|ie)ve Either of receive or recieve (but not receeve or reciive) cat The word cat in read more..

  • Page - 424

    the text that matches. Like most functions, replace generates a new string as a return value; it does not change the input. To compare the two methods, the following statement just returns true to let us know that the word cats appears at least once somewhere within the string: document.write(/cats/i.test("Cats are funny. I like cats.")) But the following statement read more..

  • Page - 425

    When you want to replace part of a string, you can use preg_replace as shown here. This example replaces all occurrences of the word cats with the word dogs, regardless of case: echo preg_replace("/cats/i", "dogs", "Cats are furry. I like cats."); The subject of regular expressions is a large one and entire books have been written about read more..

  • Page - 426

    echo "<!DOCTYPE html>\n<html><head><title>An Example Form</title>"; if ($fail == "") { echo "</head><body>Form data successfully validated: $forename, $surname, $username, $password, $age, $email.</body></html>"; // This is where you would enter the posted fields into a database, // read more..

  • Page - 427

    else if (field.length < 5) return "Usernames must be at least 5 characters.\n" else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n" return "" } function validatePassword(field) { read more..

  • Page - 428

    <td><input type="text" maxlength="16" name="username" value="username"> </td></tr><tr><td>Password</td> <td><input type="text" maxlength="12" name="password" value="password"> </td></tr><tr><td>Age</td> read more..

  • Page - 429

    if ($field == "") return "No Age was entered<br>"; else if ($field < 18 || $field > 110) return "Age must be between 18 and 110<br>"; return ""; } function validate_email($field) { if ($field == "") return "No Email was entered<br>"; else if read more..

  • Page - 430

    This courtesy is highly recommended so that the user has to edit only the previously entered values, and doesn’t have to type the fields all over again. Figure 17-5. The form as represented after PHP validation fails In the real world, you probably wouldn’t start with an HTML form such as the one in Example 17-1. Instead, you’d be read more..

  • Page - 431

    Questions 1. What JavaScript method can you use to send a form for validation prior to sub‐ mitting it? 2. What JavaScript method is used to match a string against a regular expression? 3. Write a regular expression to match any characters that are not in a word, as defined by regular expression syntax. 4. Write a regular expression to match either of the words fox read more..

  • Page - 432

    read more..

  • Page - 433

    CHAPTER 18 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 into JavaScript to transfer data between the browser and a server in the background. An excellent example of this technology is Google Maps (see Figure 18-1), in which new sections of a map are down‐ read more..

  • Page - 434

    Figure 18-1. Google Maps is an excellent example of Ajax in action Using XMLHttpRequest Due to 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 = new read more..

  • Page - 435

    Example 18-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 - 436

    Table 18-1. An XMLHttpRequest object’s properties Properties 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 - 437

    Example 18-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 - 438

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

  • Page - 439

    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 18-1, you’ll see that readyState can have five different values. But only one of them concerns us: value 4 , which represents a completed Ajax read more..

  • Page - 440

    The server half of the Ajax process Now we get to the PHP half of the equation, which you can see in Example 18-3. Type it and save it as urlpost.php. Example 18-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 - 441

    Figure 18-2. The Amazon mobile website has been loaded into a DIV Using GET Instead of POST As with submitting any form data, you have the option of submitting your data in the form of GET requests, and you will save a few lines of code if you do so. However, there is a downside: some browsers may cache GET requests, whereas POST requests will never be cached. read more..

  • Page - 442

    <h1>Loading a web page into a DIV</h1> <div id='info'>This sentence will be replaced</div> <script> nocache = "&nocache=" + Math.random() * 1000000 request = new ajaxRequest() request.open("GET", "urlget.php?url=amazon.com/gp/aw" + nocache, true) request.onreadystatechange = function() read more..

  • Page - 443

    } </script> </body> </html> The differences to note between the two documents are highlighted in bold, and de‐ scribed as follows: • It is not necessary to send headers for a GET request. • We call the open method using a GET request, supplying a URL with a string com‐ prising a ? symbol followed by the parameter/value read more..

  • Page - 444

    of which is XML. As you have seen, we have requested an entire HTML document via Ajax, but we could equally have asked for a text page, a string or number, or even spreadsheet data. So let’s modify the previous example document and PHP program to fetch some XML data. To do this, first take a look at the PHP program, xmlget.php, shown in Example 18-6. Example read more..

  • Page - 445

    if (this.readyState == 4) { if (this.status == 200) { if (this.responseText != null) { titles = this.responseXML.getElementsByTagName('title') for (j = 0 ; j < titles.length ; ++j) read more..

  • Page - 446

    Again, the changes have been highlighted in bold, so you can see that this code is sub‐ stantially similar to previous versions, except that the URL now being requested, rss.news.yahoo.com/rss/topstories, contains an XML document, the Yahoo! News Top Stories feed. The other big difference is the use of the responseXML property, which replaces the responseText property. Whenever a read more..

  • Page - 447

    <item> <title>Headline</title> <guid>http://website.com/headline</guid> <description>This is a headline</description> </item> <item> <title>Headline 2</title> <guid>http://website.com/headline2</guid> <description>The 2nd headline</description> read more..

  • Page - 448

    Figure 18-4. Fetching a Yahoo! XML news feed via Ajax Using Frameworks for Ajax Now that you know how to code your own Ajax routines, you might like to investigate some of the free frameworks that are available to make it even easier, as they offer many more advanced features. In particular, I would suggest you check out jQuery, which is probably the most commonly used read more..

  • Page - 449

    Questions 1. Why is it necessary to write a function for creating new XMLHttpRequest objects? 2. What is the purpose of the try ... catch construct? 3. How many properties and how many methods does an XMLHttpRequest object have? 4. How can you tell when an Ajax call has completed? 5. How do you know whether an Ajax call completed successfully? 6. What XMLHttpRequest read more..

  • Page - 450

    read more..

  • Page - 451

    CHAPTER 19 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 (Docu‐ ment Object Model), which I explained in Chapter 14. With CSS and its integration with the DOM, you can quickly and easily restyle any element. For example, if you read more..

  • Page - 452

    Figure 19-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 you need. This lets you apply different style sheets for different layouts (such read more..

  • Page - 453

    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 - 454

    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 - 455

    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 values starting at the same horizontal offset. In the preceding examples, the final semicolon is unnecessary, but should you ever want read more..

  • Page - 456

    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 (and any user styles you may have applied in your browser to override its defaults), read more..

  • Page - 457

    Figure 19-2. Applying a user style to Internet Explorer External Style Sheets The next types of styles are those assigned in an external style sheet. These settings will override any assigned either by the user or by the browser. External style sheets are the recommended way to create your styles because you can produce different style sheets for different purposes such as read more..

  • Page - 458

    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 - 459

    <!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 - 460

    Now the word Hello will not change color because it is not a direct child of the paragraph. For a practical example, suppose you wish to embolden 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 do not get emboldened: <!DOCTYPE read more..

  • Page - 461

    Because IDs normally apply only to unique elements, the following rule will apply an underline to only the first occurrence of myid : #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 read more..

  • Page - 462

    The Attribute Selector Many HTML tags support attributes, and using this type of selector can save you from having to use IDs and classes to refer to them. For example, you can directly reference attributes in the following manner, which sets all elements with the attribute type="sub mit" to a width of 100 pixels: [type="submit"] { width:100px; } If you wish to read more..

  • Page - 463

    3. Find all p sub-elements of the objects returned in step 2 and, because this is the final selector in the group, also find all p sub- and sub-sub-elements (and so on) of the objects returned in step 2. 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 read more..

  • Page - 464

    Cascading is a method used to resolve potential conflicts between the various types of style sheet a browser supports, and apply them in order of precedence by who created them, the method used to create the style, and the types of properties selected. Style Sheet Creators There are three main types of style sheet supported by all modern browsers. In order of precedence from read more..

  • Page - 465

    Style Sheet Selectors There are three different ways of selecting elements to be styled. Going from highest to lowest order of precedence, they are: • Referencing by individual ID or attribute selector • Referencing in groups by class • Referencing by element tags (such as <p> or <b> ) Selectors are processed according to the number and types of elements affected read more..

  • Page - 466

    In cases where there are nine or fewer of each type in a compound number, you can convert it directly to a decimal number, which in this case is 352. Rules with a lower number than this will have lower precedence, and those with a higher number will have greater precedence. Where two rules share the same value, the most recently applied one wins. Using a different read more..

  • Page - 467

    The Difference Between Div and Span Elements Both <div> and <span> elements are types of containers, but with some different qual‐ ities. By default, a <div> element has infinite width (at least to the browser edge), which you can see by applying a border to one, like this: <div style="border:1px solid green;">Hello</div> A <span> element, read more..

  • Page - 468

    Figure 19-4. A variety of elements of differing width The figure also shows how <span> elements keep to themselves and take up only the space required to hold their content, without forcing subsequent content to appear below them. For example, in the bottom two examples of the figure, you can also see that when <div> elements wrap around the screen edge they read more..

  • Page - 469

    Points A point is equivalent in size to 1/72 of an inch. The measurement comes from a print design background and is best suited for that medium, but is also commonly used on monitors. For example: .classname { font-size:14pt; } Inches An inch is the equivalent of 72 points and is also a measurement type best suited for print. For example: .classname { width:3in; } read more..

  • Page - 470

    .classname { height:120%; } Figure 19-5 shows each of these measurement types in turn being used to display text in almost identical sizes. Figure 19-5. Different measurements that display almost the same Fonts and Typography There are four main font properties that you can style using CSS: family , style , size , and weight . Between them, you can fine-tune the way text read more..

  • Page - 471

    p { font-family:"Times New Roman", Georgia, serif; } Because they should be available on virtually all web browsers and operating systems, the safest font families to use on a web page are Arial, Helvetica, Times New Roman, Times, Courier New, and Couri‐ er. The Verdana, Georgia, Comic Sans MS, Trebuchet MS, Arial Black, and read more..

  • Page - 472

    p { font-size:14pt; } Alternatively, you may wish to work with the current default font size, using it to style various types of text such as headings. In the following rules, relative sizes of some headers are defined, with the <h4> tag starting off 20% bigger than the default, and with each greater size another 40% larger than the previous one: h1 { font-size:240%; read more..

  • Page - 473

    style and font-weight properties, while others such as underlining require the text- decoration property. Decoration With the text-decoration property, you can apply effects to text such as underline , line-through , overline , and blink . The following rule creates a new class called over that applies overlines to text (the weight of over, under, and through lines will match read more..

  • Page - 474

    Alignment Four types of text alignment are available in CSS: left , right , center , and justify . In the following rule, default paragraph text is set to full justification: p { text-align:justify; } Transformation There are four properties available for transforming text: none , capitalize , upper case , and lowercase . The following rule creates a class called upper that will read more..

  • Page - 475

    CSS Colors You can apply colors to the foreground and background of text and objects 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 hexadecimal RGB triplets (such as #ff0000 or #0000ff ), or colors created using read more..

  • Page - 476

    Wherever you intend to use a color such as #883366 , this is the direct equivalent of #836 (because the repeated digits are implied by the shorter version), and you can use either string to create the exact same color. Gradients In place of using a solid background color, you can choose to apply a gradient, which will then automatically flow from a given initial color to read more..

  • Page - 477

    Figure 19-10. A solid background color, a linear gradient, and a radial gradient To create a gradient, choose where it will begin out of top , bottom , left , right , and center (or any combination, such as top left or center right ), enter the start and end colors you require, and then apply either the linear-gradient or radial- gradient rule, making sure you read more..

  • Page - 478

    #object { position:absolute; top :100px; left :200px; } Relative Positioning Likewise, you can move the object relative to the location it would occupy in the normal document flow. So, for example, to move object 10 pixels down and 10 pixels to the right of its normal location, you would use the following rules: #object { position:relative; read more..

  • Page - 479

    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 absolute positioning is located exactly at 100 pixels down, with 0 horizontal offset, while the element with relative positioning is actually moved up by 8 pixels and then offset from the left margin by 110 read more..

  • Page - 480

    Pseudo-Classes There are a number of selectors and classes that are used only within a style sheet and do not have any matching tags or attributes within any HTML. Their task is to classify elements using characteristics other than their name, attributes, or content—that is, characteristics that cannot be deduced from the document tree. These include pseudo- classes such as read more..

  • Page - 481

    rule uses the universal selector to always place a mid-gray, dotted, 2-pixel border around the currently focused object: *:focus { border:2px dotted #888888; } Example 19-5 displays two links and an input field, as shown in Figure 19-12. The first link shows up as gray because it has already been visited in this browser, but the second link has not and displays in blue. read more..

  • Page - 482

    Beware of applying the focus pseudo-class to the universal selector, * , as shown in this example; Internet Explorer regards an unfocused document as actually having focus applied to the entire web page, and (in this instance) the whole page will turn yellow until Tab is press‐ ed or focus is otherwise read more..

  • Page - 483

    The box model of an object starts at the outside, with the object’s margin. Inside this is the border, then there is padding between the border and the inner contents, and finally there’s the object’s contents. Once you have the hang of the box model, you will be well on your way to creating professionally laid-out pages, as these properties alone will make up read more..

  • Page - 484

    Example 19-6. How margins are applied <!DOCTYPE html> <html> <head> <title>Margins</title> <style> #object1 { background :lightgreen; border-style:solid; border-width:1px; font-family :"Courier New"; font-size :9px; width read more..

  • Page - 485

    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 of these can have other subproperties added as suffixes, such as -color , read more..

  • Page - 486

    The third element has a 1 pixel wide top, its sides are 5 pixels wide, and its bottom is 10 pixels wide. The fourth element has a 1-pixel top border width, a 5-pixel right border width, a 10-pixel bottom border width, and a 15-pixel left border width. The final element, under the previous ones, doesn’t use the shorthand rules; instead, it has each of the border read more..

  • Page - 487

    font-size :12px; text-align :justify; display :table-cell; width :148px; padding :10px 20px 30px 40px; } </style> </head> <body> <div id='object1'>To be, or not to be that is the question: Whether 'tis Nobler read more..

  • Page - 488

    5. Which characters are used to prefix (a) IDs, and (b) class names in a CSS rule? 6. In CSS rules, what is the purpose of the semicolon? 7. How can you add a comment to a style sheet? 8. Which character is used by CSS to represent any element? 9. How can you select a group of different elements and/or element types in CSS? 10. Given a pair of CSS rules with read more..

  • Page - 489

    CHAPTER 20 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 second spec‐ ification, CSS2; its standard was completed in 2007 and revised in 2009. Development read more..

  • Page - 490

    Table 20-1. CSS selectors, pseudo-classes, and pseudo-elements 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 - 491

    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 - 492

    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 - 493

    Figure 20-1. Different ways of combining CSS3 background properties The background-origin Property With the background-origin property, you can control where a background image will be located by specifying where the top left of the image should start. For example, the following declaration states that the background image’s origin should be the top-left corner of the outer edge of read more..

  • Page - 494

    background-origin:padding-box; Or to set the origin of an image to the top-left corner of an element’s inner content section, you would use this declaration: background-origin:content-box; Looking again at Figure 20-1, you can see in each row the first box uses a background- origin property of border-box , the second uses padding-box , and the third uses content-box . Consequently, read more..

  • Page - 495

    Multiple Backgrounds With CSS3 you can now attach multiple backgrounds to an element, each of which can use the previously discussed CSS3 background properties. Figure 20-2 shows an exam‐ ple of this; eight different images have been assigned to the background, to create the four corners and four edges of the certificate border. Figure 20-2. A background created with multiple read more..

  • Page - 496

    Example 20-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 - 497

    CSS3 Borders CSS3 also brings a lot more flexibility to the way borders can be presented, by allowing 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 can read more..

  • Page - 498

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

  • Page - 499

    </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'> border-top-left-radius &nbsp;&nbsp;&nbsp;:40px read more..

  • Page - 500

    So, for example, to create a rounded border with a radius of 20 pixels, you could simply 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 read more..

  • Page - 501

    Figure 20-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 contained by its parent by setting the overflow property to hidden , visible , scroll , or auto . But with CSS3, you can read more..

  • Page - 502

    Figure 20-5. Flowing text in multiple columns Example 20-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 - 503

    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 needed for multiple columns, but they improve the text read more..

  • Page - 504

    lightens the color until it shows as white. You can visualize this as if you are mixing levels of either black or white into the color. Therefore, for example, to choose a fully saturated yellow color with standard percent brightness, you would use a declaration such as this: color:hsl(60, 100%, 50%); Or, for a darker blue color, you might use a declaration such as: read more..

  • Page - 505

    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 in it than green, you could make a good first guess at 0% red, 40% green, and 60% blue, and try a declaration such as this: color:rgb(0%, 40%, 60%); RGBA Colors As with read more..

  • Page - 506

    The result of this declaration looks like Figure 20-6, and works in all recent versions of all major browsers (but not IE9 or lower). Figure 20-6. Applying a shadow to text The text-overflow Property When using any of the CSS overflow properties with a value of hidden , you can also use the text-overflow property to place an ellipsis (three dots) just before the cutoff read more..

  • Page - 507

    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 prop‐ erty 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 20-9 the read more..

  • Page - 508

    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 - 509

    Figure 20-11. It’s easy to include Google’s web fonts 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 rectangular layout of <div> and other elements, because read more..

  • Page - 510

    You can supply one or more of the following functions to the transform property: matrix Transforms an object by applying a matrix of values to it translate Moves an element’s origin scale Scales an object rotate Rotates an object skew Skews an object There are also single versions of many of these functions, such as translateX , scaleY , and so on. So, for example, to read more..

  • Page - 511

    3D Transformations You can also transform objects in three dimensions using the following CSS3 3D trans‐ formation 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 element to another location in its 3D space scale3d read more..

  • Page - 512

    specify an animation effect you want to occur when an element is transformed, and the browser will automatically take care of all the in-between frames for you. There are four properties you should supply in order to set up a transition, as follows: transition-property : property; transition-duration : time; transition-delay : time; read more..

  • Page - 513

    Transition Timing The transition-timing function property requires one of the following values: ease Start slowly, get faster, and then end slowly. linear Transition at constant speed. ease-in Start slowly, and then go quickly until finished. ease-out Start quickly, stay fast until near the end, and then end slowly. ease-in-out Start slowly, go fast, and then end slowly. Using any of read more..

  • Page - 514

    Example 20-4. A transition on hover effect <!DOCTYPE html> <html> <head> <title>Transitioning on hover</title> <style> #square { position :absolute; top :50px; left :50px; width read more..

  • Page - 515

    Figure 20-14. The object rotates and changes color when hovered over The sample code caters to all the different browsers by providing browser-specific ver‐ sions of the declarations. On all the latest browsers (including IE10 or higher), the object will rotate clockwise when hovered over, while slowly changing from orange to yellow. CSS transitions are smart in that when they read more..

  • Page - 516

    read more..

  • Page - 517

    CHAPTER 21 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 that you can create animations or provide any code that must continue read more..

  • Page - 518

    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 21-1. Example 21-1. The O() function function O(obj) { if (typeof obj == 'object') return obj else return read more..

  • Page - 519

    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 - 520

    Then a new array called objects is created, into which all the matching objects found will be placed: var objects = [] Next, a for loop iterates through all the elements in the elements object using the variable i as the index: for (var i = 0 ; i < elements.length ; ++i) Each time around the loop, if an element’s className property is the same as the string read more..

  • Page - 521

    Example 21-4. The OSC.js file function O(obj) { if (typeof obj == 'object') return obj else return document.getElementById(obj) } function S(obj) { return O(obj).style } function C(name) { var elements = document.getElementsByTagName('*') var objects = [] for (var i = 0 ; i < elements.length ; ++i) if (elements[i].className == name) read more..

  • Page - 522

    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 - 523

    Figure 21-1. Modifying styles from JavaScript Other Properties JavaScript also opens up access to a very wide range of other properties, such as the width and height of the browser and of any pop-up or in-browser windows or frames, handy information such as the parent window (if there is one), and the history of URLs visited this session. All these properties are accessed from read more..

  • Page - 524

    Properties Sets and/or returns pageYOffset Returns the pixels the document has been scrolled vertically from the top of the window parent Returns the parent window of a window screen Returns the screen object for the window screenLeft Returns the x coordinate of the window relative to the screen in all recent browsers read more..

  • Page - 525

    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, there are far more properties and methods available than can be covered in this chapter. However, now that you know how to access and use properties, all you need is a resource listing them all, so I recommend that read more..

  • Page - 526

    Figure 21-2. Inline mouse hover JavaScript example When supplied from an inline JavaScript call, the this keyword rep‐ resents the calling object. When used in class methods, it represents 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 read more..

  • Page - 527

    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 21-2 lists these events and details when they will be triggered. Table 21-2. Events and when they are triggered Event Occurs onabort When an image’s loading is read more..

  • Page - 528

    Adding New Elements With JavaScript you are not limited to manipulating the elements and objects supplied 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 21-8 shows one way you can add it to the web page. Example 21-8. Inserting an element into the DOM read more..

  • Page - 529

    Figure 21-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, to make sure the new element is instantly revealed, its offset Top property is read into the throwaway variable tmp . This forces a DOM refresh and makes the element display in any browser that might otherwise read more..

  • Page - 530

    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 property 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 new read more..

  • Page - 531

    Using Interrupts JavaScript provides access to interrupts, a method by which you can ask the browser to call your code after a set period of time, or even to keep calling it at specified intervals. This gives you a means of handling background tasks such as Ajax communications, or even things like animating web elements. To accomplish this, you have two types of read more..

  • Page - 532

    Repeating timeouts One technique some programmers use to provide repeating interrupts with setTime out is to call the setTimeout function from the code called by it, as with the following, which will initiate a never-ending loop of alert windows: setTimeout(dothis, 5000) function dothis() { setTimeout(dothis, 5000) alert('I am annoying!') } Now the alert will pop up every five read more..

  • Page - 533

    <script> setInterval("showtime(O('time'))", 1000) function showtime(object) { var date = new Date() object.innerHTML = date.toTimeString().substr(0,8) } </script> </body> </html> Figure 21-4. Maintaining the correct time with interrupts Every time ShowTime is read more..

  • Page - 534

    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 somebody has disabled JavaScript (which people sometimes do for security reasons), your JavaScript will not run and the user will see the original 00:00:00 . Canceling an interval In order to read more..

  • Page - 535

    <script> SIZE = LEFT = 0 setInterval(animate, 30) function animate() { SIZE += 10 LEFT += 3 if (SIZE == 200) SIZE = 0 if (LEFT == 600) LEFT = 0 S('box').width = SIZE + 'px' S('box').height = SIZE read more..

  • Page - 536

    Questions 1. What are the O , S , and C functions provided to do? 2. Name two ways to modify a CSS attribute of an object. 3. Which properties provide the width and height available in a browser window? 4. How can you make something happen when the mouse passes both over and out of an object? 5. Which JavaScript function creates new elements, and which appends them read more..

  • Page - 537

    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 - 538

    technology that uses visual and voice input—like Google Glass and the Galaxy 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 so many parts of the specification are usable on virtually all devices and browsers, I’m pleased to read more..

  • Page - 539

    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 canvas At this point it’s not necessary to detail exactly what is going on, as I read more..

  • Page - 540

    other places; letting you know which friends are near you; directing you to the nearest 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 user’s read more..

  • Page - 541

    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 been used to display a map Again, here is not the place to describe read more..

  • Page - 542

    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 - 543

    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 meager space read more..

  • Page - 544

    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 infor‐ mation it can read more..

  • Page - 545

    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 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 - 546

    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) context.closePath() context.fill() </script> </body> read more..

  • Page - 547

    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, be‐ ginning at an angle of 0 degrees (which is the righthand edge of the circle as you look at it), and continuing all the read more..

  • Page - 548

    <img id='myimage'> <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 * read more..

  • Page - 549

    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 com‐ pression to use between 0 (for lowest quality) and 1 (for highest read more..

  • Page - 550

    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, supplying any valid CSS color argument: context.strokeStyle = 'green' read more..

  • Page - 551

    Figure 23-2. Drawing concentric rectangles The createLinearGradient Method There are a couple of different ways you can apply a gradient to a fill, but the simplest is with the createLinearGradient method. You specify start and end x and y coordi‐ nates relative to the canvas (not the object being filled). This allows for greater subtlety. For example, you can specify that read more..

  • Page - 552

    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 is applied to the fillStyle property of con text , so that the final fillRect call can use it. read more..

  • Page - 553

    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 linear gradients In this example, I chose to place the gradients directly on top of read more..

  • Page - 554

    In the preceding examples, only the two start and end values were chosen, but to create 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 color stops gradient.addColorStop(0.00, 'red') gradient.addColorStop(0.14, 'orange') gradient.addColorStop(0.28, 'yellow') gradient.addColorStop(0.42, 'green') read more..

  • Page - 555

    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 circumfer‐ ence, 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 - 556

    Figure 23-7. A stretched radial gradient 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 document, or even one created from a canvas via the toDataURL method (explained earlier in this chapter). Example 23-9 loads a 100×100-pixel image (the yin-yang symbol) into the new image read more..

  • Page - 557

    Figure 23-8. Tiling an image by using it as a pattern fill We create the pattern using the createPattern method, which also supports nonrep‐ eating 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 vertically and read more..

  • Page - 558

    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 with read more..

  • Page - 559

    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 read more..

  • Page - 560

    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 - 561

    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 - 562

    context.lineJoin = 'bevel' Example 23-12 (shown here in full because it’s a little more complicated) applies all three values of each property used in combination, creating the informative result shown in Figure 23-11. The beginPath , closePath , moveTo , and lineTo methods used by this example are explained next. Example 23-12. Displaying combinations of line caps and joins read more..

  • Page - 563

    </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 with the fillText method. Using these settings, the code then draws nine shapes with a read more..

  • Page - 564

    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, if you are having trouble with your pointed miters, simply increase the value you supply for miterLimit until the miter displays. Using Paths The previous example made use read more..

  • Page - 565

    The stroke Method The stroke method has the job of actually drawing all the lines created so far in a path onto the canvas. If it is issued from inside an unclosed path, this has the effect of im‐ mediately drawing everything up to the most recent imaginary pen location. However, if you close a path and then issue a call to stroke , it has the effect of also read more..

  • Page - 566

    All you really need to look at, however, are the lines highlighted in bold, in which a path is started, a pair of lineTo calls defines the shape, the path is closed, and then the stroke and fill methods are used to draw the shape outline in orange and fill it in with yellow (as shown in Figure 23-12). Example 23-13. Filling in a complex path <!DOCTYPE html> read more..

  • Page - 567

    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 want to ignore read more..

  • Page - 568

    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 simply need read more..

  • Page - 569

    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 high‐ lighted in bold, and as read more..

  • Page - 570

    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 clipping can be when used effectively. The isPointInPath Method Sometimes you need to know whether a particular point lies in a path you’ve construc‐ ted. However, you will probably only want to use this function if you’re read more..

  • Page - 571

    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 read more..

  • Page - 572

    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, 400, 70, 0, arcs[j], true) context.stroke() read more..

  • Page - 573

    Figure 23-15. A variety of arc types If you prefer to work with degrees instead of radians, you could cre‐ ate 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, read more..

  • Page - 574

    The arcTo Method Rather than creating a whole arc at once, you can choose to arc from the current location 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 lines read more..

  • Page - 575

    Figure 23-16. Drawing arcs of different radii The quadraticCurveTo Method Useful as arcs are, they are only one type of curve and can be limiting for more complex designs. But have no fear: there are still more ways to draw curves—for example, by using the quadraticCurveTo method. With this method, you can place an imaginary attractor near (or far from) a curve to pull read more..

  • Page - 576

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

  • Page - 577

    Figure 23-18. A Bézier curve with 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 to draw every type of curve you read more..

  • Page - 578

    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 read more..

  • Page - 579

    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, because it does, I’m afraid read more..

  • Page - 580

    Copying from a Canvas You can also use a canvas as a source image for drawing to the same (or another) canvas. 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 read more..

  • Page - 581

    Example 23-21. Applying shadows when drawing on the canvas myimage = new Image() myimage.src = 'apple.png' 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) read more..

  • Page - 582

    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 meth‐ ods, 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 a read more..

  • Page - 583

    { 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] = average - 50 pos += 4; } read more..

  • Page - 584

    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 point, the value 319 is multiplied by 4 (the number of read more..

  • Page - 585

    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’d like to perform more advanced image manipulations, you may wish to refer to the following (third-party) web pages, read more..

  • Page - 586

    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 trans‐ formations 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, read more..

  • Page - 587

    destination-atop The source image displays where the destination is not displayed. Where the des‐ tination 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 over‐ lap, they display as normal; read more..

  • Page - 588

    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 en‐ hance the display, which isn’t shown here because it’s not essential to the read more..

  • Page - 589

    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% opaque (or 10% transparent): context.globalAlpha = 0.9 This property read more..

  • Page - 590

    Figure 23-23. Scaling an image up and then down again The save and restore Methods If you need to use several scaling operations on different drawing elements, not only can you introduce fuzziness into the results, but it can be very time-consuming to cal‐ culate that a three times upward scaling requires a 0.33 value to scale back down again (and a two times upscale read more..

  • Page - 591

    Rotation takes place around the canvas origin, which, by default, is its top-left corner (but as you’ll see shortly, this can be changed). Example 23-25 displays the yin-yang image four times, rotating each consecutive image by Math.PI / 25 radians. Example 23-25. Rotating an image for (j = 0 ; j < 4 ; ++j) { context.drawImage(myimage, 20 + j * 120 , 20) read more..

  • Page - 592

    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 usually, somewhere within the destination location of the object (usually its center). Example 23-26 performs this translation prior to each call to rotate , now resulting in the effect that read more..

  • Page - 593

    1. Save the context. 2. Translate the canvas origin to the center of where the object is to be placed. 3. Issue the rotation or transformation instruction. 4. Draw the object with any of the drawing methods supported, using a negative des‐ tination location point half the object’s width to the left, and half its height upward. 5. Restore the context to revert the read more..

  • Page - 594

    Note how the horizontal and vertical scaling arguments are given values of 1 to ensure a 1:1 result, while the skew values are 0 to pre‐ vent the result from being skewed. You could even combine the previous two lines of code to get a translation and scale at the same time, like this: context.transform(3, 0, 0, 2 , 20 + w read more..

  • Page - 595

    The setTransform Method As an alternative to using the save and restore methods, you can set an absolute transform, which has the effect of resetting the transformation matrix and then applying the supplied values. Use the setTransform method just like transform , as in this ex‐ ample (which applies a horizontal positive skew with the value 1 ): context.setTransform(1, 0, 1 read more..

  • Page - 596

    read more..

  • Page - 597

    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 - 598

    Finally, it is now 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 user ever having to download a plug-in or make any other changes. There are still a read more..

  • Page - 599

    It is 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, read more..

  • Page - 600

    In this example, I included three different audio types, because that’s perfectly accept‐ able, and can be a good idea if you wish to ensure that each browser can locate its preferred 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 both) of the MP3 or the AAC files is read more..

  • Page - 601

    <script> function playaudio() { O('myaudio').play() } function pauseaudio() { O('myaudio').pause() } </script> </body> </html> Figure 24-2. HTML5 audio can be controlled with JavaScript This works by calling the play or pause methods read more..

  • Page - 602

    Here we take advantage of the fact that on non-HTML5 browsers, anything inside the <audio> tag (other than the <source> elements, which are ignored) will be acted on by the browser. Therefore, by placing an <object> element there that calls up a Flash player, we ensure that any non-HTML5 browsers will at least have a chance of playing the audio, as long read more..

  • Page - 603

    Figure 24-4. Playing HTML5 video The Video Codecs As with audio, there are a number of video codecs available, with differing support across multiple browsers. These codecs come in different containers, as follows: 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, which has its read more..

  • Page - 604

    These may then contain one of the following video codecs: H.264 A patented, proprietary video codec for which playback is free for the end user, but which may incur royalty fees for all parts of the encoding and transmission process. At the time of writing, all of Apple, Google, Mozilla Firefox, and Microsoft Internet Explorer support this codec, while Opera (the remaining read more..

  • Page - 605

    autoplay Causes the video to start playing as soon as it is ready controls Causes the control panel to be displayed height Specifies the height at which to display the video loop Sets the video to play over and over muted Mutes the audio output poster Lets you choose an image to display where the video will play preload Causes the video to begin loading before the user read more..

  • Page - 606

    <script> function playvideo() { O('myvideo').play() } function pausevideo() { O('myvideo').pause() } </script> </body> </html> Figure 24-5. JavaScript is being used to control the video This code is just like controlling audio from read more..

  • Page - 607

    Example 24-6. Providing Flash as a fallback video player <video width='560' height='320' controls> <object width='560' height='320' type='application/x-shockwave-flash' data='flowplayer.swf'> <param name='movie' value='flowplayer.swf'> <param name='flashvars' value='config={"clip": { "url": "http://tinyurl.com/html5video-mp4", read more..

  • Page - 608

    autoPlay If true , plays automatically; otherwise, waits for the play button to be clicked autoBuffering If true , in order to minimize buffering later on with slow connections, before it starts playing the video will be preloaded sufficiently for the available bandwidth For more information on the Flash flowplayer program (and an HTML5 version), check out read more..

  • Page - 609

    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 extensions to HTML, because you access them with JavaScript read more..

  • Page - 610

    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 communication towers with which it can communicate (and whose positions are very precisely known). If there read more..

  • Page - 611

    Geolocation and HTML5 In Chapter 22, I briefly introduced HTML5 geolocation. Now it’s time to look at it in depth, starting with the example I gave you before, shown again in Example 25-1. Example 25-1. Displaying a map of your current location <!DOCTYPE html> <html> <head> <title>Geolocation Example</title> <script read more..

  • Page - 612

    case 4: message = 'Unknown Error'; break; } O('status').innerHTML = message } </script> </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 read more..

  • Page - 613

    var lat = position.coords.latitude var long = position.coords.longitude var gmap = O('map') After this, the object gopts is populated with the values in lat and long , the zoom level is set (in this case to 9), and the ROADMAP map type is selected: var gopts = { center: new google.maps.LatLng(lat, long), zoom: 9, mapTypeId: google.maps.MapTypeId.ROADMAP } Lastly, in read more..

  • Page - 614

    switch(error.code) { case 1: message = 'Permission Denied'; break; case 2: message = 'Position Unavailable'; break; case 3: message = 'Operation Timed Out'; break; case 4: message = 'Unknown Error'; break; } O('status').innerHTML = message The Google map will be fully interactive and zoomable by the user, who can also change the map type to satellite imagery. You can read more..

  • Page - 615

    you could create in-browser web apps and services for editing word processing docu‐ ments, spreadsheets, and graphic images, saving all this data offsite on users’ computers and keeping your server purchasing budget as low as possible. From the user’s point of view, think about how much faster a document can be loaded up locally than from across the Web, especially on a read more..

  • Page - 616

    Once you’ve ascertained that local storage is available, you can start making use of it with the setItem and getItem methods of the localStorage object, like this: localStorage.setItem('username', 'ceastwood') localStorage.setItem('password', 'makemyday') To later retrieve this data, pass the keys to the getItem method, like this: username = localStorage.getItem('username') password = read more..

  • Page - 617

    password = localStorage.getItem('password') alert("The current values of 'username' and 'password' are\n\n" + username + " / " + password) } 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 read more..

  • Page - 618

    Example 25-3. Setting up and communicating with a web worker <!DOCTYPE html> <html> <head> <title>Web Workers</title> <script src='OSC.js'></script> </head> <body> Current highest prime number: <span id='result'>0</span> <script> if (!!window.Worker) { read more..

  • Page - 619

    for (var i = 2; i <= Math.sqrt(n); i += 1) { if (n % i == 0) continue search } postMessage(n) } 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 read more..

  • Page - 620

    Example 25-5. The clock.appcache file CACHE MANIFEST clock.html OSC.js clock.css clock.js The first line in this file declares it to be a manifest file. The lines following list the files the browser needs to download and store, starting with Example 25-6, the clock.html file, and followed by the OSC.js file, which is the same one used by many examples in this book. Example read more..

  • Page - 621

    This is a very simple anonymous function attached to an interval that repeats once a second to save the current date and time into the innerHTML property of the <output> element that has the ID of clock . The final file is the clock.css file (see Example 25-8), which simply applies bold styling to the <output> element. Example 25-8. The clock.css file output { read more..

  • Page - 622

    <img id='source1' src='image1.png' draggable='true' ondragstart='drag(event)'> <img id='source2' src='image2.png' draggable='true' ondragstart='drag(event)'> <img id='source3' src='image3.png' draggable='true' ondragstart='drag(event)'> <script> function allow(event) { event.preventDefault() } function drag(event) read more..

  • Page - 623

    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 during these operations. Cross Document Messaging You’ve already seen messaging read more..

  • Page - 624

    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 HTML> read more..

  • Page - 625

    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> window.onmessage = function(event) { O('output').innerHTML = read more..

  • Page - 626

    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, like this: O('frame').contentWindow.postMessage('Message ' + count++, 'http://localhost' ) Likewise, as it stands, the listener program displays read more..

  • Page - 627

    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 networking site, with microdata added to the various elements (shown highlighted in bold). The result looks like Figure 25-5, which will look the same with or without microdata, read more..

  • Page - 628

    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 microdata. However, at some point browsers may also find a use for read more..

  • Page - 629

    Figure 25-6. Displaying the value for the ‘jobTitle’ microdata key Google has stated that it definitely uses microdata when it finds it, and that microdata is also the preferred snippet format for Google+, so it’s well worth starting to add it to your HTML where applicable. For a complete breakdown of the myriad of microdata properties available, check out http://schema.org, read more..

  • Page - 630

    Questions 1. What method do you call to request geolocation data from a web browser? 2. How can you determine whether or not a browser supports local storage? 3. What method can you call to erase all local storage data for the current domain? 4. What is the best way for web workers to communicate with a main program? 5. How can your code inform a web browser read more..

  • Page - 631

    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 - 632

    • 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 the Website All the examples in this chapter read more..

  • Page - 633

    The Functions The project uses five main functions: 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 read more..

  • Page - 634

    function queryMysql($query) { global $connection; $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, '/'); read more..

  • Page - 635

    header.php For uniformity, each page of the project needs to have access to the same set of features. Therefore I placed these things in Example 26-2, header.php. This is the file that is actually included by the other files and it, in turn, includes functions.php. This means that only a single require_once is needed in each file. header.php starts by calling the function read more..

  • Page - 636

    else $loggedin = FALSE; 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 - 637

    Because the function createTable first checks whether a table already exists, this pro‐ gram can be safely called multiple times without generating any errors. 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 read more..

  • Page - 638

    For Example 26-3 to work, you must first ensure that you have al‐ ready created the database specified in the variable $dbname in Ex‐ ample 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 read more..

  • Page - 639

    Figure 26-1. The main page of the site Checking for Username Availability Now go back to the program start and you’ll see a block of JavaScript that starts with the function checkUser . This is called by the JavaScript onBlur event when focus is removed from the username field of the form. First it sets the contents of the span I mentioned (with the id of info ) read more..

  • Page - 640

    want to overly complicate the code, I have kept the signup and login modules separate from each other. I’m sure you can easily implement this if you want to, however. Example 26-5 uses the CSS class fieldname to arrange the form fields, aligning them neatly under each other in columns. When loaded into a browser (and in conjunction with checkuser.php, shown later), this read more..

  • Page - 641

    return request } </script> <div class='main'><h3>Please enter your details to sign up</h3> _END; $error = $user = $pass = ""; if (isset($_SESSION['user'])) destroySession(); if (isset($_POST['user'])) { $user = sanitizeString($_POST['user']); $pass = sanitizeString($_POST['pass']); if ($user == read more..

  • Page - 642

    Figure 26-2. The signup page On a production server, I wouldn’t recommend storing user pass‐ words in the clear as I’ve done here (for reasons of space and sim‐ plicity). Instead, you should salt them and store them as one-way hash strings. See Chapter 13 for more details on how to do this. read more..

  • Page - 643

    The HTML entities &#x2718; and &#x2714; are also used to preface the string with either a cross or a checkmark. Example 26-6. checkuser.php <?php require_once 'functions.php'; if (isset($_POST['user'])) { $user = sanitizeString($_POST['user']); $result = queryMysql("SELECT * FROM members WHERE user='$user'"); if ($result->num_rows) read more..

  • Page - 644

    Example 26-7. login.php <?php require_once 'header.php'; echo "<div class='main'><h3>Please enter your details to log in</h3>"; $error = $user = $pass = ""; if (isset($_POST['user'])) { $user = sanitizeString($_POST['user']); $pass = sanitizeString($_POST['pass']); if ($user == "" || $pass == "") read more..

  • Page - 645

    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 26-8, profile.php. I think you’ll find some interesting code here, such as routines to upload, resize, and sharpen images. Let’s start by looking at the main HTML at the end of the read more..

  • Page - 646

    Adding the “About Me” Text Then the POST variable text is checked to see whether some text was posted to the program. If so, it is sanitized and all long whitespace sequences (including returns and line feeds) are replaced with a single space. This function incorporates a double security check, ensuring that the user actually exists in the database and that no read more..

  • Page - 647

    Finally, the image is saved as a jpeg file in the location defined by the variable $saveto , after which we remove both the original and the resized image canvases from memory using the imagedestroy function, returning the memory that was used. Displaying the Current Profile Last but not least, so that the user can see what the current profile looks like before editing read more..

  • Page - 648

    $typeok = TRUE; switch($_FILES['image']['type']) { case "image/gif": $src = imagecreatefromgif($saveto); break; case "image/jpeg": // Both regular and progressive jpegs case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break; case "image/png": $src = imagecreatefrompng($saveto); read more..

  • Page - 649

    Image: <input type='file' name='image' size='14'> <input type='submit' value='Save Profile'> </form></div><br> </body> </html> Figure 26-4. Editing a user profile profile.php | 621 read more..

  • Page - 650

    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, where a read more..

  • Page - 651

    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 non-following member, but if the member is already fol‐ lowing 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 following. Example 26-9. read more..

  • Page - 652

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

  • Page - 653

    Figure 26-5. Using the members module friends.php The module that shows a user’s friends and followers is Example 26-10, friends.php. This interrogates the friends table just like the members.php program, but only for a single user. It then shows all of that user’s mutual friends and followers along with the people he is following. All the followers are saved into an read more..

  • Page - 654

    $followers = array_diff($followers, $mutual); $following = array_diff($following, $mutual); This results in the array $mutual containing only mutual friends, $followers contain‐ ing only followers (and no mutual friends), and $following containing only people being followed (and no mutual friends). Now that we’re armed with these arrays, it’s a simple matter to separately display read more..

  • Page - 655

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

  • Page - 656

    </body> </html> Figure 26-6. Displaying a user’s friends and followers messages.php The last of the main modules is Example 26-11, messages.php. The program starts by checking whether a message has been posted in the POST variable text . If so, it is inserted into the messages table. At the same time, the value of pm is also stored. This indicates whether read more..

  • Page - 657

    handled by a couple of queries to the MySQL database. Additionally, when a message is private, it is introduced by the word whispered and shown in italic. Finally, the program displays a couple of links to refresh the messages (in case another user has posted one in the meantime) and to view the user’s friends. The trick using the variables $name1 and $name2 is read more..

  • Page - 658

    <input type='submit' value='Post Message'></form><br> _END; if (isset($_GET['erase'])) { $erase = sanitizeString($_GET['erase']); queryMysql("DELETE FROM messages WHERE id=$erase AND recip='$user'"); } $query = "SELECT * FROM messages WHERE recip='$view' ORDER BY time DESC"; $result = read more..

  • Page - 659

    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 on a link that will take her to the un-logged-in home page and read more..

  • Page - 660

    links from the top of the screen. Of course, you could write a JavaScript or PHP redirect to do this (probably a good idea if you wish to keep logout looking clean). 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 " . read more..

  • Page - 661

    * Sets the default font family and size for the project using the universal selector. 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 read more..

  • Page - 662

    #logo These rules style the logo text as a fallback in case a non-HTML5 browser is in use and the canvas logo doesn’t get created. 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 { read more..

  • Page - 663

    .main { margin-left:40px; } .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; read more..

  • Page - 664

    javascript.js Finally, there’s the JavaScript file (see Example 26-14), which contains the O , S , and C functions used throughout this book, along with some code to draw the logo for the site using an HTML5 canvas, as explained in Chapter 23. Example 26-14. javascript.js canvas = O('logo') context = read more..

  • Page - 665

    And that, as they say, is that. If you write anything based on this code or any other examples in this book, or have gained in any other way from it, then I am glad to have been of help and thank you for reading this book. But before you go and try out your newly learned skills on the Web at large, browse through the appendixes that follow, as there’s read more..

  • Page - 666

    read more..

  • Page - 667

    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 - 668

    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 - 669

    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 to a function. In such cases, ++$j increments $j before the test or other operation is performed, whereas $j++ read more..

  • Page - 670

    6. You use the identity operator when you wish to bypass PHP’s automatic operand type changing (also called type casting). 7. The three conditional statement types are if , switch , and the ?: operator. 8. To skip the current iteration of a loop and move on to the next one, use a continue statement. 9. Loops using for statements are more powerful than while loops, read more..

  • Page - 671

    9. To call a piece of initializing code when an object is created, create a constructor method called __construct within the class and place your code there. 10. Explicitly declaring properties within a class is unnecessary, as they will be implicitly declared upon first use. But it is considered good practice as it helps with code readability and debugging, and is read more..

  • Page - 672

    4. To create a Unix timestamp for 7:11am on May 2nd 2016, you could use the command: $timestamp = mktime(7, 11, 0, 5, 2, 2016); 5. You would use the “w+” file access mode with fopen to open a file in write and read mode, with the file truncated and the file pointer at the start. 6. The PHP command for deleting the file file.txt is: unlink('file.txt'); 7. The PHP read more..

  • Page - 673

    8. SELECT DISTINCT essentially affects only the display, choosing a single row and eliminating all the duplicates. GROUP BY does not eliminate rows, but combines all the rows that have the same value in the column. Therefore, GROUP BY is useful for performing an operation such as COUNT on groups of rows. SELECT DISTINCT is not useful for that purpose. 9. To return read more..

  • Page - 674

    9. To back up the database publications to a file called publications.sql, you would use a command such as: mysqldump -u user -p password publications > publications.sql Chapter 10 Answers 1. The standard MySQL function used for connecting to a MySQL database is mysql_connect . 2. The mysql_result function is not optimal when more than one cell is being re‐ quested, read more..

  • Page - 675

    6. To escape special characters in strings, you can call the real_escape_string meth‐ od of a mysqli connection object, passing it the string to be escaped. 7. If you neglect to properly close objects created with mysqli methods, your programs carry the risk of running out of memory, especially on high-traffic websites. If there’s a program flow logic error in your read more..

  • Page - 676

    Chapter 13 Answers 1. Cookies should be transferred before a web page’s HTML, because they are sent as part of the headers. 2. To store a cookie on a web browser, use the set_cookie function. 3. To destroy a cookie, reissue it with set_cookie , but set its expiration date in the past. 4. Using HTTP authentication, the username and password are stored in $_SERV read more..

  • Page - 677

    7. Within a JavaScript function, you can define a variable that has local scope by pre‐ ceding it with the var keyword upon first assignment. 8. To display the URL assigned to the link ID thislink in all main browsers, you can use the two following commands: document.write(document.getElementById('thislink').href) document.write(thislink.href) 9. The commands to change to the read more..

  • Page - 678

    cution when they evaluate to a nonempty string. A NULL value is evaluated as false and therefore does not trigger execution. 9. Loops using for statements are more powerful than while loops, because they support two additional parameters to control loop handling. 10. The with statement takes an object as its parameter. Using it, you specify an object once; then for each read more..

  • Page - 679

    Chapter 17 Answers 1. You can send a form for validation prior to submitting it by adding the JavaScript onsubmit attribute to the <form> tag. Make sure that your function returns true if the form is to be submitted and false otherwise. 2. To match a string against a regular expression in JavaScript, use the test method. 3. Regular expressions to match read more..

  • Page - 680

    6. The responseText property of an XMLHttpRequest object contains the value re‐ turned by a successful Ajax call. 7. The responseXML property of an XMLHttpRequest object contains a DOM tree cre‐ ated from the XML returned by a successful Ajax call. 8. To specify a callback function to handle Ajax responses, assign the function name to the XMLHttpRequest object’s read more..

  • Page - 681

    Chapter 20 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, like this: border-radius:20px; 4. To flow text read more..

  • Page - 682

    Chapter 21 Answers 1. The O function returns an object by its ID, the S function returns the style property 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 also (usually) modify an read more..

  • Page - 683

    Chapter 22 Answers 1. The new HTML5 element for drawing graphics in a web browser is the canvas element, created using the <canvas> tag. 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 read more..

  • Page - 684

    gradient.addColorStop(0, 'green') gradient.addColorStop(0.3, 'red') gradient.addColorStop(0,79, 'orange') gradient.addColorStop(1, 'brown') 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 read more..

  • Page - 685

    Chapter 25 Answers 1. To request geolocation data from a web browser, you call the following method, passing the names of two functions you have written for handling access or denial to the data: navigator.geolocation.getCurrentPosition(granted, denied) 2. To determine whether or not a browser supports local storage, test the typeof property of the localStorage object, like this: if read more..

  • Page - 686

    read more..

  • Page - 687

    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/ • http://php.net read more..

  • Page - 688

    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 • http://w3schools.com/JS • read more..

  • Page - 689

    • http://html5test.com • 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 - 690

    • http://programmingforums.org • 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 662 | Appendix B: Online Resources read more..

  • Page - 691

    APPENDIX C MySQL’s FULLTEXT Stopwords This appendix contains the more than 500 stopwords referred to in the section “Creating a FULLTEXT index” on page 196 in Chapter 8. Stopwords are words that are considered so common as to not be worth searching for, or storing, in a FULLTEXT index. Theoret‐ ically, ignoring these words makes little difference to the results of read more..

  • Page - 692

    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, hadn’t, happens, hardly, has, hasn’t, have, haven’t, having, he, he’s, hello, help, hence, her, here, here’s, hereafter, hereby, herein, hereupon, hers, herself, hi, him, read more..

  • Page - 693

    R rather, rd, re, really, reasonably, regarding, regardless, regards, relatively, respective‐ ly, right S said, same, saw, say, saying, says, second, secondly, see, seeing, seem, seemed, seem‐ ing, 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, read more..

  • Page - 694

    read more..

  • Page - 695

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

  • Page - 696

    RIGHT( str, len) Returns the rightmost len characters from the string str (or NULL if any argument is NULL ). This code returns the string "Columbus" : SELECT RIGHT('Christopher Columbus', '8'); MID( str, pos, len) Returns up to len characters from the string str starting at position pos . If len is omitted, then all characters up to the end of the read more..

  • Page - 697

    LOCATE( substr, str, pos) Returns the position of the first occurrence of substr in the string str . If the pa‐ rameter 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 the word unit, while read more..

  • Page - 698

    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 as‐ sumed. The remove string is optional and, if omitted, spaces are removed. This code returns the strings "No Padding" and "Hello__" : SELECT TRIM(' read more..

  • Page - 699


  • Page - 700

    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 % character is required before each specifier, as shown. This code returns the given date and time as Friday May 4th 2018 03:02 AM : SELECT DATE_FORMAT('2018-05-04 03:02:01', '%W %M %D %Y read more..

  • Page - 701

    Specifier Description %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, two digits %% A literal % character DAY( date) Returns the day of the month for date , in the range 1 to 31 or 0 for dates that have a zero day part such as read more..

  • Page - 702

    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 De‐ cember. Dates that have a zero month part, such as 0000-00-00 or 2016-00-00, return 0 . This code read more..

  • Page - 703

    Table D-3. The modes supported by the WEEK function Mode First day of week Range Where week 1 is the first week... 0 Sunday 0–53 with a Sunday in this year 1 Monday 0–53 with more than three days this year 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 read more..

  • Page - 704

    MAKETIME( hour, minute, second) Returns a time value calculated from the hour , minute , and second arguments. This code returns the time 11:56:23 . 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 read more..

  • Page - 705

    We’d like to hear your suggestions for improving our indexes. Send email to index@oreilly.com. Index Symbols ! (Not) logical operator in JavaScript, 333, 348 in PHP, 57, 82 != (inequality) comparison operator in JavaScript, 333 in PHP, 56, 81 !== (not identical) comparison operator (Java‐ Script), 333 " (quotation marks, double) in JavaScript, 330 in MySQL, 173 in PHP, 59 # symbol, read more..

  • Page - 706

    / (division) operator in JavaScript, 332 in PHP, 55 /* ... */ remark construct, 48, 427 // (forward slash, double) remark, 326, 329 /= (division) assignment operator in JavaScript, 332 in PHP, 55 :: (double colon) scope operator, 121 ; (semicolon) CSS usage, 426 JavaScript syntax and, 324, 329 MySQL command-line interface and, 177 PHP syntax, 49 < (less than) com parison operator in read more..

  • Page - 707

    arguments classes and, 119 functions and, 104 arithmetic operators in JavaScript, 332, 345 in PHP, 55, 76, 78 (array) cast type, 99 Array keyword (JavaScript), 374 array keyword (PHP), 134 arrays in JavaScript about, 331 array methods, 376 associative arrays, 374 multidimensional arrays, 331, 375 numeric arrays, 373 as operator type, 345 returning values, 367 two-dimensional arrays, 331 in PHP read more..

  • Page - 708

    border-right property (CSS), 457 border-top property (CSS), 457 border-width property (CSS), 457 borders applying with CSS, 457 applying with CSS3, 469–472 box model (CSS) about, 454 adjusting padding, 458–459 applying borders, 457 object contents, 459 setting margins, 455–457 box-shadow property (CSS3), 472 box-sizing property (CSS), 463 <br> tag, 11, 74, 343 break statement in JavaScript, read more..

  • Page - 709

    codecs (encoders/decoders) audio supported, 570 video supported, 575 color input type (HTML5), 298 color property (CSS), 447 colors adding color stops in gradients, 525–526 CSS-supported about, 447 applying gradients, 448–449 short color strings, 447 CSS3-supported applying to borders, 469 colors and opacity, 475–477 cols attribute (forms), 285 columns (fields) about, 171–172 adding, 190 changing read more..

  • Page - 710

    destroying, 304 forcing cookie-only sessions, 319 setting, 303 third-party, 301 copy function (PHP), 158 count function (PHP), 140 CREATE command (MySQL) about, 178 adding indexes to tables, 194 creating databases, 179 creating tables, 181–182 createElement function (JavaScript), 500 createImageData method (canvas), 557 createLinearGradient method (canvas), 523–525 createPattern method (canvas), 529 read more..

  • Page - 711

    DATE data type (MySQL), 186 DATE function (MySQL), 670 date function (PHP) about, 152 date constants, 154 format specifiers, 152 returning values, 66, 67 date input type (HTML5), 298 DateTime class (PHP), 152 DATETIME data type (MySQL), 186 datetime input type (HTML5), 298 datetime-local input type (HTML5), 298 DATE_ADD function (MySQL), 670 DATE_ATOM constant (PHP), 154 DATE_COOKIE constant read more..

  • Page - 712

    DROP keyword (MySQL), 191 Duplicate entry error, 195 dynamic web content about, 1 Apache Web Server and, 11 benefits of, 5 combining technologies, 12–14 CSS and, 9 dynamic linking, 99–101 HTML and, 2 HTML5 and, 10 HTTP and, 2 JavaScript and, 8 MySQL and, 7 open source and, 12 PHP and, 6, 45 request/response process and, 2–5 E each function (PHP), 136 echo <<<_END ... _END read more..

  • Page - 713

    file handling creating login files, 242 development servers, 39 in JavaScript, 326 in PHP checking if file exists, 155 copying files, 158 creating files, 155–157 deleting files, 158 including files, 111 locking files for multiple accesses, 160– 161 moving files, 158 reading entire files, 162 reading from files, 157 requiring files, 112 updating files, 159–160 uploading files, 162–167 file read more..

  • Page - 714

    returning values, 365–367 in MySQL, 209, 667–676 one-way, 308 in PHP about, 65–71, 103 arguments and, 104 array functions, 140–144 bundling into objects, 113 creating functions, 65 date and time functions, 151–154 defining functions, 106 parentheses in, 104 passing by reference, 108–110 returning arrays, 108 returning values, 106–108 variable scope and, 66–71, 111 social networking read more..

  • Page - 715

    form handling, 279–295 importing CSS from within, 424 JavaScript and, 324–328 PHP and, 45–47 HTML injection, preventing, 266–268 HTML5, 517 (see also canvas (HTML5)) about, 169, 509, 517 <audio> elemen t, 513, 570–574 cross document messaging, 595–598 DOCTYPE declaration, 423 dynamic web content and, 10 form features awaiting full implementation, 297–299 form handling, 514 form read more..

  • Page - 716

    input types supported, 298 list attribute, 297 max attribute, 298 min attribute, 298 placeholder attribute, 296 required attribute, 296 step attribute, 298 width attribute, 297 INSERT command (MySQL) about, 178 adding data to databases, 7 adding data to tables, 188 INTO qualifier, 208 insert IDs, 261 instances of classes, 114 (int) cast type, 99 INT data type (MySQL), 185 integrated read more..

  • Page - 717

    lineWidth property (canvas), 533 link pseudo-class (CSS), 452 <link> tag, 424 links object (JavaScript), 341 Linux operating system accessing MySQL, 175 installing LAMPs, 38 ls system command, 167 list attribute (HTML5), 297 list function (PHP), 136 literals in expressions in JavaScript, 344 in PHP, 75 local storage, 515, 586–589 local variables in JavaScript, 336 in PHP, 66–68, 111 read more..

  • Page - 718

    members.php (social networking site), 622–625 messages.php (social networking site), 628–631 messaging, cross document, 595–598 metacharacters in regular expressions, 388, 393–395 __METHOD__ constant (PHP), 64 methods in JavaScript array methods, 376 DOM and, 338 prototype keyword and, 370–372 static methods, 371 in PHP about, 103, 114 constructor methods, 119, 127 destructor methods, 120 final read more..

  • Page - 719

    mysql_select_db function (PHP), 244 N \n (newline) escape character, 60, 334 name attribute (forms), 281 __NAMESPACE__ constant (PHP), 64 naming conventions JavaScript function names, 364 JavaScript variables, 330 PHP constants, 122 PHP constructor methods, 119 PHP variables, 54, 69–70 NATURAL_JOIN clause (MySQL commands), 208, 263 nesting arrays, 331 comments, 49, 329, 428 constructs, 54 NetBeans read more..

  • Page - 720

    onmouseout event, 499 onmouseover event, 499 onmouseup event, 499 onreset event, 499 onresize event, 499 onscroll event, 499 onselect event, 499 onsubmit event, 499 onunload event, 499 OOP (object-oriented programming), 113 opacity, colors and (CSS), 475–477 open source software, 12 OpenType fonts, 479 operators CSS supported, 462 in JavaScript arithmetic operators, 332, 345 arrays as, 345 assignment read more..

  • Page - 721

    functions in, 65–66, 103–111, 151–154 HTML and, 45–47 HTML forms and, 279 IDEs supported, 41–43 implementing Ajax, 412 implicit casting, 98 literals in, 75 looping in, 92–98 methods in, 103, 114, 119–121, 123–129 multiple-line commands in, 60–62 objects in, 103, 113–129 operators in, 55–57, 76–83, 121, 125 printf function, 147–151 properties in, 114, 121–125 querying MySQL read more..

  • Page - 722

    border properties, 469–472 box shadows, 472 colors and opacity, 477 element overflow, 473 text effects, 477–479 transitions, 484–487 in JavaScript accessing CSS properties, 493–497 DOM and, 338 prototype keyword and, 370–372 static properties, 371 in PHP about, 114 declaring properties, 122 property scope, 123 static methods and, 121 static properties, 124 window object, 495 XMLHttpRequest read more..

  • Page - 723

    $_REQUEST variable (PHP), 70 request/response process, 2–5 require statement (PHP), 112, 243 required attribute (HTML5), 296 require_once statement (PHP), 112, 243, 270 reset function (PHP), 144 resource sites, 659–662 restore method (canvas), 562 restoring MySQL databases, 235–240 return statement in JavaScript, 364 in PHP, 106 returning values about, 106–108, 365–367 arrays and, 108, 367 read more..

  • Page - 724

    self keyword (PHP), 123, 127 semicolon (;) CSS usage, 426 JavaScript syntax and, 324, 329 MySQL command-line interface and, 177 PHP syntax, 49 $_SERVER variable (PHP), 70, 306 $_SESSION variable (PHP), 70, 312–315 sessions about, 312 cookie-only, 319 ending, 315 preventing session fixation, 318–319 preventing session hijacking, 317 security considerations, 317–320 setting timeouts, 317 shared read more..

  • Page - 725

    MySQL string functions, 667–670 in PHP concatenating strings, 58, 76 converting string case, 105 converting strings to numbers, 63 escape characters, 59 multiple-line commands and, 60 padding strings, 150 string types supported, 59 string variables, 50 strings as operators, 76, 78 stroke method (canvas), 537 strokeRect method (canvas), 522 strokeText method (canvas), 530 strrev function (PHP), read more..

  • Page - 726

    text-indent property (CSS), 446 text-overflow property (CSS3), 478 text-shadow property (CSS3), 477 text-transform property (CSS), 446 textAlign property (canvas), 531 <textarea> tag about, 284 autofocus attribute, 295 textBaseline property (canvas), 531 textDecoration property (JavaScript), 492 Theora (video) codec, 576 Third Normal Form, 224–226 third-party cookies, 301 this keyword (JavaScript), 497 read more..

  • Page - 727

    user agent string, 318 user styles (CSS), 428 users and usernames creating users in MySQL, 179 Gmail example, 12–14 HTTP authentication and, 304–307 social networking site example, 611 storing, 307 validating on forms, 385 V validation form data using PHP, 165–167 form data with JavaScript, 381–387 redisplaying forms after, 397–402 value attribute (forms), 283, 290 var keyword read more..

  • Page - 728

    pageXOffset property, 495 pageYOffset property, 496 parent property, 496 screen property, 496 screenLeft property, 496 screenTop property, 496 screenX property, 496 screenY property, 496 self property, 496 status property, 496 top property, 496 Windows operating systems accessing MySQL, 173 calling up command prompt, 173 dir system command, 167 installing WAMPs on, 16–31 with statement (JavaScript), read more..

  • Page - 729

    About the Author Robin Nixon has worked with and written about computers since the early 1980s (his first computer was a Tandy TRS 80 Model 1 with a massive 4KB of RAM!). One of the websites he developed presented the world’s first radio station licensed by the music copyright holders. In order to enable people to continue to surf while listening, Robin also developed read more..

Write Your Review