www.it-ebooks.info www.it-ebooks.info www.it-ebooks.info PHP & MySQL The book that should have been in the box® Brett McLaughlin Beijing | Cambridge | Farnham | Köln | Sebastopol | Tokyo www.it-ebooks.info PHP and MySQL: The Missing Manual by Brett McLaughlin Copyright © 2012 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 Printing History: November 2011: First Edition Revision History: 2011-11-09 First release See http://oreilly.com/catalog/errata.csp?isbn=9780596515867 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 ISBN-13: 978-0-596-51586-7 www.it-ebooks.info Contents The Missing Credits vii Introduction xi Part One: Chapter 1: PHP and MySQL Basics PHP: What, Why, and Where? Gathering Your Tools Writing Your First Program 14 Running Your First Program 16 Writing Your Second Program 17 Upload Your HTML, CSS, and PHP 20 Running Your Second Program 21 Chapter 2: PHP Syntax: Weird and Wonderful 25 Get Information from a Web Form 25 Working with Text in PHP 32 The $_REQUEST Variable 46 What Do You Do with User Information? 53 Chapter 3: MySQL and SQL: Database and Language 55 What Is a Database? 55 Installing MySQL 59 SQL Is a Language for Talking to Databases 76 Part Two: Chapter 4: Dynamic Web Pages Connecting PHP to MySQL 91 Writing a Simple PHP Connection Script 91 Cleaning Up Your Code with Multiple Files 103 Building a Basic SQL Query Runner 109 Chapter 5: Better Searching with Regular Expressions 127 String Matching, Double-Time 128 iii www.it-ebooks.info Chapter 6: Generating Dynamic Web Pages 143 Revisiting a User’s Information 143 Planning Your Database Tables 145 Saving a User’s Information 151 Show Me the User 159 Redirection and Revisitation of Creating Users 176 Part Three: Chapter 7: From Web Pages to Web Applications When Things Go Wrong (and They Will) 191 Planning Your Error Pages 192 Finding a Middle Ground for Error Pages with PHP 199 Add Debugging to Your Application 207 Redirecting on Error 216 Chapter 8: Handling Images and Complexity 227 Images Are Just Files 228 Images Are For Viewing 249 And Now for Something Completely Different 258 Chapter 9: Binary Objects and Image Loading 259 Storing Different Objects in Different Tables 260 Inserting a Raw Image into a Table 262 Your Binary Data Isn’t Safe to Insert Yet 266 Connecting Users and Images 273 Show Me the Image 283 Embedding an Image Is Just Viewing an Image .293 So Which Approach is Best? 298 Chapter 10: Listing, Iterating, and Administrating 301 Some Things Never Change 302 Listing All Your Users 305 Deleting a User 313 Talking Back To Your Users 321 Standardizing on Messaging 331 Integrating Utilities, Views, and Messages 338 iv Contents www.it-ebooks.info Part Four: Chapter 11: Security and the Real World Authentication and Authorization 353 Start with Basic Authentication 354 Abstracting What’s the Same 364 Passwords Don’t Belong in PHP Scripts 367 Passwords Create Security, But Should Be Secure 382 Chapter 12: Cookies, Sign-ins, and Ditching Crummy Pop-ups 389 Going Beyond Basic Authentication 390 Logging In with Cookies 396 Adding Context-Specific Menus 413 Chapter 13: Authorization and Sessions 427 Modeling Groups in Your Database 428 Checking for Group Membership 434 Group-Specific Menus 443 Entering Browser Sessions 447 Memory Lane: Remember that Phishing Problem? 459 So Why Ever Use Cookies? 463 Index 465 Contents v www.it-ebooks.info vi Contents www.it-ebooks.info 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 large-scale 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 current 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 Jasmine Perez (production editor) spends her free time cooking vegetarian meals, listening to her favorite freeform radio station, WFMU, and going on adventures whenever possible Email: jperez@oreilly.com Nan Reinhardt (proofreader) is a freelancer copy editor and proofreader, who is also a writer of romantic fiction She has two novels with her agent at Curtis Brown Literary Agency In between editing gigs, she is busy working on her third book She blogs thrice weekly at www.nanreinhardt.com Email: reinhardt8@comcast.net Ron Strauss (indexer) lives with his wife in northern California at 2,300 feet When not indexing Missing Manual books, he moonlights as a musician (viola and Native American flute) Shelley Powers (technical reviewer) is a former HTML5 working group member and author of several O’Reilly books She is also an animal welfare advocate, working to close down puppy mills in Missouri Website: www.burningbird.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 The Missing Credits vii www.it-ebooks.info Acknowledgments Acknowledgements are always nearly impossible to well Before you can think anyone of substance, the music swells and they’re shuffling you off stage Seriously, before 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’s 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 And then, 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 into the Missing Manual series I won’t forget that call anytime soon And then Nan Barber IM-ed and emailed me through this whole thing 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 a few short weeks Shelley Powers and Steve Suehring were technical reviewers, and they were both picky and gentle That’s about all you can ask Shelley helped me remember to keep the learner front and center, and if you like the longer code listings when things get hairy, she’s the one to thank And Steve 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 And then there’s the vast machinery at O’Reilly It all works, and I don’t know how, really, and I’m OK with that I imagine somewhere Sanders is pulling important levers and Courtney is badgering authors and Laura is angry and in heels and Laurie thinks this all costs too much and Tim is well, Tim is thinking about something important I’m glad for all of them —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 Buying a Home: The Missing Manual by Nancy Conner CSS: The Missing Manual, Second 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 viii The Missing Credits www.it-ebooks.info 464 PHP & MySQL: The Missing Manual www.it-ebooks.info Index Symbols $ (dollar sign) for naming variables, 20 in PHP, 15 in regular expressions, 135–136 %20 (insert a space), 202 32-bit vs 64-bit system (Mac), 65 & (ampersand) for separating multiple request parameters, 202 (angle brackets) in PHP, 15 * (asterisk) in regular expressions, 137 @ (at operator) in PHP, 240–241 \ (backslash) in PHP, 15, 202 in regular expressions, 130–131 ^ (carat) symbol in regular expressions, 133–135 { } (curly braces) in foreach loops, 50 in PHP, 267 || (double pipe) OR operator (PHP), 125 %d type specifier, 277 ?> for ending PHP code, 19, 40 / (forward slash) in regular expressions, 129 \n (line feed character), 139 ( ) parentheses in MySQL commands, 82