Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

PHP solutions 2nd edition[a4]
PREMIUM
Số trang
543
Kích thước
30.7 MB
Định dạng
PDF
Lượt xem
866

PHP solutions 2nd edition[a4]

Nội dung xem thử

Mô tả chi tiết

PHP Solutions

Dynamic Web Design Made Easy

Second Edition

David Powers

Download from Wow! eBook <www.wowebook.com>

ii

PHP Solutions: Dynamic Web Design

Made Easy, Second Edition

Copyright © 2010 by DAVID POWERS

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,

electronic or mechanical, including photocopying, recording, or by any information storage or retrieval

system, without the prior written permission of the copyright owner and the publisher.

ISBN-13 (pbk): 978-1-4302-3249-0

ISBN-13 (electronic): 978-1-4302-3250-6

Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1

Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence

of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark

owner, with no intention of infringement of the trademark.

Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street,

6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505,

e-mail [email protected], or visit www.springeronline.com.

For information on translations, please e-mail [email protected], or visit www.apress.com.

Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.

eBook versions and licenses are also available for most titles. For more information, reference our Special

Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales.

The information in this book is distributed on an “as is” basis, without warranty. Although every precaution

has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to

any person or entity with respect to any loss or damage caused or alleged to be caused directly or

indirectly by the information contained in this work.

The source code for this book is freely available to readers at www.friendsofed.com in the Downloads

section.

Credits

Lead Editor:

Ben Renow-Clarke

Technical Reviewers:

Kristian Besley and Jason Nadon

Editorial Board:

Steve Anglin, Mark Beckner, Ewan Buckingham, Tony

Campbell, Gary Cornell, Jonathan Gennick, Michelle

Lowman, Matthew Moodie, Jeffrey Pepper, Frank Pohlmann,

Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade,

Tom Welsh

Project Manager: Anita Castro

Copy Editor:

Heather Lang

Compositor:

Bronkella Publishing, LLC

Indexer:

Toma Mulligan

Artist:

April Milne

Cover Designer:

Anna Ishchenko

Cover Artist:

Corné van Doreen

CONTENTS

iii

Contents at a Glance

Contents at a Glance................................................................................................ iii

Contents.................................................................................................................... iv

About the Author ................................................................................................... xiii

About the Technical Reviewers ...........................................................................xiv

Acknowledgments...................................................................................................xv

Introduction ............................................................................................................xvi

Chapter 1: What Is PHP—And Why Should I Care?............................................... 1

Chapter 2: Getting Ready to Work with PHP......................................................... 9

Chapter 3: How to Write PHP Scripts .................................................................. 29

Chapter 4: Lightening Your Workload with Includes............................................ 69

Chapter 5: Bringing Forms to Life ....................................................................... 103

Chapter 6: Uploading Files ................................................................................... 141

Chapter 7: Using PHP to Manage Files ............................................................... 179

Chapter 8: Generating Thumbnail Images............................................................ 215

Chapter 9: Pages That Remember: Simple Login and Multipage Forms ........ 243

Chapter 10: Getting Started with MySQL.......................................................... 279

Chapter 11: Connecting to MySQL with PHP and SQL .................................... 303

Chapter 12: Creating a Dynamic Online Gallery ................................................. 335

Chapter 13: Managing Content............................................................................. 355

Chapter 14: Formatting Text and Dates ............................................................. 383

Chapter 15: Pulling Data from Multiple Tables ................................................... 415

Chapter 16: Managing Multiple Database Tables ............................................... 431

Chapter 17: Authenticating Users with a Database .......................................... 459

Index....................................................................................................................... 475

CONTENTS

iv

Contents

Contents at a Glance................................................................................................ iii

Contents.................................................................................................................... iv

About the Author ................................................................................................... xiii

About the Technical Reviewers ...........................................................................xiv

Acknowledgments...................................................................................................xv

Introduction ............................................................................................................xvi

Chapter 1: What Is PHP—And Why Should I Care?............................................... 1

How PHP has grown....................................................................................................................................2

How PHP makes pages dynamic..............................................................................................................2

Creating pages that think for themselves................................................................................................4

How hard is PHP to use and learn?.........................................................................................................5

Can I just copy and paste the code?........................................................................................................6

How safe is PHP?......................................................................................................................................6

What software do I need to write PHP? ...............................................................................................6

What to look for when choosing a PHP editor..........................................................................................7

So, lets get on with it . . ..........................................................................................................................8

Chapter 2: Getting Ready to Work with PHP......................................................... 9

Checking whether your website supports PHP....................................................................................9

Deciding where to test your pages.........................................................................................................10

What you need for a local test environment......................................................................................10

Individual programs or an all-in-one package?......................................................................................11

Setting up on Windows ...........................................................................................................................11

Getting Windows to display filename extensions..................................................................................11

