PHP&MySQL:The.Missing.ManualPHP MySQLSecond editionthe missing manualThe book that should have been in the boxBrett McLaughlin○ REILLYBeijing Cambridge Farnham Koln Sebastopol TokyoPHP& MySGL: The missing Manual, Second Editionby Brett MclaughlinCopyright C 2013 Brett McLaughlin. All rights reservedPrinted in the united states of americaPublished by o reilly media, In1005 Gravenstein Highway north Sebastopol, Ca 95472O'Reilly books may be purchased for educational, business or sales promotional useOnlineeditionsarealsoavailableformosttitles(http://my.safaribooksonline.com)For more information contact our corporate/institutional sales department: (800)998-9938orcorporateaoreilly.comNovember 2011: First editionNovember 2012: Second editionRevision History for the second edition2012-11-5First releaseSeehttporeillycom/catalog/errata.csp?isbn=0636920024927forreleasedetailsThe missing manual is a registered trademark of o'Reilly Media, Inc. The missingManual logo, and" the book that should have been in the box"are trademarks ofO'Reilly Media, Inc. Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks. Where those designationsappear in this book, and o Reilly Media is aware of a trademark claim, thedesignations are capitalizedWhile every precaution has been taken in the preparation of this book, the publisherassumes no responsibility for errors or omissions, or for damages resulting from theuse of the information contained in it[LSI]SBN:978-1-44932557-2ContentsThe Missing CreditsIntroductionPart One: PHP and MySQL BasicsCHAPTER 1: PHP: What, Why and where?PHP Comes in two flavors Local and remotePHP: Going Local.21Write Your first program38Run Your first program40But where's That Web server?42CHaPTER2: PHP Meets html45Script or HTML?46PHP Talks backRun Php scripts remotely54CHAPTER 3: PHP Syntax: Weird and wonderful61Get Information from a web forr62Working with Text in PHP69The s request variable Is an array83What do you do with user information?90CHAPTER 4: MysQL and sQL: database and language∴..,91What is a databaseInstalling MySQ95SQL Is a Language for talking to databases104Part Two: Dynamic Web PagesCHAPTER 5: Connecting PhP to MySQL119Writing a Simple PhP connection Script......120Cleaning Up Your Code with Multiple files...132Building a Basic SQL Query Runner138CHAPTER 6: Regular Expressions155String Matching, Double-TimeCHAPTER 7: Generating Dynamic Web Pages173Revisiting a Users Information174Planning Your database Tables175Saving a User's Information82Show me the u.190Revisiting(and Redirecting) the Create User Script......208Part Three: From Web Pages to Web applicationsCHAPTER 8: When Things Go Wrong(and They Will)221Planning Your Error Pages223Finding a Middle Ground for Error pages with PHP229Add Debugging to Your Application∴..∴..237Redirecting On Error..∴..∴..............242CHAPTER 9: Handling Images and complexity253Images are Just Files..254nages are for viewingAnd Now for Something Completely Different288CHAPTER 10: Binary objects and Image Loading289Storing different objects in different tables290Inserting a raw Image into a table∴..∴..292Your binary data Isn't Safe to Insert.Yet296Connecting Users and Images303Show me the Image313Embedding an Image ls just viewing an Image...324So, Which Approach Is Best?330CHAPTER 11: Listing, Iterating, and Administrating333Thinking about What You need as an admin.∴.∴...334Listing All Your Users...337Deleting a user345Talking back to your Users351Standardizing on messaging362Integrating Utilities, Views, and messages369CONTENTSPart Four: Security and the real worldCHAPTER 12: Authentication and authorization385Basic authentication386Abstracting What's the Same395Passwords Don' t Belong in PHP Scripts399Passwords Create Security, But Should Be secure413CHAPTER 13: Cookies, Sign-Ins, and Ditching Crummy Pop-Ups419Moving Beyond Basic Authentication420Logging In with Cookies426Adding Context-Specific Menus443CHAPTER 14 Authorization and sessions455Modeling groups in Your database455Checking for group membershipGroup-Specific Menus471Entering Browser Sessions475Memory Lane: Remember That Phishing Problem?..486Why Would you ever Use cookies?489Part Five: AppendixesAPPENDIX A: Installing PHP on Windows without WAMP493APPENDIX B: Installing MySQL Without MAMP or WAMP499Index513CONTENTSThe missing CreditsABOUT THE AUTHORBrett 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 astem, he architects, designs, manages, and implements largscale applications from start to finish with mission-critical implementations and deadlinesOf course, that's all fancy-talk for saying that bretts a geekspending most of his day in front of a computer with his handsflying across a keyboard. Currently, he spends most of his timeworking on NASa projects, which sounds much cooler than it actually is. But heymaybe that satellite overhead really is controlled by php and mysQABOUT THE CREATIVE TEAMNan Barber (editor has been working on the missing manual series since its inception she lives in boston with her husband and various electronic devices emailnanbarberaoreilly.comHolly Bauer (production editor)lives in Ye olde cambridge, Massachusetts, whereshe is an avid home cook, prolific dIYer, and mid-century modern furniture designenthusiast. Email: hollyaoreilly conBob Russell (copyeditor) is a documentation specialist and president of octal Publishing,Inc.,inSalemNewhampshire(www.octalpub.com).Email:bobrusselloctalpub.comBob Pfahler (indexer) is a freelance indexer For the past five years, he has indexedmany computer books as well as biographies, history, and business books. Whenhe is not working he likes to take bike rides in the foothills outside of denver he indexedthisbookasanassociateforPotomacIndexing(www.potomacindexing.com)Roger House(technical reviewer) is a freelance software developer living in northernCalifornia. he has written code in many languages for various kinds of applicationsHe enjoys algorithm design, use of data structures, and applications of mathematicsWeb:www.rogerfhouse.com.Emailrhouse(asonic.netSteve Suehring(technical reviewer is a technical architect with an extensive back-ground finding simple solutions to complex problems. Steve plays several musicalinstruments (not at the same time) and can be reached through his website wwwbraingia orgACKNOWLEDGMENTSAcknowledgments are nearly impossible to do well Before you can thank anyoneof substance the music swells and they re shuffling you off stage. Seriously, apartfrom the writing there' s my wife Leigh, and my kids, Dean, robbie, and AddieAny energy or joy or relaxation that happens during the long writing process filtersthrough those four, and there are never enough royalties to cover the time lost withthem. I suppose it's a reflection of their love and support for me that they re oKwith me writing anywayThere's certainly the writing. Brian Sawyer was the first guy to call me when i becameavailable to write and he called when i was really in need of just what he gave meexcitement about me writing and encouragement that i could write for the missingManual series. I wont forget that call anytime soon and, there's nan barber, whoIM'ed and emailed me throughout the entire process. she showed a really unhealthylevel of trust that wasnt earned and I m quite thankful. especially in the dark days ofearly August, when i had hundreds of pages left to write, in just a few short weeksRoger House and steve Suehring, my technical reviewers were both picky andgentle. That's about all you can ask And steve filled out my php holes. He caughtone particularly nasty issue that i think vastly improved the book. You don 't realizethis, but you owe him a real debt of thanks if this book helps youBrett McLaughlinTHE MISSING MANUAL SERIESMissing Manuals are witty, superbly written guides to computer products that dontcome with printed manuals(which is just about all of them). each book features ahandcrafted index and cross-references to specific pages (not just chapters)Recent and upcoming titles includeAccess 2010: The Missing Manual by Matthew MacDonaldAdobe Edge Animate: The Missing Manual by Chris groverBuying a Home: The Missing Manual by Nancy connerCSS3: The Missing Manual, Third Edition, by david Sawyer McFarlandCreating a Website: The Missing Manual, Third Edition, by Matthew MacDonaldDavid Pogue's Digital Photography: The Missing Manual by david PogueDreamweaver CS5.5: The Missing Manual by david Sawyer McFarlandDroid 2: The Missing Manual by preston grallaDroid X2: The Missing Manual by Preston grallaExce/ 2010: The Missing Manual by matthew MacDonaldFacebook: The Missing Manual, Third Edition by E.A. vander VeerTHE MISSING CREDITS