PHP & MySQL: The Missing Manual, Second Edition My SQL (The Manual 2nd Edition) Brett Mc Laughin O'Reilly
User Manual:
Open the PDF directly: View PDF .
Page Count: 548
Download | |
Open PDF In Browser | View PDF |
PHP & MySQL Second Edition The book that should have been in the box® Brett McLaughlin Beijing | Cambridge | Farnham | Köln | Sebastopol | Tokyo PHP & MySQL: The Missing Manual, Second Edition by Brett McLaughlin Copyright © 2013 Brett McLaughlin. 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 titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. November 2011: November 2012: First Edition. Second Edition. Revision History for the Second Edition: 2012-11-5 First release See http://oreilly.com/catalog/errata.csp?isbn=0636920024927 for release details. The Missing Manual is a registered trademark of O’Reilly Media, Inc. The Missing Manual logo, and “The book that should have been in the box” are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media is aware of a trademark claim, the designations are capitalized. While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions, or for damages resulting from the use of the information contained in it. [LSI] ISBN: 978-1-449-32557-2 Contents The Missing Credits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Part One: Chapter 1: PHP and MySQL Basics PHP: What, Why, and Where?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 PHP Comes in Two Flavors: Local and Remote. . . . . . . . . . . . . . . . . . . . . . . . . 15 PHP: Going Local . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Write Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Run Your First Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 But Where’s That Web Server?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Chapter2: PHP Meets HTML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Script or HTML?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 PHP Talks Back. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Run PHP Scripts Remotely. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Chapter 3: PHP Syntax: Weird and Wonderful. . . . . . . . . . . . . . . . . . . . . . . . . 61 Get Information from a Web Form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Working with Text in PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 The $_REQUEST Variable Is an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 What Do You Do with User Information?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Chapter 4: MySQL and SQL: Database and Language. . . . . . . . . . . . . . . . . 91 What Is a Database?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Installing MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 SQL Is a Language for Talking to Databases. . . . . . . . . . . . . . . . . . . . . . . . . . 104 Part Two: Dynamic Web Pages Chapter 5: Connecting PHP to MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Writing a Simple PHP Connection Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Cleaning Up Your Code with Multiple Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Building a Basic SQL Query Runner. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 iii Chapter 6: Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 String Matching, Double-Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Chapter 7: Generating Dynamic Web Pages. . . . . . . . . . . . . . . . . . . . . . . . . . 173 Revisiting a User’s Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Planning Your Database Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Saving a User’s Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Show Me the User. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 Revisiting (and Redirecting) the Create User Script . . . . . . . . . . . . . . . . . . . 208 Part Three: Chapter 8: From Web Pages to Web Applications When Things Go Wrong (and They Will). . . . . . . . . . . . . . . . . . 221 Planning Your Error Pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Finding a Middle Ground for Error Pages with PHP. . . . . . . . . . . . . . . . . . . . 229 Add Debugging to Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Redirecting On Error. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Chapter 9: Handling Images and Complexity. . . . . . . . . . . . . . . . . . . . . . . . . 253 Images Are Just Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Images Are for Viewing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 And Now for Something Completely Different. . . . . . . . . . . . . . . . . . . . . . . . 288 Chapter 10: Binary Objects and Image Loading. . . . . . . . . . . . . . . . . . . . . . . 289 Storing Different Objects in Different Tables . . . . . . . . . . . . . . . . . . . . . . . . . 290 Inserting a Raw Image into a Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 Your Binary Data Isn’t Safe to Insert...Yet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 Connecting Users and Images. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Show Me the Image!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 Embedding an Image Is Just Viewing an Image. . . . . . . . . . . . . . . . . . . . . . .324 So, Which Approach Is Best?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Chapter 11: Listing, Iterating, and Administrating.. . . . . . . . . . . . . . . . . . . . 333 Thinking about What You Need as an Admin. . . . . . . . . . . . . . . . . . . . . . . . . 334 Listing All Your Users. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 Deleting a User. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 Talking Back to Your Users. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Standardizing on Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Integrating Utilities, Views, and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 iv Contents Part Four: Security and the Real World Chapter 12: Authentication and Authorization. . . . . . . . . . . . . . . . . . . . . . . . 385 Basic Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 Abstracting What’s the Same . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 Passwords Don’t Belong in PHP Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 Passwords Create Security, But Should Be Secure. . . . . . . . . . . . . . . . . . . . . 413 Chapter 13: Cookies, Sign-Ins, and Ditching Crummy Pop-Ups. . . . . . . . 419 Moving Beyond Basic Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 Logging In with Cookies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 Adding Context-Specific Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Chapter 14: Authorization and Sessions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 Modeling Groups in Your Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 Checking for Group Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461 Group-Specific Menus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 Entering Browser Sessions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475 Memory Lane: Remember That Phishing Problem?. . . . . . . . . . . . . . . . . . . . 486 Why Would You Ever Use Cookies? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 Part Five: Appendixes Appendix A: Installing PHP on Windows Without WAMP. . . . . . . . . . . . . . . 493 Appendix B: Installing MySQL Without MAMP or WAMP. . . . . . . . . . . . . . . 499 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 Contents v The Missing Credits About the Author Brett McLaughlin is a senior-level technologist and strategist, active especially in web programming and data-driven, customer-facing systems. Rarely focused on only one component of a system, he architects, designs, manages, and implements largescale applications from start to finish with mission-critical implementations and deadlines. Of course, that’s all fancy-talk for saying that Brett’s a geek, spending most of his day in front of a computer with his hands flying across a keyboard. Currently, he spends most of his time working on NASA projects, which sounds much cooler than it actually is. But hey, maybe that satellite overhead really is controlled by PHP and MySQL... About the Creative Team Nan Barber (editor) has been working on the Missing Manual series since its inception. She lives in Boston with her husband and various electronic devices. Email: nanbarber@oreilly.com. Holly Bauer (production editor) lives in Ye Olde Cambridge, Massachusetts, where she is an avid home cook, prolific DIYer, and mid-century modern furniture design enthusiast. Email: holly@oreilly.com. Bob Russell (copyeditor) is a documentation specialist and President of Octal Publishing, Inc., in Salem, New Hampshire (www.octalpub.com). Email: bob.russell@ octalpub.com. Bob Pfahler (indexer) is a freelance indexer. For the past five years, he has indexed many computer books as well as biographies, history, and business books. When he is not working, he likes to take bike rides in the foothills outside of Denver. He indexed this book as an associate for Potomac Indexing (www.potomacindexing.com). Roger House (technical reviewer) is a freelance software developer living in northern California. He has written code in many languages for various kinds of applications. He enjoys algorithm design, use of data structures, and applications of mathematics. Web: www.rogerfhouse.com. Email: rhouse@sonic.net. Steve Suehring (technical reviewer) is a technical architect with an extensive background finding simple solutions to complex problems. Steve plays several musical instruments (not at the same time) and can be reached through his website www .braingia.org. vii Acknowledgments Acknowledgments are nearly impossible to do well. Before you can thank anyone of substance, the music swells and they’re shuffling you off stage. Seriously, apart from the writing, there’s my wife, Leigh, and my kids, Dean, Robbie, and Addie. Any energy or joy or relaxation that happens during the long writing process filters through those four, and there are never enough royalties to cover the time lost with them. I suppose it’s a reflection of their love and support for me that they’re OK with me writing anyway. There’s certainly the writing. Brian Sawyer was the first guy to call me when I became available to write, and he called when I was really in need of just what he gave me: excitement about me writing and encouragement that I could write for the Missing Manual series. I won’t forget that call anytime soon. And, there’s Nan Barber, who IM’ed and emailed me throughout the entire process. She showed a really unhealthy level of trust that wasn’t earned, and I’m quite thankful...especially in the dark days of early August, when I had hundreds of pages left to write, in just a few short weeks. Roger House and Steve Suehring, my technical reviewers, were both picky and gentle. That’s about all you can ask. And Steve filled out my PHP holes. He caught one particularly nasty issue that I think vastly improved the book. You don’t realize this, but you owe him a real debt of thanks if this book helps you. ——Brett McLaughlin The Missing Manual Series Missing Manuals are witty, superbly written guides to computer products that don’t come with printed manuals (which is just about all of them). Each book features a handcrafted index and cross-references to specific pages (not just chapters). Recent and upcoming titles include: Access 2010: The Missing Manual by Matthew MacDonald Adobe Edge Animate: The Missing Manual by Chris Grover Buying a Home: The Missing Manual by Nancy Conner CSS3: The Missing Manual, Third Edition, by David Sawyer McFarland Creating a Website: The Missing Manual, Third Edition, by Matthew MacDonald David Pogue’s Digital Photography: The Missing Manual by David Pogue Dreamweaver CS5.5: The Missing Manual by David Sawyer McFarland Droid 2: The Missing Manual by Preston Gralla Droid X2: The Missing Manual by Preston Gralla Excel 2010: The Missing Manual by Matthew MacDonald Facebook: The Missing Manual, Third Edition by E.A. Vander Veer viii The Missing Credits FileMaker Pro 12: The Missing Manual by Susan Prosser and Stuart Gripman Flash CS5.5: The Missing Manual by Chris Grover Galaxy S II: The Missing Manual by Preston Gralla Galaxy Tab: The Missing Manual by Preston Gralla Google Apps: The Missing Manual by Nancy Conner Google SketchUp: The Missing Manual by Chris Grover HTML5: The Missing Manual by Matthew MacDonald iMovie ’11 & iDVD: The Missing Manual by David Pogue and Aaron Miller iPad: The Missing Manual, Fifth Edition by J.D. Biersdorfer iPhone: The Missing Manual, Sixth Edition by David Pogue iPhone App Development: The Missing Manual by Craig Hockenberry iPhoto ’11: The Missing Manual by David Pogue and Lesa Snider iPod: The Missing Manual, Eleventh Edition by J.D. Biersdorfer and David Pogue JavaScript & jQuery: The Missing Manual by David Sawyer McFarland Kindle Fire: The Missing Manual, Second Edition by Peter Meyers Living Green: The Missing Manual by Nancy Conner Mac OS X Snow Leopard: The Missing Manual by David Pogue Mac OS X Lion: The Missing Manual by David Pogue Microsoft Project 2010: The Missing Manual by Bonnie Biafore Motorola Xoom: The Missing Manual by Preston Gralla Netbooks: The Missing Manual by J.D. Biersdorfer NOOK Tablet: The Missing Manual by Preston Gralla Office 2010: The Missing Manual by Nancy Connor, Chris Grover, and Matthew MacDonald Office 2011 for Macintosh: The Missing Manual by Chris Grover Palm Pre: The Missing Manual by Ed Baig Personal Investing: The Missing Manual by Bonnie Biafore Photoshop CS6: The Missing Manual by Lesa Snider Photoshop Elements 11: The Missing Manual by Barbara Brundage PowerPoint 2007: The Missing Manual by E.A. Vander Veer Premiere Elements 8: The Missing Manual by Chris Grover The Missing Credits ix QuickBase: The Missing Manual by Nancy Conner QuickBooks 2013: The Missing Manual by Bonnie Biafore Quicken 2009: The Missing Manual by Bonnie Biafore Switching to the Mac: The Missing Manual, Snow Leopard Edition by David Pogue Switching to the Mac: The Missing Manual, Lion Edition by David Pogue Wikipedia: The Missing Manual by John Broughton Windows Vista: The Missing Manual by David Pogue Windows 7: The Missing Manual by David Pogue Windows 8: The Missing Manual by David Pogue Word 2007: The Missing Manual by Chris Grover WordPress: The Missing Manual by Matthew MacDonald Your Body: The Missing Manual by Matthew MacDonald Your Brain: The Missing Manual by Matthew MacDonald Your Money: The Missing Manual by J.D. Roth x The Missing Credits Introduction G iven that you’re reading this book, the chances are good that you’ve built a web page in HTML. You’ve styled it by using Cascading Style Sheets (CSS) and maybe written a little JavaScript to validate your custom-built web forms. If that wasn’t enough, you’ve learned a lot more JavaScript, threw in some jQuery, and constructed a whole lot of web pages. Maybe you’ve even moved your JavaScript into external files, shared your CSS across your entire site, and validated your HTML with the latest standards. But now you want more. Perhaps you’ve become frustrated with your website’s inability to store user information in anything beyond cookies. Maybe you want a full-blown online store, complete with PayPal integration and details about what items are in stock. Or maybe you’ve simply caught the programming bug and want to go beyond what HTML, CSS, and JavaScript can easily give you. If any of these are the case—and you may find that all of these are the case—learning PHP and MySQL is a great way to take a giant programming step forward. Even if you’ve never heard of PHP, you’ll find it’s the best way to go from building web pages to creating full-fledged web applications that store all sorts of information in databases. This book shows you how to do just that. 1 What PHP and MySQL Can Do What PHP and MySQL Can Do PHP can handle payment processing on its own, and it can connect with services like PayPal and Google Checkout. PHP can store and load images from a database or a file system and give you the ability to log users in and out as well as control what they see throughout your application. Add in MySQL, and you can store your users’ names, addresses, billing data, and even their preferences regarding the color of their own personal landing page. MySQL can store just a few bits of data, a few thousand lines of data, or every page access by every user who ever logs into your application. And, of course, PHP can easily connect to MySQL. PHP can do everything from grabbing a user name based on a user ID to storing the details about financial transactions to actually creating tables and updating their structures, and MySQL can back-end all that work and store that data. Ultimately, this is the stuff of web applications; it’s what a web application is. Obviously, web applications like this aren’t simple. They have a lot of complexity, and that complexity has to be managed and ultimately tamed into a usable, sensible web application that you can maintain and your users can enjoy. That’s what this book is about: building web applications, and doing it with an understanding of what you’re doing, and why you’re doing it. What Is PHP? PHP started out as a set of tools for doing simple web-related tasks. It appeared on the Web scene way back in 1994. Initially, PHP did nothing more than just track visits to a particular web page (the online resume of Rasmus Lerdorf—the inventor of PHP). It was then expanded to interact with databases, as well as provide a tool set for online guest books and HTML form processing. The next thing you know, it was hugely popular as an alternative to less web-friendly languages like C. New versions of PHP started coming out, and an increasing number of web programmers adopted it as their scripting language of choice for web tasks. PHP 3, 4, and now 5 are now mainstays on the Web. PHP has become fast while remaining lightweight. And, of course, its ability to easily interact with databases such as MySQL remains one of its most attractive features. What Is PHP Like? PHP is a programming language. It’s like JavaScript in that you spend most of your time dealing with values and making decisions about which path through your code should be followed at any given time. But it’s like HTML in that you deal with output—tags that your users view through the lens of their web browsers. In fact, PHP in the context of web programming is a bit of a mutt; it does lots of things pretty well, rather than just doing one single thing. (And, if you’ve ever wondered why it’s called PHP, see the box on the following page.) 2 PHP & MySQL: The Missing Manual What Is PHP? FREQUENTLY ASKED QUESTION Personal Home Page, Indeed What does PHP stand for? PHP is an acronym. Originally, it stood for Personal Home Page Construction Kit , because lots of programmers used it to build their websites, going much further than what was possible with HTML, CSS, and JavaScript. But in the last few years, “personal home page” tends to sound more like something that happens on one of those really cheap hosting sites, rather than a highpowered programming language. So now, PHP stands for PHP: Hypertext Preprocessor. If that sounds geeky, it is. In fact, it’s a bit of a programmer joke: PHP stands for something that actually contains PHP within itself. That makes it a recursive acronym, meaning that it references itself. You don’t have to know what a recursive acronym is; that won’t be on the quiz. Just be warned that PHP’s recursive acronym won’t be the last weird and slightly funny thing you’ll run across in the PHP language. PHP Is All About the Web If you came here for web programming, you’re in the right place. Although you can write PHP programs that run from a command line (check out Figure I-1 for an example), that’s not really where it excels. The PHP programs you write run within your website, part and parcel with your HTML forms, web sessions, and browser cookies. For example, PHP is great at integrating with your website’s existing authentication system, or letting you create one of your own. Figure I-1 Sure, you can run PHP programs from a Terminal window or a command shell in Windows. But most of the time, you won’t. PHP is perfectly suited to the Web, and that’s where you’ll spend most of your time. You’ll spend a lot of time not just handing off control to an HTML page, but actually writing the HTML you’re already familiar with right into your PHP scripts. Lots of times, you’ll actually write some PHP and then write some HTML, all in the same PHP file, as in the following example:PHP & MySQL: The Missing Manual
User Profile
Get in touch with : p>
This script references another script, database_connection.php, and then extracts a user’s ID from the request parameters sent by a web browser. The script uses that ID to search a database for the rest of the user’s information. Then, it builds the data into a web page that’s created on the fly. The result? Pages that are both full of HTML and have dynamic content, like Figure I-2. Figure I-2 This page is as much PHP as HTML. It looks up your visitor’s name in the database and displays it dynamically. The menu creates a Show Profile option specific to this user. But there’s still lots and lots of HTML. This is PHP at its best: combining the HTML (and even JavaScript) that you know with the PHP you’re about to learn. 4 PHP & MySQL: The Missing Manual JavaScript Is Loose, PHP Is…Less So If you’ve written some JavaScript—and if you’re checking out this book, that’s probably the case—you know that JavaScript lets you get away with just about anything. You can occasionally leave out semicolons; you can use brackets, or not; you can use the var keyword, or not. That sort of looseness is great for getting things working quickly, but at the same time, it’s frustrating. It makes finding bugs tricky at times, and working across browsers can be a nightmare. What Is PHP? PHP is not quite as loose as JavaScript, so it makes you learn a little more structure and tighten up your understanding of what’s going on as your program is constructed and then run. That’s a good thing, because it will end up making you tighten up your JavaScript skills, too. And, perhaps best of all, PHP’s stodgy consistency makes it easier to learn. It gives you firm rules to hang on to, rather than lots of “You can do this…or this…or this…” So get ready. There is a lot to learn, but everything you learn gives you something on which to build. And PHP, lets you know right away when there’s a problem. You won’t need to pop open an error console or keep an eye out for the tiny yellow warning triangle in Internet Explorer as you do with JavaScript. More often, you’ll get a nasty error that stops you in your tracks and screams, “Fix me!” And, over the next couple of hundred pages, you’ll be able to do just that: fix the problems you’ll run across in typical PHP programs, whether you’ve written those programs or someone else has. PHP Is Interpreted PHP code comes in the form of scripts, which are plain-text files that you create and fill with code. Whereas HTML uses lots of angle brackets and keywords like html, head, and ul, PHP uses lots of dollar signs ($) and keywords like mysql_query and echo. So, HTML and PHP don’t look at all alike. But where they are alike is in the basic underlying format: they’re both just text. You can open up an HTML document not just in a web browser, but in Notepad or an integrated development environment (IDE) like Eclipse or even a command-line editor like vi or emacs. The same is true for PHP: it’s just text. So, get ready; throughout this book, you’ll be typing words—albeit strange ones, with lots of underscores—and saving those words into text files called scripts. Once you’ve got a script, you let a PHP program interpret that script. The PHP interpreter is a piece of software on your web server that reads your script and makes sense of it, giving the web server output and directions about where to go next or how to handle a user’s form field entries. Your script—remember, just a text file—is interpreted, one line at a time, every time it is accessed. This is a bit different from languages like Java or C++, which are compiled. In those languages, you also write your code in text files, but then run a command that turns those text files into something else: class files, binary files, pieces of unreadable code that your computer uses. Introduction 5 What Is PHP? The beauty of an interpreted language like PHP—and JavaScript, for that matter—is that you write your code and go. You don’t need a bunch of tools or subsequent steps. You write PHP, test it out in the browser, and then write some more. It’s fast, and that usually means it’s pretty fun. PHP Doesn’t Run in the Browser There’s one other big difference between PHP and what you may be used to with HTML, CSS, and JavaScript. It’s a big difference, too; in fact, this difference is such a big deal that it’s going to affect everything you do when it comes to writing PHP scripts, getting those PHP scripts to run, and checking them out in a web browser. So what’s the difference? It’s this: PHP, unlike HTML or CSS or JavaScript, doesn’t run entirely in a browser. What does that mean? Chapter 1 begins to get into the details, but for now, you just need to know that HTML, JavaScript, and CSS are entirely handled by your web browser software. Whether you use Internet Explorer, Apple Safari, Google Chrome, Mozilla Firefox, or Opera, once you have a browser, you have everything you need. That’s why you can write an HTML document, save it with an extension like .html, double-click that file, and voilà: your browser opens (assuming you’ve got things set up on your computer the right way) and you’re looking at HTML. You can reference CSS in that HTML file as well as JavaScript, and the same thing happens. Write code, save, and open. Pretty easy stuff. With PHP, you’ll need a bit more than that. The PHP interpreter interacts with your browser but doesn’t run in the browser automatically. In other words, you cannot simply double-click a PHP script and expect a browser to pop up and handle things. HTML forms that submit to a PHP script won’t “just work” the way that HTML and JavaScript do. Right now, then, you just need to know two things: • It’s going to take a little more work to get your PHP programs working. You can’t just write and save a script and then open it the way you can HTML. Don’t worry; you’ll learn exactly how to get PHP working both locally—on your computer—and remotely—on a web hosting company’s servers. But it’s going to take a little more effort. • It’s not trivial to set up everything you need to run PHP programs on your own computer—especially once you involve MySQL, too (more on this in just a moment). That’s why Internet Service Providers (ISPs) and web hosting companies exist! They take care of that sort of thing. So, although it’s possible to do all your PHP coding on your own machine, it’s a lot more common to write your scripts and then send them to a remote web server. Sound scary? It’s not…but it’s important. You’ll spend a good bit of time in this book writing code and uploading it to a server. 6 PHP & MySQL: The Missing Manual PHP is different from JavaScript and HTML in some important ways. You’ll get used to those differences, but you’ll be a lot less frustrated and confused if you go in knowing that you’ll have to do some things differently when it comes to PHP. About This Book What Is MySQL? MySQL is a database. It stores your information, your users’ information, and anything else you want to stuff into it. But, beyond its ability to store information, MySQL is popular. In fact, it’s the most popular open-source database system in the world. It has literally millions of users working with it, finding and reporting problems, and testing its limits. And, it has thousands of developers that at some point have helped improved its code base. MySQL is essentially a warehouse in which you can store things to be looked up later. Not only that, MySQL provides you with a really fast mechanism to find all that stuff you stuck in the warehouse whenever it’s needed. By the time you’re through this book, you’ll love MySQL. It will do work that you could never do on your own, and it will do that work tirelessly and quickly. It’s also the perfect companion to PHP. It’s easy to install on any system; it doesn’t take up huge resources like larger commercial offerings such as Oracle’s or IBM’s products; and its easy to connect to. In fact, you’ll find that PHP and MySQL are perfectly matched, with a ton of easy-to-use functions that let PHP scripts to do just about anything you can imagine with a MySQL database. Note There’s actually a lot more nuance to MySQL—and SQL, the language in which you’ll interact with MySQL—but it’s better to save that for Chapter 4, when you’ve got a little PHP under your belt. About This Book PHP is a web-based language, not a program that comes in a box. Tens of thousands (maybe even hundreds of thousands) of websites have bits of PHP tutorial or instruction on them. That’s great, right? Well, not so much. Those websites aren’t all current. Some are full of bugs. Some have more information in the comment trails—scattered amongst gripes, complaints, and lambasting from other programmers—as they do in the main page. It’s no easy matter to find what you’re looking for. The purpose of this book, therefore, is to serve as the manual that should have been included when you download PHP. It’s the missing PDF, if you will (or maybe the missing eBook, if you’re a Kindle or Nook or iPad person). In this book’s pages, you’ll find step-by-step instructions for getting PHP running, writing your first program… and your second program…and eventually building a web application from scratch. In addition, you’ll find clear evaluations of the absolutely critical parts of PHP that you’ll use every day, whether you’re building a personal blog or a corporate intranet. Introduction 7 About This Book Note This book periodically recommends other books, covering topics that are too specialized or tangential for a manual about PHP and MySQL. Careful readers may notice that not every one of these titles is published by Missing Manual parent company O’Reilly Media. If there’s a great book out there that doesn’t happen to be published by O’Reilly, this book will still let you know about it. PHP & MySQL: The Missing Manual is designed to accommodate readers at every technical level. The primary discussions are written for advanced-beginner or intermediate web authors and programmers. Hopefully, you’re comfortable with HTML and CSS, and maybe even know a bit of JavaScript. But, if you’re new to all this Web stuff, take heart: special boxes called “Up to Speed” provide the introductory information you need to understand the topic at hand. If you’re an advanced user, on the other hand, keep your eye out for similar boxes called “Power Users’ Clinic.” They offer more technical tips, tricks, and shortcuts for the experienced computer fan. Macintosh and Windows PHP and MySQL work almost precisely the same in their Macintosh and Windows versions. Even more important, you’ll do most of your work by uploading your scripts and running your database code against a web server. That means that your hosting provider has to deal with operating system issues; you get to focus on your code and information. In the first few chapters, you get your system set up to write code and deal with PHP scripts. Thereafter, you will soon forget about whether you’re on a Macintosh or using a Windows-based computer. You’ll just be writing code, the same way you write HTML and CSS. And remember, you’ll soon be uploading your scripts to remote web servers, so your own computer is only part of the solution. FTP: It’s Critical One piece of software that’s absolutely critical is a good FTP client. No matter how awesome your scripting skills become—and they’re gonna be formidable!—you have to actually get your scripts to your web hosting server. That’s where FTP comes in: it’s the means by which a file on your computer gets placed in just the right location on a remote server. Note From the author: Typing in a command-line editor is actually exactly how I work. But then, I’m a dinosaur, a throwback to days when you had to watch commercials to see primetime TV, and you’d miss emails because your pocket didn’t buzz every time your boss whisked you a command through the ether. Today, for most of you, a good text editor and a good graphical FTP client are much better choices. Seriously, my addiction owns me, and I so badly want to :wq! it. Chapter 1 points you to several great editors, and the fancier ones will have FTP built right in. If you don’t opt for an integrated solution, a dedicated FTP program like Cyberduck (www.cyberduck.ch) is great, too. You can write a script, throw it online, and test it all with a few mouse clicks. So, go ahead and get that FTP program downloaded, configured for your web hosting service (which might also be called your ISP), and fired up. You’re gonna need it. 8 PHP & MySQL: The Missing Manual About the Outline PHP & MySQL: The Missing Manual is divided into five parts, each containing several chapters: About the Online Resources • Part 1: PHP and MySQL Basics. In the first four chapters, you install PHP, get it running on your computer, write your first few PHP programs, and learn to do a few basic things like collect user information via a web form and work with text. You also install MySQL and become thoroughly acquainted with the structure of a database. • Part 2: Dynamic Web Pages. These are the chapters in which you start to build the basics of a solid web application. You add a table in which you can store users and their information, and get a grasp of how easily you can manipulate text. From URLs and emails to Twitter handles, you use regular expressions and string handling to bend letters, numbers, and slashes to your will. • Part 3: From Web Pages to Web Applications. With a solid foundation, you’re ready to connect your web pages into a more cohesive unit. You add custom error handling so that your users won’t become confused when things go wrong. You also add your own debugging to help you find problems. You also learn how to store references to users’ images of themselves, store the images themselves in a database, and learn which approach is best in which situations. • Part 4: Security and the Real World. In even the simplest of applications, logging in and logging out is critical. In this section, you build an authentication system and then deal with passwords (which are important, but a bit of a pain). You then work with cookies and sessions, and use both to create a group-based authorization system for your web application. • Part 5: Appendixes. Although the first several chapters show you how to get PHP and MySQL onto your own Macintosh or Windows-based computer the easy way, using the WampServer software package or the Mac’s built-in installation, the two appendixes in this section show you how to install the software manually for full control of all the details. At the Missing Manual website (www.missingmanuals.com/cds/phpmysqlmm2e), you can find every single code example, from every chapter, in the state it is shown for that chapter. About the Online Resources As the owner of a Missing Manual, you’ve got more than just a book to read. Online, you can find example files so that you can get some hands-on experience, as well as tips, articles, and maybe even a video or two. You can also communicate with the Missing Manual team and tell us what you love (or hate) about the book. Head over to www.missingmanuals.com, or go directly to one of the following sections. Introduction 9 About the Online Resources Missing CD This book doesn’t have a CD pasted inside the back cover, but you’re not missing out on anything. Go to www.missingmanuals.com/cds/phpmysqlmm2e to download code samples, code samples, and also, some code samples. Yup, there are a lot of them. Every chapter has a section of code for that chapter. And, you don’t just get completed versions of the book’s scripts: You get a version that matches up with each chapter, so you’ll never get too confused about exactly how your version of a script or web page should look. And so you don’t wear down your fingers typing long web addresses, the Missing CD page also offers a list of links that you can click to bring you to the websites mentioned in this book. Registration If you register this book at Oreilly.com (http://oreilly.com), you’ll be eligible for special offers—like discounts on future editions of PHP & MySQL: The Missing Manual. Registering takes only a few clicks. To get started, type www.oreilly.com/register into your browser to hop directly to the Registration page. Feedback Got questions? Need more information? Fancy yourself a book reviewer? On the Feedback page, you can get expert answers to questions that come to you while reading, share your thoughts on this Missing Manual, and find groups for folks who share your interest in PHP, MySQL, and web applications in general. To have your say, go to www.missingmanuals.com/feedback. Errata In an effort to keep this book as up-to-date and accurate as possible, each time we print more copies, we’ll make any confirmed corrections you’ve suggested. We also note such changes on the book’s website, so you can mark important corrections into your own copy of the book, if you like. Go to http://tinyurl.com/phpmysql2e-mm to report an error and view existing corrections. 10 PHP & MySQL: The Missing Manual Safari® Books Online Safari® Books Online Safari® Books Online is an on-demand digital library that lets you easily search over 24,000 technology and creative reference books and videos to find the answers you need quickly. With a subscription, you can read any page and watch any video from the library online. You can read books on your cell phone and mobile devices; access new titles before they are available for print; and get exclusive access to manuscripts in development and post feedback for the authors. You can copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features. O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com. Introduction 11 Part PHP and MySQL Basics Chapter 1: PHP: What, Why, and Where? Chapter 2: PHP Meets HTML Chapter 3: PHP Syntax: Weird and Wonderful Chapter 4: MySQL and SQL: Database and Language 1 chapter 1 PHP: What, Why, and Where? P HP is ultimately just text that is taken by your web server and turned into a set of commands and information for your web browser. And because you’re just working in text, there’s not a lot you have to do to get going as a PHP programmer. You need to become familiar with PHP itself, and the best way to do that is to install PHP on your own computer as well as becoming familiar with how PHP runs on a remote web server. Then, you need to run an actual script. Don’t worry; it’s amazingly easy to write your first program in PHP. Not only that, you’ll run your script, upload it to your web server, and access your script with a web browser…and that’s all in the first two chapters! Throughout the process, you’ll begin taking control. With PHP, you become an active participant in your web pages. PHP lets you listen carefully to your users and say something back. So get going; there’s no reason to leave your users with passive HTML pages any longer. PHP Comes in Two Flavors: Local and Remote One of the most difficult things to get a handle on when it comes to PHP programming doesn’t have much to do with programming at all. It’s figuring out just how PHP runs, how it interacts with your web browser and web server, and why it’s not possible to just double-click a PHP file on your hard drive and see the script in that file run. 15 PHP Comes in Two Flavors: Local and Remote HTML and CSS Run Within a Web Browser First, it’s worth thinking back to when you were a wee programmer, writing your first HTML page. You could save that page in a file, name that file with a .html extension, and boom—you had a web page. Double-click that file, and on most computers, you see that page open up in a web browser. That’s because just as a .doc file is connected to the Microsoft Word program, a .html file is connected to a web browser (specifically, the browser you’ve chosen as the default on your computer). Figure 1-1 should give you an idea. Figure 1-1 Web Browser Web browsers know all they need to know in order to load and display an HTML page. No extra software or configuration is necessary. HTML renderer HTML Files If you keep thinking back, you probably added some styling to your HTML pages. Using the style attribute and tags in your HTML document, you could change fonts, add striping to your table rows, and generally spice up otherwise boring text. Then, at some point, some well-meaning web designer slapped your hand and insisted that you start writing all your CSS in external style sheets, and referencing those files in the head of your HTML, like this: You might even have a few style sheets for the benefit of people viewing your website on mobile devices or printing out a page: But you can still double-click that HTML file, and your browser knows what to do (see Figure 1-2). That’s because, once again, the web browser is completely capable of not just rendering HTML, but applying all those CSS styles to the page, too. Again, no extra software needed. 16 PHP & MySQL: The Missing Manual At this point, even though you’re using only two technologies—HTML and CSS—you need only a single program to handle those technologies: the web browser. PHP Comes in Two Flavors: Local and Remote HTML Files Figure 1-2 HTML renderer As was the case with HTML, web browsers don’t need any extra help or plug-ins to turn your textual CSS descriptions into styles and apply those styles to your HTML elements. CSS renderer body{ ... } Web Browser CSS Files JavaScript Adds Complexity, but Not Software Next up in the pantheon of web technologies that every designer and fledgling programmer needs to learn: JavaScript. Suddenly, you weren’t limited to elements that never moved and text that never changed. Whether it was simple phone number validation, more advanced jQuery functions that turned boring gray boxes into animated buttons and
elements into tabs, or even the new HTML5 canvas object, within which you could build entire JavaScript-based 3D games, your pages suddenly had new life with JavaScript. But just as with HTML and CSS, JavaScript is at heart a web technology, and even more specifically, a browser-based technology. In other words, support for JavaScript is part and parcel of your web browser. In fact, if a new version of JavaScript were to appear—something that rarely happens these days—you’d need to download a new version of your browser to get that version of JavaScript. Just as you can’t upgrade your HTML installation outside of your browser, you can’t upgrade your JavaScript installation outside of your browser. Chapter 1: PHP: What, Why, and Where? 17 PHP Comes in Two Flavors: Local and Remote UNDER THE HOOD You Probably Have Multiple Versions of JavaScript Already! Think about it: if JavaScript is built in to your browser, and you have more than one browser, you actually have multiple installations of JavaScript on your computer. Suppose that you have Internet Explorer and Firefox; you’ve got the JavaScript installation that came with Internet Explorer and the one that came with Firefox. Add Chrome or Opera to the mix, and you’ve got a few more installations. And, if you have multiple versions of a single browser—like Firefox 3.6.3 for testing with older Linux-based systems and the most current version (14 something-or-other as of late), they each have a different JavaScript installation. Even though JavaScript doesn’t get updated very often, those multiple installations usually translate into multiple versions of JavaScript, because JavaScript isn’t a product that is distributed by a central organization to browser developers. Rather, it’s a specification: a document that defines how things should work to be considered as JavaScript. That means that each browser has to write code that matches that specification so that they can say, “Yes, you can run JavaScript in our browser!” Furthermore, each browser does things a bit differently, and that’s why a website feature that works perfectly in Firefox might not quite work perfectly in Internet Explorer, and vice versa. So, even if you have two browsers that implement the same version of the JavaScript specification, the code in that implementation isn’t identical; there are usually differences. What does all this mean to you? Test your code—JavaScript, PHP, or otherwise—in as many browsers as you can. Things aren’t always the same in every browser, and it’s up to you—not your users—to handle inconsistencies. Figure 1-3 shows you how JavaScript fits in (hint: just as HTML and CSS do). HTML Files Figure 1-3 HTML renderer The web browser can handle your JavaScript, too. That browser is doing a lot behind the scenes. CSS renderer body{ ... } Web Browser JavaScript interpreter function{ } JavaScript Files 18 PHP & MySQL: The Missing Manual CSS Files Note The code that handles your HTML and CSS isn’t quite as disconnected as it might appear from Figure 1-2 and Figure 1-3. In other words, there are no individual components in your web browser that render HTML or CSS. But you get the idea; your browser can handle all these different tasks and technologies and turn them into a web page. PHP Comes in Two Flavors: Local and Remote PHP Is Not Part of Your Browser And here’s where things change from the easy, browser-centric view of the world. When you download a web browser, you get HTML, CSS, and JavaScript, but you do not get PHP. PHP scripts—which you’ll soon be writing—have to be interpreted by the PHP interpreter program, called php. And, you can’t just add a PHP interpreter to your browser. It doesn’t know what to do with scripts and isn’t built to interpret PHP. Instead, you need PHP on a web server. It’s the web server—not the web browser— that can interact with a PHP interpreter. Your browser can handle HTML on its own, but it has to make a request to a web server to deal with PHP scripts. That server can take your PHP scripts and run them, and then take the response and send it back to your browser. Your browser can then understand and handle the response. So, Figure 1-4 adds a couple of new wrinkles: the PHP interpreter, the magical thing that takes the PHP scripts you’ll be writing and does something useful with them; and a web server to communicate with that interpreter. These both live outside of your web browser. In this scenario, the browser now makes a request to the server and then takes the response and shows it to you. Could be for HTML, CSS, PHP or a combination. Figure 1-4 HTML Web Browser HTML renderer CSS Request CSS renderer JavaScript interpreter Response Web Server PHP interpreter JavaScript PHP Scripts Response is not PHP, but the result of interpreting PHP, usually more HTML and CSS. Web browsers handle HTML, CSS, and JavaScript using the browser’s own code. But PHP scripts have to be handed off to another program, and that program deals with the scripts, returning something useful (hopefully!) to a web server, which then can pass a response back to the web browser. (As was the case with earlier diagrams, this is a bit of an over-simplification. The PHP interpreter interacts closely with your web server, and so doesn’t stand quite so far outside the server as it might appear.) Chapter 1: PHP: What, Why, and Where? 19 PHP Comes in Two Flavors: Local and Remote Here’s the basic process: 1. A web browser makes a request for some page. That page might be a URL on a remote web server, or a local file on your computer. Warning Right away, there’s potential for trouble here. If the browser requests a local HTML, CSS, or JavaScript file, there’s no problem. That’s because, as you now know, browsers can handle those file types. But if it requests a PHP file without going through a web server you’re not going to get a response that the browser can handle on its own. 2. Assuming that the request goes to a web server, the web server returns HTML (and CSS and JavaScript) or, in the case of PHP, passes the PHP request on to the PHP interpreter. 3. The PHP interpreter does what it’s supposed to: it interprets, or runs, the PHP. The result of that should be something that a browser can understand, like HTML. It passes this result, or response, back to the web server. 4. The web server gives the browser back something that the browser can understand: the HTML result of interpreting a PHP script, or CSS, or JavaScript, or a combination of all of the above. Understanding this difference in how PHP works, as opposed to HTML, CSS, and JavaScript, is important because it determines the approach you’ll take to writing PHP scripts and getting those scripts to run. Write Anywhere, Run Where There’s PHP The cool thing about HTML, CSS, and JavaScript is that because they’re built in to browsers and you can download browsers so easily, those technologies become instantly available. It’s tough to even find a computer without a browser preinstalled. So, you turn on your computer for the first time, and boom, you can start creating web pages immediately. Double-click the HTML file, your browser fires up, and you’re good to go. But PHP isn’t part of that browser. It’s not always preinstalled. If you write a PHP script and then double-click it, you’ll probably see a code editor launch, but not something that will actually run that script. Even worse, if your browser does open up your PHP script, it’s not a web server. It doesn’t have a PHP interpreter. It will just show you your code, rather than run it, and what good is that to anyone? This long prelude is just a big warning: although it’s easy enough to start writing PHP scripts, you can’t just open them in Dreamweaver or Firefox and expect them to run. You’ll end up frustrated and annoyed, and that’s no good for anyone. 20 PHP & MySQL: The Missing Manual The bottom line is this: You can write PHP on your own local computer, but you’ve got two choices for actually running that PHP: PHP: Going Local 1. You can go through the lengthy process detailed in the next section and install PHP on your local computer. This process will take some time, and you’ll have to monkey around a bit with your computer at a system and network level. You’ll also need a local web server to handle the PHP interpreting part of the gig. This way, you’ll not only have a browser that can handle HTML, CSS, and JavaScript, but a complete setup that can take on PHP without a problem, too—right on your own computer. 2. You can write your scripts locally and always upload them to an Internet Service Provider (ISP) or web hosting company. Every ISP and web hosting company supports PHP, and you usually don’t have to do anything more than name your scripts with a .php extension. This option involves less initial setup, but it means that every time you edit your script, you need to upload it again to your ISP. It also means that double-clicking your PHP script won’t do anything more than, at best, open your editor. You can’t test your scripts on your own computer. Both choices are equally good, and which one you choose depends largely on your circumstances. Even though it might seem perfectly natural to jump right into uploading your scripts, you aren’t always going to have a network connection. (The sound you just heard was the cheering of all the programmers who have an hour-long commute into work on their local metro or subway!) For those unwired situations, it’s nice to be able to keep developing on your own computer without the need to access your hosting provider. Note only that, installing PHP on your own computer is great for understanding what the PHP interpreter actually does. So, before you start writing scripts that you can’t even run, it’s time to get PHP working on your own computer (if you want to), and then talk about getting scripts running out there in the wild, as well. Note In the long run, you probably want to have both a way to use of PHP and MySQL without an Internet connection and a hosting provider or ISP set up. That way, you can work on your own computer whenever you want, and then upload your scripts when they’re ready to see the light of day. PHP: Going Local It’s not difficult to install PHP on your own computer. This is typically called a local installation, which just means that all your programs are running on your own local machine. (For more detail on how the whole thing works, see the box on page 22.) Chapter 1: PHP: What, Why, and Where? 21 PHP: Going Local Although PHP isn’t preloaded on every computer like web browsers are, it’s still easy to download PHP from the Internet, get it working on your computer, and get up and running fast…all without spending a dime. On top of that, most of the easiest and best tools for writing PHP code are also free. You just have to know where to find them. POWER USERS’ CLINIC Local Software Runs on localhost The term local has a lot of meanings in computer programming, especially when you start interacting with networks. Every computer is capable of sending information to itself, through a loopback network interface. This interface usually has the IP address 127.0.0.1 and a hostname of localhost . This scenario becomes pretty handy when you want to run a web server on your own computer, and that’s what you’ll be doing later when you get a local installation of PHP up and going. When you want to access that web server, you need to type something into your browser, and that’s where localhost comes in. You can enter either the IP address http://127.0.0.1, or http://localhost , and your computer will send your request to itself…and any software you’ve got installed and running that’s capable of receiving that request. Note The next section explains how to install PHP on computers running Microsoft Windows. If you have a Macintosh, flip to page 28. PHP on the Windows-Based Computers (WampServer Installation) Open your favorite web browser and head to www.wampserver.com. This is the online home of WAMP, which stands for Windows, Apache, MySQL, PHP. The site is shown in Figure 1-5. Note Although the website is called WampServer—and describes the grouping of software “Apache, PHP, MySQL on Windows”—the WAMP acronym lives on. Select the relevant Download link for your version of Windows. If you’re not sure, you can go to your Control Panel, select System, and then poke around. You’ll see either “32-bit Operating System” or “64-bit Operating System,” and that tells you what you want. Just select the first link on the top-left of the page that matches your system. When downloading starts, you see a warning—actually, a couple of them—about needing some C++ extensions. Click the link for your system (see Figure 1-6), download the extensions (see Figure 1-7), and then run the downloaded file. You’ll need to allow the downloaded program to update your system, accept a license agreement, and install the extensions. When that’s complete, a screen appears like the one in Figure 1-8. 22 PHP & MySQL: The Missing Manual PHP: Going Local Figure 1-5 Wampserver.com brings together everything you need for getting PHP and MySQL going and behaving on your Windows PC. Figure 1-6 WampServer requires some extra work on your part before it can install, most notably, you need to download some C++ extensions to get everything in the PHP interpreter behaving. Chapter 1: PHP: What, Why, and Where? 23 PHP: Going Local Figure 1-7 Microsoft hosts the C++ libraries that WampServer depends on to install. Figure 1-8 Finally! The C++ extensions are installed. Now you can get back to actually installing WampServer. 24 PHP & MySQL: The Missing Manual Once you’ve installed the C++ extensions, go back to Wampserver.com, select Downloads again, and then click the download link. This time, you can ignore the warning. Click the words “you can download it directly.” PHP: Going Local The ad-heavy site you’re taken to will trigger a download in a few seconds. Then, save and run that file; you’re finally installing WampServer. Figure 1-9 is what you’re aiming for. Figure 1-9 All that work for the little pink “W” logo. It’s worth it, though. Installing PHP manually (as detailed in the appendixes) makes this look like a walk in the park. Accept the license and default installation directory (typically C:\wamp). You might want to create a quick link icon, or at least a desktop shortcut, and then let installation take off. Select your default browser. You’ll then be asked about allowing Apache to access public networks (Figure 1-10). The best option here is usually the default supplied by the WampServer installer. Figure 1-10 Unless your computer is directly connected to the Internet and has its own dedicated, publicly available IP address, the default options are just fine here. Chapter 1: PHP: What, Why, and Where? 25 PHP: Going Local You then have a few other options for PHP mail, and then you’re finished. Launch WampServer, and you should see…nothing! Well, almost nothing. On the right side of the taskbar, notice there is now a little green “W” (check out Figure 1-11). Figure 1-11 Now you’ve got WampServer running happily in the background. For your troubles, though, it appears you’ve only got this little green “W” icon. Click the green W icon to see all of the things you’ve been reading about, like PHP, MySQL, and Localhost, as shown in Figure 1-12. Figure 1-12 You can do a lot from the WampServer icon: start and stop the new programs you’ve installed, use the handydandy phpMyAdmin tool (which you’ll see more of in Chapter 7), and more. You’ll use almost everything here before you’re done. You’re almost done. Select the top option, Localhost. (If you don’t remember what localhost means, see the box on page 22.) A new web browser window or tab opens with an address that references your own locally installed web server. This Server Configuration page presents information about your own web server setup (see Figure 1-13). It isn’t particularly impressive to look at, but it’s proof that your Windows computer can now serve up web pages. While on the Server Configuration page, in the Tools section (about halfway down the page), click the phpinfo() link. A page opens that looks something like Figure 1-14, which is everything you’ll ever need to know about your local PHP installation. 26 PHP & MySQL: The Missing Manual More important, it means that your browser made a request to a web server, and that web server processed some PHP (the phpinfo function) and handed back a response to your browser. Not only can you run PHP on your computer, you just did. PHP: Going Local Figure 1-13 Having a web server running on your local computer isn’t necessary for developing HTML, CSS, or most JavaScript applications. But because a browser can’t interpret PHP, a local web server is essential if you want to write PHP scripts on that computer and run them without uploading them to a server somewhere. Figure 1-14 And the big win: PHP is running! Actually, your browser made a request to your local web server, your local web server executed some PHP, and then it responded to your browser with the response from that PHP command. Chapter 1: PHP: What, Why, and Where? 27 PHP: Going Local You’ve got PHP! Now it’s time to get scripting. PHP on the Mac (Default Installation) If you’ve got a Mac, you’ve got more than just a sleek, shiny machine and way too many ways to spend even more money with Apple, you’ve already got PHP installed. To prove it, open the Terminal application on your Mac. If you’ve never used Terminal, don’t worry; you’ll get used to it quickly and find it’s one of your best friends for working with PHP. Go to Applications→Utilities→Terminal. Note You can also get to the Applications folder in a flash by pressing Shift--A. However, this keyboard shortcut works only in the Finder. If you’re currently viewing this book in an e-reader or online, for example, click your desktop and then press Shift--A. Shift--A is a little-known shortcut, but if you’re the programming type, you’re probably all about keyboard shortcuts. Once you’ve found the Applications folder, open it and find the Terminal application. It looks like a computer monitor with a black screen and a little white arrow, as shown in Figure 1-15. Figure 1-15 The Terminal program lets you use a command line on Macintosh computers. A lot of your PHP coding will be done by using Terminal, so you’ll get used to this application quickly. Open it, and you see a barebones screen like the one in Figure 1-16. Tip You’ll often use Terminal for testing your PHP programs before you upload them to your server. To make it easier to launch Terminal, drag the icon onto your dock. 28 PHP & MySQL: The Missing Manual PHP: Going Local Figure 1-16 When you first open Terminal, you won’t be too impressed. You’ll get a line that probably matches your computer’s name and then a weird dollar sign. Don’t worry…this will all soon be old hat. To ensure that PHP is installed on your system, type php (all in lowercase letters) and press Enter. Unfortunately, the way to know things are working is if you don’t see anything but that blank cursor, a little further down in Terminal. It won’t even blink at you anymore; it’s just a boring, dark gray square. Press Control-C to stop that single eye from hanging around and to display the blinking cursor again. This time, type which php. The which command lets you know where on your computer the program you type is located. In this case, you’re asking where the php program is located. You’ll probably get something back that looks like Figure 1-17; for the computer in this example, php is in the /usr/bin directory. You’ll probably get a similar result. Figure 1-17 Lots of the programs you’ll use in Terminal are scattered around your Mac’s hard drive. The which command lets you know exactly where a program resides on your machine. Once you’ve seen where php is, you’re ready to go. It was installed all along. Chapter 1: PHP: What, Why, and Where? 29 PHP: Going Local Power Users’ Clinic Take Control of Your PHP Installation Like most of the programs on your computer, the PHP software package (which includes the php program you’ve been running) is updated fairly often. Most of the time, if you’re keeping your computer updated with Apple’s Software Update, this isn’t something to worry about. But if you want to see what version of PHP you’re running, you can type php –version into your Terminal window. You’ll get back something like this: Bretts-MacBook-Pro:~ bdm0509$ php -version PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 19982010 Zend Technologies Look at the very first line that PHP displays: this tells you that you’re running version 5.3.4. If you want to get the very latest version of PHP, you can visit www.php.net and download the PHP source code. That’s a little trickier than just using the preinstalled version on your Mac, though, so unless you’re into commands like unzip and tar, you can stick with what’s already on your computer. By the way, this is a great time to remind you that if you’re not using your Mac’s Software Update frequently, you might want to do that now. It keeps your software current without all the hassle of downloading programs on your own. PHP on the Mac (MAMP Installation) Although it’s nice that Macs come with PHP already installed, there might just be a better option—one worth doing a bit of downloading and installing for yourself. That better option is MAMP, which stands for Mac, Apache, MySQL, PHP. This is the Mac counterpart to WAMP, the easy Windows PHP installation (page 22) that you, as a Mac user, probably skipped. MAMP doesn’t improve on the PHP installation that came on your Macs; it does integrate MySQL—which you’ll need before you know it—as well as the Apache web server and several helpful tools for working with PHP scripts and MySQL databases. You even get a simple control panel for starting up your local web server and MySQL database. Those additions are a nice perk, and coupled with how easy it is to install MAMP, you might just want to ditch the default PHP installation and get MAMP going. First, using your favorite web browser, visit www.mamp.info. A site like the one shown in Figure 1-18. 30 PHP & MySQL: The Missing Manual PHP: Going Local Figure 1-18 The MAMP site is a PHP developer’s best friend. The free MAMP download gives you almost everything you could want for developing great PHP scripts and the databases with which they work. Simply click the “Download now” button under MAMP and then grab a coffee and wait for the installer to download. Now, launch the installer. Click Next a few times to select your hard drive and agree to the license. Keep going until the installer informs you that MAMP is ready to install, as shown in Figure 1-19. Note Some versions of MAMP don’t have a correctly signed security certificate. This results in a nasty message popping up when you try to launch the installer: “MAMP_2.1.1.pkg can’t be opened because it is from an unidentified developer.” Fortunately, you can safely ignore this for MAMP. Just Control-click the installer, and then in the popup menu that appears, you can click “Open.” This will in turn give you a dialog box, and you can click “Open” yet again. Finally, you’ll have your program ready to run. Fortunately, you should only have to do this once. Chapter 1: PHP: What, Why, and Where? 31 PHP: Going Local Figure 1-19 MAMP is simple to install but it eats up about half a gigabyte of disk space. That’s ok; you’re getting a full-blown web server, PHP interpreter, MySQL database, and a suite of tools. Once the installation is complete, go to Applications→MAMP. You’ll see a nifty control panel, a la Figure 1-20. Figure 1-20 This control panel is MAMP’s home base. You can start and stop software components and make all your configuration changes here. While you’re getting your PHP feet wet, you may want to move the MAMP icon into your dock; you’ll be using it a ton. Your installation might try to automatically start both an Apache server and the database. Still, you can configure these easily by clicking the Preferences button. You should probably check the Ports tab and ensure that there aren’t any issues with any other software on your computer. You can do this all within MAMP, as shown in Figure 1-21. 32 PHP & MySQL: The Missing Manual PHP: Going Local Figure 1-21 MAMP lets you change both the port that Apache (the web server) runs on, as well as the port that MySQL runs on. Be especially careful with the MySQL port. Most programs that use MySQL will need to be updated to the value you use here. Note If all this talk of ports is starting to give you a headache, that’s okay. It probably just means that your machine is set up without any software running on weird ports, and that makes things easy here: just accept the defaults. These are pretty standard ports, and will almost always work perfectly with a system. You can also click the PHP Preferences option and see a few things that, honestly, probably don’t matter much to you (see Figure 1-22). Just leave these alone. In fact, there’s almost never a reason to mess with these selections. Mostly, it’s good to know that yes, MAMP did indeed install PHP (along with a web server and MySQL) with just a few mouse clicks. Figure 1-22 There are some reasons you might one day want to jump back from PHP 5.3 to 5.2, but that’s far down the line. For now, just accept these options as they are and get ready to start scripting. Chapter 1: PHP: What, Why, and Where? 33 PHP: Going Local There’s not much else to do now, so you can close Preferences and click the “Open start page” option to get a nice browser page like the one shown in Figure 1-23. Here’s where you’ll spend lots of your troubleshooting time as well as digging into databases once you’ve mastered the command line tools for MySQL that you’ll learn about in Chapter 4. Figure 1-23 Here’s where you’ll do most of the work once you have your MAMP software running. Think of the MAMP control panel as the place you’ll control the programs, and this start page as where you’ll interact with those programs. Before moving on, you can verify that this is all doing what it should. At the top of the MAMP start page, click the “phpInfo” tab. A screen appears, similar to that in Figure 1-24. What’s significant here isn’t all the information listed; you needn’t concern yourself with that just yet. What is cool, though, is that you’re looking at a PHP script that’s been interpreted by a PHP interpreter (installed as part of MAMP). The interpreter then fed the output of that script to your new MAMP-installed web server, which in turn handed that response to your web browser. Proof that you’re already running PHP. 34 PHP & MySQL: The Missing Manual PHP: Going Local Figure 1-24 This page is actually the output of the phpinfo function in PHP. Here’s the proof that you’ve got what you need to run PHP scripts on your local machine. In fact, you just ran one. Get Out Your Text Editor All the programs you’re going to write in PHP are plain, old text files. Writing PHP isn’t a lot different than writing HTML or CSS or JavaScript. You’ll type different things, of course, but these are all just text files saved with a special extension. You use .html for HTML, .css for CSS, .js for JavaScript, and now you’ll use .php for PHP files. Because PHP is just text, you’ll want a good text editor in which to work. If you’re in Windows, you can use Notepad. As simple as that program is, it’s perfect for coding in PHP. If you’re on a Mac, TextEdit is a great choice. The good news is that each of these programs comes preinstalled on your computer, so you don’t have to download or buy anything. The bad news is that none of these programs know you’re writing PHP, so you don’t get much help if you type something wrong or want to organize your files without resorting to Windows Explorer or the Finder. These programs are simple, but limited. On the other hand, there are quite a few editors out there that are built specifically to handle PHP. For instance, for Windows, you can download NuSphere PhpED (nusphere.com/products/phped.htm), which is shown in Figure 1-25. You’ll pay a bit for a program like NuSphere—usually between $50 and $100—but you’ll get fancy Chapter 1: PHP: What, Why, and Where? 35 PHP: Going Local color coding, help with special language features, and in a lot of cases, some nifty file organization features and the ability to upload your PHP directly to your web server. Figure 1-25 NuSphere PhpED gives you a ton of features and supports JavaScript, CSS, and HTML, as well as PHP. It also has great documentation for most of the PHP functions and libraries. If you’re on a Mac, the two leading candidates for editors that do text plus lots of other cool things are BBEdit (www.barebones.com/products/bbedit/index.html) and TextMate (www.macromates.com). Both are Mac-only programs, and both offer similar features on the Mac as does PhpED for Windows: color-coding, file management, help documentation, and support for HTML, CSS, JavaScript, and a lot more. You can see BBEdit in action in Figure 1-26; you’ll need to drop $100 to get your own copy, though. Figure 1-26 BBEdit is supposed to be bare bones, but you’ll find it has more than adequate PHP support. It’s tuned primarily for HTML, so there are a few oddities, but it’s a great choice for PHP work on the Mac. You can see what TextMate looks like in Figure 1-27. It’s a little simpler than BBEdit, so if you’ve never used a programming editor, this might be easier to begin with. TextMate costs around $60, slightly less than BBEdit. 36 PHP & MySQL: The Missing Manual PHP: Going Local Figure 1-27 TextMate is an editor that seeks to provide colorcoded editing and not much else. It does offer file management and FTP support, but it’s best at letting you type code and staying out of the way. UNDER THE HOOD Text Editors: Mashing Up Programs Although programs like PhpED, BBEdit, and TextMate are billed as text editors, they’re actually lots of programs rolled into one. Imagine having a text editor, a file management tool like Windows Explorer or Finder, a telnet or terminal program, an FTP client, and some glue to hold them all together. That’s more or less what these programs give you: a bunch of things all rolled into one single software package. What’s great about these “text editors plus” is that they offer you all sorts of features, and you don’t need five or six icons in your Mac’s Dock or shortcuts on your Windows desktop. You have access to almost everything you’ll typically need to build web pages or program in PHP, right at your fingertips. What’s not so great, though, is that generalized tools aren’t often as fully featured as specific tools. In other words, a program that tries to do everything usually does lots of things decently, as opposed to lots of programs that only do one thing, but do that one thing really well. Much of the time, you’re making a choice between convenience and features. If you only use FTP to upload files to a server on occasion, you almost never work with your computer’s command line, and you get a kick out of colored editors, the bundled text editors with lots of extra features might be a good fit. Whether you use a more full-featured text editor or not, though, at some point you might need to ditch the editor and use an actual FTP or telnet program. As long as you’re comfortable diving into those programs without the use of an editor from time to time, by all means, go forth in code in TextMate or PhpED without worry. Once you’re comfortable writing PHP code, you can spend some time playing with all these different enhanced editors. You can see what you like, discover whether an editor is perfect for you, or realize you’re a Notepad or TextEdit programmer at heart. There’s no one right option for PHP; all of these choices work just fine. If you’re just starting out, though, try to use a simple text editor—Notepad on Windows or TextEdit on the Mac. You’ll learn a lot more about PHP this way, even if you don’t get all the bells and whistles of one of the full-featured editors. Besides, once you understand PHP and have learned to work with it manually, you’ll appreciate and be able to use the features of the other editors a lot more effectively. Chapter 1: PHP: What, Why, and Where? 37 Write Your First Program Note Once you’ve become familiar with PHP, you can also check out Eclipse PHP (www.eclipse.org). The Eclipse IDE has long been a favorite for Java developers, and there are now enough plug-ins for PHP that it’s a legitimate option for PHP programmers, too. However, there’s a lot going on in Eclipse—tons of tools and gadgets—so you might want to wait a bit before you dive head first into it. Come back to it later, though; it’s well worth checking out. Write Your First Program You’ve got PHP installed locally and you’ve got a text editor. Now all you need is an actual program. Start your text editor and type the following code, exactly as shown here: Note You can find a copy of this script on this book’s Missing CD page at www.missingmanuals.com/cds/ phpmysqlmm2e. A lot of this probably looks weird, and that’s OK. You’ll soon understand every bit of this code. Right now, just get used to looking at PHP, which is quite different from HTML or JavaScript. Warning Some of the editors you might use, like TextEdit, will try to save the document as rich text. Rich text lets you use formatting, like bolding and underlining. You don’t want that in your PHP code, so look for the option to use plain text, which doesn’t provide formatting. If you’re using TextEdit, choose Format→Make Plain Text. (You won’t see that option if you’re already working in plain text.) If you’re using Notepad, rich text isn’t an option, so you’ve got nothing to worry about. Once you’re done, your editor should look similar to Figure 1-28. 38 PHP & MySQL: The Missing Manual Write Your First Program Figure 1-28 PHP is just text, but it uses several weird characters. Start getting used to typing the dollar sign ($), angle brackets (< and >, just like in HTML), and the backslash (\). You’ll be using those characters a lot. Note You won’t see the nice color-highlighted syntax until you save your file with a .php extension. This program does just a few simple things: • Identifies itself as PHP by using characters. It’s okay if not much on this list makes sense yet, especially the weird line beginning with $name =. There are also some strange characters like \n and STDIN that you’ll learn about soon. But see if you can follow the plain-English words through the basic path: the opening . Now, save this program. Name it sayHello.php, and ensure that you add that .php extension! Otherwise, you’ll have a lot of problems down the line. Save the file some place handy, like on your desktop, your home directory, or a folder you’re using to keep all your PHP programs in as you’re learning. Warning Most programs in Windows and on the Mac append a default extension, like .txt. Make sure you replace this with .php. Windows especially tends to hide extensions, so verify that your full filename is sayHello. php, not something like sayHello.php.txt. That’s it; you’ve written your first PHP program! Chapter 1: PHP: What, Why, and Where? 39 Run Your First Program POWER USERS’ CLINIC Default to Plain Text Most of the popular text editors let you change from rich text to plain text on a per-file basis, but they automatically start out in rich text mode. That can become a pain, so you might want to change the setup of your editor to always start out in plain-text mode. For TextEdit on the Mac, open the Preferences menu. At the very top, under Format, select “Plain text” (as shown in Figure 1-29). In Windows, if you use Notepad, you avoid this entire issue, so you’ve got nothing to worry about. Figure 1-29 You can get to the TextEdit preferences via the Preferences menu, or by using the shortcut combination -period. In the Preferences box, you’ve got lots of options, but the text format and font used for plain text are the most important for now. Run Your First Program What good is it to get all this code typed in if you can’t see if it works? This particular program isn’t ready to run on the Web yet; first you need to add something to it in your command-line terminal program, so go ahead and fire that up. If you’re on the Mac, you should open up Terminal. In Windows 7 or earlier, go to Windows Start→Run and then run command or cmd from the menu to get a command line. In Windows 8, at the start screen, press Windows key + R and then type cmd (as shown in Figure 1-30). 40 PHP & MySQL: The Missing Manual Run Your First Program Figure 1-30 In Windows 7 (left) and earlier, you can get to the command line via the Start menu. Since Windows 8 doesn’t have a Start menu, just go to the Start screen and press Windows key+R. That opens the Run box where you can type cmd. Now, go to the directory in which you saved your program, sayHello.php. You can do a directory listing with dir (in Windows) or ls (on the Mac) to ensure that you’re in the right directory. Once you’re in the right directory, type this into your command line: php sayHello.php This instructs the php program to run and gives it your program, sayHello.php, as the script to run. In short order, you should see the welcome message you typed, and then the program asks you for your name. Type your name and press Enter. The program should then greet you, just as shown in Figure 1-31. Figure 1-31 Eventually, you’ll run most of your PHP scripts through a web browser. For now, though, the command line lets you take control of the php command and give it a particular script to run so that you can see the output on the command line. That’s it! Your first program works, and you’re ready to go deeper into PHP. Chapter 1: PHP: What, Why, and Where? 41 But Where’s That Web Server? But Where’s That Web Server? Before you take that well-deserved break, there’s one question left to answer. Remember way back to the discussion about a PHP interpreter interacting with a web server? All that business about PHP running locally or running remotely? Uploading files, web hosting providers; remember all that stuff? If not, Figure 1-32 should be a helpful refresher as to how PHP usually functions. Could be for HTML, CSS, PHP or a combination. Figure 1-32 HTML Web Browser HTML renderer CSS Request CSS renderer JavaScript interpreter Response Web Server PHP interpreter JavaScript Remember this diagram from earlier? Even though it hasn’t applied to your first PHP program, it still holds true. As soon as you start writing scripts that interact with web pages, you’re going to need a web server. PHP Scripts Response is not PHP, but the result of interpreting PHP, usually more HTML and CSS. So what gives? You installed PHP locally and ran your script without problem, but a web browser wasn’t involved The PHP Interpreter Is a Program You Can Run The PHP interpreter that’s shown in Figure 1-32 is just a program, like dir or ls or which or anything else you can type into a command-line or terminal window. And just like those other programs, you can run it on your scripts manually. In fact, that’s just what you did. You ran the PHP interpreter (php) on your script, because you installed WampServer or, if you’re on a Mac, because php is already installed. But, this sort of script—where all it does is output some text—is not the typical PHP script. It’s more of a “blow bubbles in the kiddie pool” script: helpful to get started, but just the tiniest taste of what’s coming. 42 PHP & MySQL: The Missing Manual So, you don’t need a web browser or a web server. You just needed the PHP interpreter. Because of that, there’s no sense uploading your script and trying to find the PHP interpreter on your hosting provider, which requires shell access, which in turn might require calling up tech support and spending 20 minutes on the phone giving out maiden names and birthdates…in other words, it’s just not worth it. But Where’s That Web Server? But, the HTML Is Coming… Keep those credentials handy, though, because in the next chapter, you will start uploading your scripts. You’ll move beyond simply outputting text and begin to output HTML. You’ll take input from an HTML form and churn back out styled, web-friendly responses. And, you’ll move from using just a local PHP installation to using a remote one. Buckle up, take that break, and head on over to Chapter 2. Chapter 1: PHP: What, Why, and Where? 43 chapter 2 PHP Meets HTML W ith your first PHP script under your belt, you’ve made some real progress. But that PHP script might not have been what you expected. Most web developers don’t fall asleep at night dreaming of seeing this in a terminal window: Hello there. So I hear you're learning to be a PHP programmer! Why don't you type in your name for me: Brett Thanks, Brett, it's really nice to meet you. Even less impressive than its complexity (or lack thereof) is the script’s format. It’s just plain text. There’s no formatting; in other words, no HTML. In this chapter, you’re going to inject HTML into your scripts. No command-line prompts and boring text. By the time you’re through, your script will be speaking the language of the Web—HTML. In addition, you’ll see how PHP does one of its core tasks: respond to an HTML form. 45 Script or HTML? Script or HTML? Before you can start doing fancy party tricks with PHP, you’ve got to get over a bit of a conceptual hurdle. So far in your web programming journey, you’re probably used to thinking about the technologies you’ve learned in strict categories: HTML is markup, the structure of your page; CSS applies style to that structure; and JavaScript adds some interaction, with everything from alert boxes to validation, redirection, and widgets. In the process, you probably also built some syntax categories. Your HTML is angle brackets,and and , and the like. CSS is curly braces and style keywords like p.warning and { } and border-style: dotted. The same is true with JavaScript: you’ve got alert and strings in quotes like "Please enter a valid phone number." And those categories are distinct. Your HTML is separate from your CSS, which is separate from your JavaScript, even though they all interact with one another. But with PHP, you’re going to have to abandon some of those categories. PHP happily—and sometimes confusingly—mixes these categories. You can write a PHP script that does programming tasks and then outputs HTML, CSS, and even JavaScript. Determination by Extension PHP scripts are identified by the extension .php. Accordingly, web servers that supports PHP see a file with a .php extension and hand that file off to the PHP interpreter for processing. The interpreter does its thing and hands the result of the interpreted script back to the web server, which in turn passes that response along to a user’s web browser. Another look at this process, which is shown in Figure 2-1, might help. Could be for HTML, CSS, PHP or a combination. Figure 2-1 HTML Web Browser HTML renderer CSS Request CSS renderer JavaScript interpreter Response Web Server PHP interpreter JavaScript PHP Scripts Response is not PHP, but the result of interpreting PHP, usually more HTML and CSS. 46 PHP & MySQL: The Missing Manual Unlike HTML, CSS, and JavaScript, which are handled by the browser using the browser’s own code, PHP scripts must be handed off to another program—the PHP interpreter. As discussed on page 19, that program deals with the scripts, returning the results to a web server, which then can pass a response back to your web browser. But what’s inside that script can be…well, all sorts of things. Remember, it’s the output of a PHP script that is ultimately handed off to a browser, so that response can’t be PHP. It must be some combination of HTML, CSS, and JavaScript—the things that a web browser knows how to handle. Script or HTML? In other words, a PHP script might be made up of PHP commands, but it also must be able to output more than just text, like sayHello.php from Chapter 1 does. It must be able to output HTML, CSS, and JavaScript. Fortunately, this isn’t as difficult or tricky as it might sound. HTML Is Treated as HTML You might be thinking, “Ok, I get it. I can use that echo command from Chapter 1 to output HTML, right?” Or maybe if you’ve used jQuery, you’re already a step beyond that: “Maybe there’s some cool PHP toolkit that makes building up an HTML and CSS response easy.” Although both of those thoughts are true, as you’ll see in this section, they’re actually not the simplest way to have a PHP script generate an HTML response. For example, here’s some HTML for a simple web form, sort of like the program you already built in Chapter 1.
PHP & MySQL: The Missing Manual
Example 2-1Chapter2: PHP Meets HTML 47 Script or HTML? Type this code into a text editor (for a refresher on text editors, see page 35) and save it as sayHelloWeb.html. For advice on where to save your files, see the box below. Up to Speed Directory Assistance If you open sayHelloWeb.html locally, you should also put the CSS and images referenced in the page alongside the file in the correct directory structure. So, if your HTML is in phpMM/, you should have scripts/, css/, and images/ subdirectories inside phpMM/. Your HTML files go directly in phpMM/, sayHelloWeb. php goes in scripts/, and your CSS and images go in css/ and images/, respectively. If you download the book’s examples, things are organized even a little more tightly. You have a core folder like ch01/, and then subdirectories for each chapter’s major headings: 01/, 02/, and so on. Then, in each of those directories, you see the HTML alongside scripts/, css/, and images/. You can use that layout, or just drop all the downloaded files as-is into your own location, and things should work just fine. Or, you can put those files somewhere else and update the paths in the HTML and CSS to point to that location. Either way, you need to realize that if you just double-click this file on your desktop, you might not see the correct images and styles. Note You can download this HTML, along with the rest of the book’s sample files, from www.missing manuals.com/cds/phpmysqlmm2e. Along with the HTML, you also get the CSS and images used by the samples, which will give your programs a little extra visual pizzazz. Still, especially as you’re just getting started, you’ll learn a lot more if you’ll type the PHP code for these programs yourself. Nothing new here other than the form’s target: scripts/sayHelloWeb.php. Don’t worry about that for now, though; you’ll deal with that shortly. Open the page locally on your own computer. (Check out the box on page 22 for more on getting your local web server going.) If you get things in the right place, you’ll see something like Figure 2-2. Your web browser sees all the HTML here and knows what to do: show a web page. FREQUENTLY ASKED QUESTION How do I access my local web server? Even though you can count on your computer’s web browser to know what to do with an HTML file, like sayHelloWeb.html, you’ll want more than that before you go much further. If you’ve followed along from Chapter 1, you should have MAMP or WampServer installed. That means you’ve got a web server ready to go on your local machine. In Windows, WampServer serves HTML by default out of C:\ wamp\www\ . You can also click the small, green “W” icon 48 in the taskbar at the bottom right of your screen and select “www directory” to go directly to this location. Then, you can access your files in a web browser by visiting http://localhost . In Mac OS X, the default directory for your web files is /Applications/MAMP/htdocs . You can drop sayHelloWeb.html in that directory and access it through http://localhost:8888/ sayHelloWeb.html. That also gives you a place to drop in the downloaded CSS and images you should have by now. PHP & MySQL: The Missing Manual Script or HTML? Figure 2-2 If there’s anything confusing here, you might want to take a look at HTML5: The Missing Manual by Matthew MacDonald (O’Reilly) to regain your bearings. Hopefully, though, this HTML is straightforward for you, and the biggest challenge is making sure that it’s in your working directory alongside css/, images/, and so on, or that your path in your HTML matches your own directory structure choices. PHP Is Not HTML (by Extension) Just for the sake of experience, do something that might seem utterly bizarre to you: rename sayHelloWeb.html with a .php extension, to sayHelloWeb.php. If you then double-click this file, a number of things might happen—none of which you want. If you have a code editor like Dreamweaver, XCode, or Eclipse, those editors might launch and show you your file. Or, you might get an error because your computer doesn’t know how to open the file. Even worse, if you open the file in your web browser (using the browser’s Open command, for example), the browser won’t know what to do with it. It will probably ask you if you want to save the file (as demonstrated in Figure 2-3). Chapter2: PHP Meets HTML 49 Script or HTML? Figure 2-3 Web browsers don’t know what to do with files ending in .php. A web server could hand that file off to a PHP interpreter, but your browser? No clue. It just dumbly suggests you save the file. The sayHelloWeb.php file is definitely not HTML in terms of the file type. But the file contains HTML, so there must be some way to display that HTML. This time, instead of double-clicking the file or opening it with the browser’s Open command, type the file’s URL directly into the browser’s address bar. (If you’re not sure what this URL is, refer back to the box on page 48.) This time, you should see something that might surprise you; check out Figure 2-4 for the details. Figure 2-4 Your web browser couldn’t open sayHelloWeb.php, and you know it’s not an HTML file, based on the .php extension. But this sure looks like HTML. In fact, it looks exactly like the HTML file sayHelloWeb.html from Figure 2-2, as it well should: it contains the exact same HTML. 50 PHP & MySQL: The Missing Manual PHP Can Be HTML—by Response As you learned in the previous section, the browser can’t handle reading a PHP script, but when you access the page through a locally running web server, things just work. That’s because the PHP interpreter is perfectly happy to take the HTML in the PHP script and push that HTML out as a response. The web server sends that HTML on to a browser, and this time—because the browser is getting HTML, not a file with a .php extension—it displays the HTML as a web page. PHP Talks Back Now you’ve seen how a PHP script can return a full-blown HTML web page that any browser can display. Well, that’s actually what you’re going to be doing a lot in this book, starting in the next section: you’ll do some programming in your scripts, and return HTML as a response. But first, rename sayHelloWeb.php back to sayHelloWeb.html. Then, look back at the form line in the HTML file:Welcome!
Hello there. So I hear you're learning to be a PHP programmer!
Why don't you type in your name for me: