“I Picked Up This Book Two Days Ago

Transcription

“I’ve never purchased a betterprogramming book This book provedto be the most informative, easiest tofollow, and had the best examples ofany other computer-related book I haveever purchased. The text is very easy tofollow!”—Nick Landman“This book by Welling & Thomsonis the only one which I have found tobe indispensable. The writing is clearand straightforward but never wastesmy time. The book is extremely welllaid out. The chapters are the rightlength and chapter titles quickly takeyou where you want to go.”—Wright Sullivan, President,A&E Engineering, Inc.,Greer South Carolina“I just wanted to tell you thatI think the book PHP and MySQLWeb Development rocks! It’s logicallystructured, just the right difficulty levelfor me (intermediate), interesting andeasy to read, and, of course, full ofvaluable information!”—CodE-E, Austria“There are several goodintroductory books on PHP, butWelling & Thomson is an excellenthandbook for those who wish to buildup complex and reliable systems. It’sobvious that the authors have a strongbackground in the development ofprofessional applications and theyteach not only the language itself, butalso how to use it with good softwareengineering practices.”—Javier Garcia, senior telecom engineer, Telefonica R&D Labs, Madrid“I picked up this book two days agoand I am half way finished. I just can’tput it down. The layout and flow isperfect. Everything is presented in sucha way so that the information is verypalatable. I am able to immediately graspall the concepts. The examples have alsobeen wonderful. I just had to take sometime out to express to you how pleasedI have been with this book.”—Jason B. Lancaster“This book has proven a trustycompanion, with an excellent crashcourse in PHP and superb coverage ofMySQL as used for Web applications.It also features several completeapplications that are great examplesof how to construct modular, scalableapplications with PHP. Whether youare a PHP newbie or a veteran in searchof a better desk-side reference, this oneis sure to please!”—WebDynamic“The true PHP/MySQL bible, PHPand MySQL Web Development by LukeWelling and Laura Thomson, made merealize that programming and databasesare now available to the commoners.Again, I know 1/10000th of what thereis to know, and already I’m enthralled.”—Tim Luoma, TnTLuoma.com“Welling and Thomson’s book isa good reference for those who wantto get to grips with practical projectsstraight off the bat. It includes webmail,shopping cart, session control, andweb-forum/weblog applications as amatter of course, and begins with asturdy look at PHP first, moving toMySQL once the basics are covered.”—twilight30 on Slashdot

“This book is absolutely excellent,to say the least . Luke Welling andLaura Thomson give the best in-depthexplanations I’ve come across on suchthings as regular expressions, classes andobjects, sessions etc. I really feel thisbook filled in a lot of gaps for me withthings I didn’t quite understand . Thisbook jumps right into the functionsand features most commonly used withPHP, and from there it continues indescribing real-world projects, MySQLintegration, and security issues froma project manager’s point of view.I found every bit of this book to be wellorganized and easy to understand.”—notepad on codewalkers.com“A top-notch reference forprogrammers using PHP and MySQL.Highly recommended.”—The Internet Writing Journal“This book rocks! I am anexperienced programmer, so I didn’tneed a lot of help with PHP syntax;after all, it’s very close to C/C . I don’tknow a thing about databases, though,so when I wanted to develop a bookreview engine (among other projects)I wanted a solid reference to usingMySQL with PHP. I have O’Reilly’smSQL and MySQL book, and it’sprobably a better pure-SQL reference,but this book has earned a place on myreference shelf Highly recommended.”applications with two of the mostpopular open-source Web developmenttechnologies . The projects are thereal jewel of the book. Not only are theprojects described and constructed ina logical, component-based manner,but the selection of projects representsan excellent cross-section of commoncomponents that are built into manyweb sites.”—Craig Cecil“The book takes an easy, step-bystep approach to introduce even theclueless programmer to the language ofPHP. On top of that, I often find myselfreferring back to it in my Web designefforts. I’m still learning new thingsabout PHP, but this book gave me asolid foundation from which to startand continues to help me to this day.”—Stephen Ward“This book is one of few that reallytouched me and made me ‘love’ it.I can’t put it in my bookshelf; I mustput it in a touchable place on myworking bench as I always like to referfrom it. Its structure is good, wordingsare simple and straight forward, andexamples are clear and step by step.Before I read it, I knew nothing of PHPand MySQL. After reading it, I have theconfidence and skill to develop anycomplicated Web application.”—Power Wong—Paul Robichaux“One of the best programmingguides I’ve ever read.”—jackofsometrades from Lahti, Finland“This is a well-written bookfor learning how to build Internet“This book is God . I highlyrecommend this book to anyonewho wants to jump in the deep endwith database driven Web applicationprogramming. I wish more computerbooks were organized this way.”—Sean C Schertell