Choosing a web server............................................................................................................................12

Installing XAMPP on Windows................................................................................................................12

Installing PHP with the Microsoft Web Platform Installer .....................................................................16

CONTENTS

v

Setting up on Mac OS X..........................................................................................................................19

Installing MAMP ......................................................................................................................................19

Testing and configuring MAMP...............................................................................................................20

Checking your PHP settings (Windows and Mac) ..............................................................................21

Editing php.ini..........................................................................................................................................25

Where to locate your PHP files .............................................................................................................26

Whats next?..............................................................................................................................................27

Chapter 3: How to Write PHP Scripts .................................................................. 29

PHP: The big picture.................................................................................................................................30

Telling the server to process PHP..........................................................................................................30

Embedding PHP in a web page...............................................................................................................31

Storing PHP in an external file................................................................................................................31

Using variables to represent changing values ......................................................................................32

Ending commands with a semicolon ......................................................................................................34

Commenting scripts ................................................................................................................................34

Using arrays to store multiple values.....................................................................................................35

PHPs built-in superglobal arrays ...........................................................................................................36

Understanding when to use quotes........................................................................................................37

Making decisions ....................................................................................................................................39

Making comparisons ...............................................................................................................................41

Using indenting and whitespace for clarity ............................................................................................42

Using loops for repetitive tasks .............................................................................................................42

Using functions for preset tasks............................................................................................................42

Understanding PHP classes and objects ..............................................................................................43

Displaying PHP output ............................................................................................................................44

Understanding PHP error messages......................................................................................................45

PHP: A quick reference ............................................................................................................................47

Using PHP in an existing website...........................................................................................................48

Data types in PHP...................................................................................................................................48

Doing calculations with PHP...................................................................................................................49

Adding to an existing string ....................................................................................................................51

All you ever wanted to know about quotes—and more .........................................................................51

CONTENTS

vi

Creating arrays........................................................................................................................................55

The truth according to PHP.....................................................................................................................57

Creating loops .........................................................................................................................................62

Modularizing code with functions ...........................................................................................................64

PHP quick checklist....................................................................................................................................67

Chapter 4: Lightening Your Workload with Includes............................................ 69

Including code from external files ........................................................................................................70

Introducing the PHP include commands................................................................................................71

Where PHP looks for include files ..........................................................................................................71

Choosing the right filename extension for includes ..............................................................................74

Creating pages with changing content...................................................................................................83

Preventing errors with include files ........................................................................................................92

Choosing where to locate your include files ..........................................................................................98

Adjusting your include_path...................................................................................................................98

Why cant I use site-root-relative links with PHP includes? ...............................................................100

Security considerations with includes .................................................................................................101

Chapter review ........................................................................................................................................101

Chapter 5: Bringing Forms to Life ....................................................................... 103

How PHP gathers information from a form ........................................................................................103

Understanding the difference between post and get ..........................................................................105

Keeping safe with PHP superglobals ...................................................................................................107

Removing unwanted backslashes from form input .............................................................................108

Processing and validating user input..................................................................................................110

Creating a reusable script.....................................................................................................................110

Preserving user input when a form is incomplete................................................................................115

Filtering out potential attacks ...............................................................................................................118

Sending email...........................................................................................................................................121

Using additional email headers safely .................................................................................................122

Keeping spam at bay.............................................................................................................................129

Handling multiple-choice form elements ............................................................................................132

Chapter review ........................................................................................................................................140

CONTENTS

vii

Chapter 6: Uploading Files ................................................................................... 141

How PHP handles file uploads..............................................................................................................142

Checking whether your server supports uploads................................................................................142

Adding a file upload field to a form........................................................................................................143

Understanding the $_FILES array........................................................................................................144

Establishing an upload directory..........................................................................................................146

Uploading files .........................................................................................................................................147

Moving the temporary file to the upload folder.....................................................................................148

Creating a PHP file upload class..........................................................................................................150

Defining a PHP class.............................................................................................................................151

Checking upload errors.........................................................................................................................156

Changing protected properties.............................................................................................................161

Explicitly changing a data type ............................................................................................................166

Preventing files from being overwritten ...............................................................................................166

Uploading multiple files..........................................................................................................................171

How the $_FILES array handles multiple files .....................................................................................171

Using namespaces in PHP 5.3 and later .............................................................................................176

Using the upload class...........................................................................................................................177

Points to watch with file uploads ........................................................................................................178

Chapter review ........................................................................................................................................178

Chapter 7: Using PHP to Manage Files ............................................................... 179

Checking that PHP has permission to open a file ...........................................................................179

Configuration settings that affect file access .....................................................................................180

Creating a file storage folder for local testing......................................................................................181

Reading and writing files........................................................................................................................181

Reading files in a single operation........................................................................................................181

Opening and closing files for read/write operations............................................................................188