PHP and MySQLWeb Development Fifth Edition

PHP and MySQLWeb Development Fifth EditionLuke WellingLaura ThomsonHoboken, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCape Town Sydney Tokyo Singapore Mexico City

PHP and MySQL Web DevelopmentCopyright 2017 by Pearson Education, Inc.All rights reserved. No part of this book shall be reproduced, stored in a retrieval system,or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise,without written permission from the publisher. No patent liability is assumed with respectto the use of the information contained herein. Although every precaution has been takenin the preparation of this book, the publisher and authors assume no responsibility forerrors or omissions. Nor is any liability assumed for damages resulting from the use of theinformation contained herein.ISBN-13: 978-0-321-83389-1ISBN-10: 0-321-83389-9Library of Congress Control Number: 2016934688Printed in the United States of AmericaFirst Printing: September 2016TrademarksAll terms mentioned in this book that are known to be trademarks or service marks havebeen appropriately capitalized. Pearson cannot attest to the accuracy of this information.Use of a term in this book should not be regarded as affecting the validity of any trademarkor service mark.Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate as possible,but no warranty or fitness is implied. The information provided is on an “as is” basis. Theauthors and the publisher shall have neither liability nor responsibility to any person or entitywith respect to any loss or damages arising from the information contained in this book.Special SalesFor information about buying this title in bulk quantities, or for special sales opportunities(which may include electronic versions; custom cover designs; and content particular to yourbusiness, training goals, marketing focus, or branding interests), please contact ourcorporate sales department at corpsales@pearsoned.com or (800) 382-3419.For government sales inquiries, please contact governmentsales@pearsoned.com.For questions about sales outside the U.S., please contact intlcs@pearson.com.EditorMark TaberProject EditorLori LyonsProject ManagerDhayanidhiCopy EditorLori EbyIndexerTim WrightTechnical EditorJulie Meloni

Contents at a GlanceIntroduction 1I: Using PHP1 PHP Crash Course112 Storing and Retrieving Data3 Using Arrays53754 String Manipulation and Regular Expressions5 Reusing Code and Writing Functions6 Object-Oriented PHP1011311597 Error and Exception Handling199II: Using MySQL8 Designing Your Web Database9 Creating Your Web Database20922110 Working with Your MySQL Database24711 Accessing Your MySQL Database from the Web with PHP12 Advanced MySQL Administration13 Advanced MySQL Programming291315III: Web Application Security14 Web Application Security Risks33115 Building a Secure Web Application34116 Implementing Authentication Methods with PHP365IV: Advanced PHP Techniques17 Interacting with the File System and the Server18 Using Network and Protocol Functions19 Managing the Date and Time423403379271

viiiContents at a Glance20 Internationalization and Localization21 Generating Images43744922 Using Session Control in PHP23 Integrating JavaScript and PHP24 Other Useful Features475493519V: Building Practical PHP and MySQL Projects25 Using PHP and MySQL for Large Projects26 Debugging and Logging52954327 Building User Authentication and Personalization56128 Building a Web-Based Email Service with Laravel Part IWeb Edition29 Building a Web-Based Email Service with Laravel Part IIWeb Edition30 Social Media Integration Sharing and Authentication31 Building a Shopping CartWeb EditionVI: AppendixA Installing Apache, PHP, and MySQLIndex 615599Web Edition

Table of ContentsIntroduction1I: Using PHP1 PHP Crash Course11Before You Begin: Accessing PHP12Creating a Sample Application: Bob’s Auto PartsCreating the Order FormProcessing the Form14Embedding PHP in HTMLPHP Tags121416PHP StatementsWhitespaceComments161717Adding Dynamic ContentCalling Functions1819Using the date() FunctionAccessing Form VariablesForm Variables20String Concatenation22Variables and Literals23Understanding Identifiers23Examining Variable Types24PHP’s Data TypesType StrengthType Casting242525Variable Variables25Declaring and Using ConstantsUnderstanding Variable ScopeUsing Operators192028Arithmetic OperatorsString Operators2829Assignment Operators29Comparison Operators31Logical Operators32262712

xContentsBitwise OperatorsOther Operators3333Working Out the Form Totals36Understanding Precedence and AssociativityUsing Variable Handling Functions39Testing and Setting Variable TypesTesting Variable Status373940Reinterpreting Variables41Making Decisions with Conditionals41if Statements 41Code Blocks42else Statements 42elseif Statements 43switch Statements 44Comparing the Different ConditionalsRepeating Actions Through Iteration4546while Loops 47for and foreach Loops 49do.while Loops 50Breaking Out of a Control Structure or ScriptEmploying Alternative Control Structure SyntaxUsing declare 51Next522 Storing and Retrieving DataSaving Data for Later5353Storing and Retrieving Bob’s OrdersProcessing FilesOpening a File545555Choosing File Modes55Using fopen() to Open a File56Opening Files Through FTP or HTTP58Addressing Problems Opening Files58Writing to a File61Parameters for fwrite() 62File FormatsClosing a File62635051

ContentsReading from a File65Opening a File for Reading: fopen() 66Knowing When to Stop: feof() 66Reading a Line at a Time: fgets(), fgetss(),and fgetcsv() 67Reading the Whole File: readfile(), fpassthru(),file(), and file get contents() 68Reading a Character: fgetc() 69Reading an Arbitrary Length: fread() 69Using Other File Functions69Checking Whether a File Is There: file exists() 70Determining How Big a File Is: filesize() 70Deleting a File: unlink() 70Navigating Inside a File: rewind(), fseek(), and ftell() 70Locking Files 71A Better Way: Databases73Problems with Using Flat Files73How RDBMSs Solve These ProblemsFurther ReadingNext7474743 Using Arrays75What Is an Array?75Numerically Indexed Arrays76Initializing Numerically Indexed ArraysAccessing Array ContentsUsing Loops to Access the ArrayArrays with Different IndicesInitializing an ArrayUsing Loops798179Multidimensional ArraysSorting Arrays7879Accessing the Array ElementsArray Operators7677798285Using sort() 85Using asort() and ksort() to Sort ArraysSorting in Reverse8786xi

xiiContentsSorting Multidimensional Arrays87Using the array multisort() functionUser-Defined Sorts88Reverse User Sorts89Reordering Arrays8790Using shuffle() 90Reversing an Array92Loading Arrays from Files92Performing Other Array Manipulations96Navigating Within an Array: each(), current(), reset(),end(), next(), pos(), and prev() 96Applying Any Function to Each Element in an Array:array walk() 97Counting Elements in an Array: count(), sizeof(),and array count values() 98Converting Arrays to Scalar Variables: extract() 99Further ReadingNext1001004 String Manipulation and Regular Expressions101Creating a Sample Application: Smart Form MailFormatting Strings101104Trimming Strings: chop(), ltrim(), and trim() 104Formatting Strings for Output105Joining and Splitting Strings with String Functions112Using explode(), implode(), and join() 112Using strtok() 113Using substr() 114Comparing Strings115Performing String Ordering: strcmp(), strcasecmp(),and strnatcmp() 115Testing String Length with strlen() 115Matching and Replacing Substrings with String Functions116Finding Strings in Strings: strstr(), strchr(), strrchr(),and stristr() 116Finding the Position of a Substring: strpos()and strrpos() 117Replacing Substrings: str replace()and substr replace() 118

ContentsIntroducing Regular ExpressionsThe Basics119120Delimiters120Character Classes and TypesRepetition120122Subexpressions122Counted Subexpressions123Anchoring to the Beginning or End of a StringBranching123123Matching Literal Special CharactersReviewing Meta CharactersEscape tting It All Together for the Smart Form127Finding Substrings with Regular Expressions128Replacing Substrings with Regular ExpressionsSplitting Strings with Regular ExpressionsFurther ReadingNext1291291301305 Reusing Code and Writing FunctionsThe Advantages of Reusing CodeCost131131132Reliability132Consistency132Using require() and include() 132Using require() to Include Code133Using require() for Website Templates134Using auto

“The true PHP/MySQL bible, PHP and MySQL Web Development by Luke Welling and Laura Thomson, made me realize that programming and databases are now available to the commoners. Again, I know 1/10000th of what there is to know, and already I’m enthralled.” —Tim Luoma, TnTLuoma.com “Welling and Thomson’s book is a good reference for those who want to get to grips with practical .