Exploring the file system ......................................................................................................................195

Inspecting a folder with scandir().........................................................................................................195

Inspecting the contents of a folder with DirectoryIterator..................................................................196

Restricting file types with the RegexIterator.......................................................................................198

CONTENTS

viii

Accessing remote files..........................................................................................................................203

Consuming news and other RSS feeds................................................................................................204

Using SimpleXML ..................................................................................................................................205

Creating a download link........................................................................................................................210

Chapter review ........................................................................................................................................213

Chapter 8: Generating Thumbnail Images............................................................ 215

Checking your servers capabilities ....................................................................................................216

Manipulating images dynamically.........................................................................................................216

Making a smaller copy of an image ......................................................................................................217

Resizing an image automatically on upload.......................................................................................235

Extending a class..................................................................................................................................235

Using the Ps2_ThumbnailUpload class ...............................................................................................240

Chapter summary....................................................................................................................................241

Chapter 9: Pages That Remember: Simple Login and Multipage Forms ........ 243

What sessions are and how they work...............................................................................................243

Creating PHP sessions.........................................................................................................................245

Creating and destroying session variables .........................................................................................246

Destroying a session ............................................................................................................................246

Regenerating the session ID................................................................................................................247

The “Headers already sent” error .........................................................................................................247

Using sessions to restrict access.......................................................................................................247

Using file-based authentication ...........................................................................................................251

Making passwords more secure...........................................................................................................258

Setting a time limit on sessions..........................................................................................................270

Passing information through multipage forms ..................................................................................273

Chapter review ........................................................................................................................................278

Chapter 10: Getting Started with MySQL.......................................................... 279

Why MySQL? ............................................................................................................................................280

Which version?......................................................................................................................................280

How a database stores information....................................................................................................281

How primary keys work .........................................................................................................................281

Linking tables with primary and foreign keys.......................................................................................282

CONTENTS

ix

Breaking down information into small chunks .....................................................................................283

Checkpoints for good database design...............................................................................................284

Using MySQL with a graphical interface .............................................................................................284

Launching phpMyAdmin........................................................................................................................286

Setting up the phpsols database .......................................................................................................287

MySQL naming rules.............................................................................................................................287

Using phpMyAdmin to create a new database.....................................................................................288

Creating database-specific user accounts .........................................................................................288

Creating a database table.....................................................................................................................291

Inserting records into a table................................................................................................................293

Creating a SQL file for backup and data transfer................................................................................297

Choosing the right data type in MySQL............................................................................................299

Storing text ............................................................................................................................................299

Storing numbers ....................................................................................................................................300

Storing dates and times........................................................................................................................300

Storing predefined lists .........................................................................................................................301

Storing binary data................................................................................................................................301

Chapter review ........................................................................................................................................301

Chapter 11: Connecting to MySQL with PHP and SQL .................................... 303

Checking your remote server setup...................................................................................................304

How PHP communicates with MySQL.................................................................................................305

Connecting with the MySQL Improved extension ...............................................................................305

Connecting with PDO............................................................................................................................305

PHP Solution 11-1: Making a reusable database connector ..............................................................306

Finding the number of results from a query..........................................................................................307

Displaying the results of a query..........................................................................................................310

MySQL connection crib sheet ..............................................................................................................313

Using SQL to interact with a database ..............................................................................................314

Writing SQL queries ..............................................................................................................................314

Refining the data retrieved by a SELECT query ..................................................................................315

Understanding the danger of SQL injection.........................................................................................319

Chapter review ........................................................................................................................................334

CONTENTS

x

Chapter 12: Creating a Dynamic Online Gallery ................................................. 335

Why not store images in a database?...............................................................................................336

Planning the gallery.................................................................................................................................336

Converting the gallery elements to PHP ..........................................................................................339

Building the dynamic elements ............................................................................................................341

Passing information through a query string.........................................................................................341

Creating a multicolumn table ................................................................................................................344

Paging through a long set of records ...................................................................................................347

Chapter review ........................................................................................................................................353

Chapter 13: Managing Content............................................................................. 355

Setting up a content management system .....................................................................................355

Creating the blog database table .........................................................................................................356

Creating the basic insert and update form...........................................................................................357

Inserting new records ...........................................................................................................................359

Linking to the update and delete pages ...............................................................................................363

Updating records...................................................................................................................................366

Deleting records ....................................................................................................................................375

Reviewing the four essential SQL commands ..................................................................................376

SELECT .................................................................................................................................................377

INSERT ..................................................................................................................................................379

UPDATE.................................................................................................................................................380

DELETE .................................................................................................................................................380

Security and error messages ...............................................................................................................380

Chapter review ........................................................................................................................................381

Chapter 14: Formatting Text and Dates ............................................................. 383

Displaying a text extract ......................................................................................................................383

Extracting a fixed number of characters .............................................................................................384

Ending an extract on a complete word.................................................................................................385

Extracting the first paragraph ..............................................................................................................385

Extracting complete sentences ...........................................................................................................387

Lets make a date ...................................................................................................................................390

How MySQL handles dates...................................................................................................................390

CONTENTS

xi

Inserting dates into MySQL..................................................................................................................394

Working with dates in PHP....................................................................................................................399

Chapter review ........................................................................................................................................414

Chapter 15: Pulling Data from Multiple Tables ................................................... 415

Understanding table relationships ......................................................................................................415

Linking an image to an article ...............................................................................................................417

Altering the structure of an existing table............................................................................................417

Inserting a foreign key in a table ..........................................................................................................419

Selecting records from multiple tables.................................................................................................422

Finding records that dont have a matching foreign key .....................................................................427

Creating an intelligent link.....................................................................................................................428

Chapter review ........................................................................................................................................429

Chapter 16: Managing Multiple Database Tables ............................................... 431

Maintaining referential integrity ...........................................................................................................431

Inserting records into multiple tables................................................................................................435

Creating a cross-reference table .........................................................................................................436

Getting the filename of an uploaded image..........................................................................................437

Adapting the insert form to deal with multiple tables ...........................................................................438

Updating and deleting records in multiple tables...........................................................................448

Updating records in a cross-reference table .......................................................................................449

Preserving referential integrity on deletion..........................................................................................452

Creating delete scripts with foreign key constraints...........................................................................456

Creating delete scripts without foreign key constraints .....................................................................457

Chapter review ........................................................................................................................................458

Chapter 17: Authenticating Users with a Database .......................................... 459

Choosing an encryption method .........................................................................................................459

Using one-way encryption .....................................................................................................................460

Creating a table to store users details ................................................................................................460

Registering new users in the database................................................................................................461

Using two-way encryption .....................................................................................................................469

Creating the table to store users details.............................................................................................469

Registering new users ..........................................................................................................................469

Download from Wow! eBook <www.wowebook.com>

CONTENTS

xii

User authentication with two-way encryption......................................................................................471

Decrypting a password .........................................................................................................................472

Updating user details.............................................................................................................................472

Where next? ............................................................................................................................................472

Index: ........................................................................................................................................................ 475

CONTENTS

xiii

About the Author

David Powers is the author of a series of highly successful books on PHP and web development. He

began developing websites in 1994 when—as Editor, BBC Japanese TV—he needed a way to promote his

fledgling TV channel but didnt have an advertising budget. He persuaded the IT department to let him

have some space on the BBCs server and hand-coded a bilingual website from scratch. That experience

ignited a passion for web development that burns just as brightly as ever.

After leaving the BBC in 1999, David developed an online system with PHP and MySQL to deliver daily

economic and political analysis in Japanese for the clients of a leading international consultancy. Since

2004, he has devoted most of his time to writing books and teaching web development.

David is an Adobe Community Professional and Adobe Certified Instructor for Dreamweaver. In 2010, he

became one of the first people to qualify as a PHP 5.3 Zend Certified Engineer.

CONTENTS

xiv

About the Technical Reviewers

Kristian Besley is the lead developer at Beetroot Design (www.beetrootdesign.co.uk) where he develops

web applications, websites, educational interactions and games written mainly in various combinations of

PHP, Flash and Javascript.

He has been working with computers and the web for far too long. He also spends far too much time

hacking and developing for open-source applications - including Moodle - so that they work just so. Health

warning: he has an unhealthy obsession with making his applications super-RSS compatible and overly

configurable.

His past and current clients include the BBC, Pearson Education, Welsh Assembly Government and loads

of clients with acronyms such as JISC, BECTA, MAWWFIRE and - possibly his favourite of all (well, just

try saying it out loud) - SWWETN.

When he isn't working, he's working elsewhere lecturing in Interactive Media (at Gower College Swansea)

or providing geeky technical assistance to a whole gamut of institutions or individuals in an effort to save

them time and money (at his own expense!!!).

He has authored and co-authored a large number of books for friends of ED and Apress including the

Foundation Flash series, Flash MX Video, Foundation ActionScript for Flash (with the wonderful David

Powers) and Flash MX Creativity. His words have also graced the pages of Computer Arts a few times too.

Kristian currently resides with his family in Swansea, Wales and is a proud fluent Welsh speaker with a

passion for pushing the language on the web and in bilingual web applications where humanly possible.

Jason Nadon has ten years experience building and supporting complex web applications. He is an active

member of the web developer community and teaches several classes in his hometown in Michigan. He

has been in the Information Technology field for more than twelve years and holds several industry

certifications. He is currently working as an Infrastructure Manager for a global information company.

Tải ngay đi em, còn do dự, trời tối mất!