1. Trang chủ
  2. » Công Nghệ Thông Tin

FriendSoft foundation PHP 5 for flash

716 538 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề FriendSoft Foundation PHP 5 for Flash
Tác giả David Powers
Trường học Not specified
Chuyên ngành Computer Science / Web Development
Thể loại Sách hướng dẫn / hướng dẫn học
Năm xuất bản 2005
Thành phố United States of America
Định dạng
Số trang 716
Dung lượng 16,34 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Tài liệu về học lập trình web bằng ngôn ngữ PHP cho tất cả mọi người.

Trang 2

Foundation PHP 5

for Flash

David Powers

Trang 3

Lead Editors

Steve Rycroft Chris Mills

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 (pbk): 1-59059-466-5 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 in the United States by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY

10013, and outside the United States by Springer-Verlag GmbH & Co KG, Tiergartenstr 17, 69112 Heidelberg, Germany.

In the United States: phone 1-800-SPRINGER, e-mail orders@springer-ny.com, or visit www.springer-ny.com Outside the United States: fax +49 6221 345229, e-mail orders@springer.de, or visit http://www.springer.de For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA 94710

Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit www.apress.com

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 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

Trang 4

About the Author ix

About the Technical Reviewer x

Acknowledgments xi

Introduction xiii

Chapter 1: Getting Ready to Work with PHP 1

Accessing external data with Flash 2

Choosing the right technology 2

What PHP, Apache, and MySQL have to offer 4

How everything fits together 5

PHP and ActionScript: Distant cousins 7

Installing the necessary software 9

Setting up on Windows 9

Setting up on Mac OS X 27

Setting up your work environment 38

Getting a first taste of the power of PHP 43

Chapter 2: Flash Breaks Free 45

Communicating with external sources 46

Taking first steps in PHP 51

How PHP fits into web design 51

The basic grammar of PHP 52

Sending feedback from Flash by email 64

Progress so far 82

Chapter 3: Calculations and Decisions 85

Performing calculations with PHP 86

Working with arithmetic operators 87

Useful math functions 91

Performing calculations in the right order 93

Combining calculations and assignment 95

Making decisions with PHP 96

Using if… else conditional statements 96

Using comparison operators 97

Trang 5

Testing more than one condition 99

Using switch for long decision chains 102

Using the conditional operator 103

Flash application: A multiconverter 104

Planning the conversion script 105

Building the Flash interface 110

Summing up 127

Chapter 4: Of Strings and Things 129

Manipulating strings with PHP 130

How PHP outputs strings 130

Changing case 135

Working with substrings 138

Modularizing code with functions 144

Understanding where PHP functions run 145

Why roll your own? 146

Understanding how PHP and ActionScript functions handle variables 147

Returning a value from a function 150

Deciding where to put functions 151

Completing the multiconverter script 151

Formatting the main measurement units 152

Handling gallons, pints, and liters 155

Dealing with kilograms, pounds, and stones 160

Handling meters to feet and yards 161

Reviewing the multiconverter project 162

Taking the project further 163

Dealing with user input 164

Trimming leading and trailing whitespace 164

Stripping HTML tags 165

Removing backslashes 165

Using regular expressions to identify patterns 166

Fine-tuning the feedback application 171

A pause for breath 174

Chapter 5: Working Smarter with Arrays and Loops 177

Understanding the basics of arrays and loops 178

Organizing items in arrays 178

Grouping similar items in multidimensional arrays 179

Using loops for repetitive tasks 180

Creating arrays in PHP 180

Indexed arrays: Organizing by number 181

Associative arrays: Organizing by name 184

Array length: Key to understanding the difference between PHP and ActionScript arrays 188

Multidimensional arrays: Nesting arrays 189

Zipping through repetitive tasks with loops 191

Looping through arrays with foreach 191

Trang 6

Using the versatile for loop 192

Simple loops with while and do 194

Breaking out of loops 195

Nesting loops 196

Passing information securely with $_POST 198

Why register_globals is so important 199

Manipulating arrays 201

Slicing and splicing arrays 202

Sorting arrays 206

Building an RSS feed aggregator 209

What an RSS feed does 209

Taking a look inside an RSS feed 210

Parsing an RSS feed with MagpieRSS 212

Displaying the merged RSS feed in Flash 223

Eliminating HTML entities that Flash cannot handle 229

Deploying the feed aggregator on the Internet 230

Progress report 231

Chapter 6: PHP and Databases: Packing Real Power Behind Your Applications 233

Why MySQL? 234

MySQL’s shortcomings 234

MySQL’s strengths 236

Choosing the right version of MySQL 237

Choosing the right license and cost 239

Considering SQLite as an alternative 239

SQLite’s strengths 239

SQLite’s shortcomings 240

Choosing the right database system 240

Installing MySQL on Windows 241

Changing the default table type on Windows Essentials 253

Starting and stopping MySQL manually on Windows 255

Launching MySQL Monitor on Windows 257

Configuring MySQL on Mac OS X 259

Working with MySQL Monitor (Windows and Mac) 261

Creating your first database in MySQL 263

Loading data from an external file 272

Using MySQL with a graphical interface 275

phpMyAdmin: A golden oldie 275

MySQL Administrator and MySQL Query Browser: Smart new kids on the block 280

Looking ahead 282

Chapter 7: Playing with Words 285

Building the game’s graphical elements 286

Using PHP to communicate with the database 291

A touch of class to emulate mysqli on all setups 292

Trang 7

Using the mysqli object-oriented interface 292

Building and using PHP 5 classes 308

Naming and declaring classes 309

Creating class properties 309

Using the constructor function 310

Setting class methods 312

Accessing public methods 313

Refining the word selection with SQL and PHP 313

Building a scoring mechanism that remembers 322

Introducing the Flash SharedObject 323

Other ways to enhance the game 326

Handling database failures 327

Setting different skill levels 330

SQLite: An alternative database system 331

SQLite basics 331

Making sure SQLite has the right permissions 333

Rewriting the Hangman PHP script for SQLite 341

Comparing MySQL and SQLite 343

Ever onward and upward 343

Chapter 8: Creating a User Registration Database 345

Understanding database types 346

Keeping things simple with flat-file databases 346

Gaining greater flexibility with relational databases 348

Understanding MySQL storage formats 353

Choosing the right column type 354

Column types in MySQL 354

Default values and NULL 358

Choosing the right language settings 358

Building a user registration system 359

Registering users with MySQL 359

What if it doesn’t work? 384

Time to take stock 385

Chapter 9: Protecting Your Data with Sessions 387

Keeping track with PHP sessions 388

The Web is a stateless environment 388

How sessions work 390

PHP session basics 392

Using sessions to restrict access 393

Other uses for sessions 405

Summary 405

Trang 8

Chapter 10: Keeping Control with a Content

Management System 407

The four essential SQL commands 408

SELECT 408

INSERT 410

UPDATE 410

DELETE 411

Building a simple content management system 411

Building the content management interface 412

Scripting the application 419

Securing the content management system 466

Adding an extra column to a table 468

A solid foundation has been laid 470

Chapter 11: Working with Dates 473

How ActionScript, PHP, and MySQL handle dates 474

Navigating the minefield of incompatible timestamps 475

Creating a timestamp 477

Formatting dates in PHP 483

Working with dates in MySQL 486

Using dates in calculations 486

Finding and creating records based on temporal criteria 493

Handling dates in user input 494

Formatting dates from text input 495

Checking a date’s validity with PHP 495

Building a Flash date selector for MySQL 498

Nearly there 510

Chapter 12: Working with Multiple Tables and XML 513

Designing the table structure 514

Deciding the basic requirements 514

Normalizing the tables 515

Preparing to build the bookstore database 518

Getting an overview of the project 521

Completing the database structure 523

Creating the content management system 529

Deciding the basic structure 529

Activating the forms with PHP 545

Retrieving data from more than one table 569

Avoiding ambiguous column references 569

Using a full join 569

Using a left join to find an incomplete match 572

Completing the content management system 574

Managing existing book records 574

Deleting records from more than one table 585

Maintaining referential integrity on deletion 587

Updating multiple records 594

Trang 9

Using SimpleXML to parse an XML feed 596

Securing your CMS 601

Displaying the database contents in Flash 601

Getting the database ready 601

Communicating with the database through PHP 602

Building the Flash interface 608

Creating the ActionScript to load results from the database 609

A long road traveled 616

Appendix A: When Things Go Wrong with PHP and MySQL 619

Appendix B: Converting Applications to ActionScript 1.0 641

Appendix C: Installing Older Versions of MySQL on Windows 647

Appendix D: Using Languages Other Than English in MySQL 657

Appendix E: Essential MySQL Maintenance 667

Index 684

Trang 10

David Powers is a professional writer who has been involved in electronic

media for more than 30 years, first with BBC radio and television, and morerecently with the Internet A mild interest in computing was transformedalmost overnight into a passion, when he was posted to Japan in 1987 as a BBCcorrespondent in Tokyo With no corporate IT department just down the cor-ridor, he was forced to learn how to fix everything himself When not tinkeringwith the innards of his computer, he was reporting for BBC radio and televi-sion on the rise and collapse of the Japanese bubble economy

It was back in the UK as Editor, BBC Japanese TV, that David started working with web design Hepersuaded the IT department to let him have free run of a tiny corner of the BBC’s Internet server;and he built and maintained an 80-page Japanese and English website—first, coding by hand, andthen trying all variety of HTML editors, good and bad He decided to set up his own independentcompany, Japan Interface (http://japan-interface.co.uk) in 1999, and he is actively involved inthe development of an online bilingual database of economic and political analysis for Japaneseclients of an international consultancy

This is David’s third book for friends of ED/Apress He co-authored Foundation Dreamweaver MX

2004 (friends of ED, ISBN: 1-59059-308-1) and PHP Web Development with Dreamweaver MX 2004

(Apress, ISBN: 1-59059-350-2) David was also the technical reviewer for the highly successful

second edition of Cascading Style Sheets: Separating Content from Presentation (friends of ED, ISBN: 1-59059-231-X) and Web Designer’s Reference (friends of ED, ISBN: 1-59059-430-4) He has also translated several plays from Japanese, most recently Southern Cross, the final part of a war trilogy

by Keita Asari

Trang 11

Sham Bhangal has written for friends of ED on new media since the imprint’s

inception over five years ago In that time, he has been involved in the writing,production, and specification of just under 20 books

Sham has considerable working experience with Macromedia and Adobe ucts, with a focus on web design and motion graphics Creating books thatteach other people about his favorite subjects is probably the best job he hashad (ignoring the long hours, aggressive deadlines, lost manuscripts, and occa-sional wiped hard drives) If he was doing something else, he’d probably be losing sleep thinkingabout writing anyway

prod-Sham currently lives in the north of England with his longtime partner, Karen

Trang 12

Writing books is a lonely business, pounding away at the keyboard night and day for months on end,but it’s not something you can achieve all on your own Every member of the editorial and produc-tion team deserves thanks for guiding, encouraging, and cajoling me from the initial conceptthrough to completion: Steve Rycroft for planting the original idea for this book in my brain andseeing it through the early stages; Chris Mills and Beckie Stones for putting up with my sometimesinterminable phone calls when I needed help in sorting out the forest from the trees; Nicole LeClercfor her sensitive and perceptive copy editing; plus, of course, all the others.

Special thanks must go to Sham Bhangal for the superb job he has done as technical reviewer, jecting both the text and the code to scrutiny, not only for accuracy, but also for ease of use Onmany occasions, he suggested that something buried deep in a chapter would make more sense ifbrought to the front—and he was right I originally learned ActionScript from Sham’s books, so itwas a particular honor to have him work on my first Flash-related book

sub-I’m also grateful to Al Sparber of Project Seven (www.projectseven.com) for allowing me to adapthis Uberlink CSS concept for the navigation menu in Chapter 12

The unsung heroes to whom we should all be grateful are the development teams behind PHP,MySQL, and Flash Without them, the Web would be a much duller place and there would havebeen no book to write

The biggest thanks of all must go to you, the reader, who makes it all worthwhile If you have justbought this book, I hope it lives up to your expectations If you have borrowed this book, I hope youenjoy it enough to want to go out and buy a copy of your own

Trang 13

Back in 2001, friends of ED published Foundation PHP for Flash It was very popular, but it has long

been out of print, and is now very much out of date It was written in the days of Flash 5, PHP 4.0, andMySQL 3.23 Since then, a lot of water has passed under the bridge The release of ActionScript 2.0 inSeptember 2003 and of PHP 5 ten months later represents a significant milestone in the evolution ofboth languages Both now have a formal object-oriented programming (OOP) syntax, turning themfrom being merely useful tools into essential assets for developing rich, interactive web applications.MySQL, the world’s most popular open source relational database, has also been making rapid strides

It has gone through two major upgrades (the current version is MySQL 4.1), and work is moving apace

on the development of MySQL 5.0, which will add more of the advanced features currently associatedwith much more expensive commercial systems

Consequently, Foundation PHP 5 for Flash is not a new edition of an old book It is completely new

from the first page to the last Although it touches only briefly on OOP, the emphasis is on laying asolid foundation of good coding practice, so that when you move on to a more advanced level, youwon’t have to unlearn any bad habits

Using the latest standards, but remaining

or it’s still stuck in the past with PHP 4 and MySQL 3.23 All the ActionScript is written usingActionScript 2.0, but Appendix B gives advice on how to adapt it to work in Flash MX, and the down-load files (available from www.friendsofed.com) include special versions rewritten in ActionScript 1.0and saved in Flash MX format

Who this book is for

Although this book is part of the Foundation series, it’s not aimed at beginners taking their firststeps with Flash It’s a book about integrating PHP and MySQL with Flash, so you need to be com-fortable moving around the Flash authoring environment Ideally, you’ll also have some experience

of ActionScript You don’t need to be able to recite the contents of the ActionScript Dictionary in

Trang 14

concepts, such as working with loops, arrays, and so on If you have worked through the ActionScript

chapters in Foundation Flash MX 2004 by Kristian Besley and Sham Bhangal (friends of ED, ISBN:

1-59059-303-0), you should have no difficulty

Even if you don’t have much experience of ActionScript, don’t worry Everything is explained indetail Rather than just throw a chunk of code at you and tell you to get on with it, my approach is

to get you to understand what’s happening and why The other main feature of this book is the way

it highlights the differences and similarities between PHP and ActionScript Both languages use thesame basic concepts and structures, but there are often subtle differences that catch out theunwary So, even if your knowledge of arrays is shaky, by the time you have finished Chapter 5, youshould have a firm grasp of how they’re used in both PHP and ActionScript

If you’re looking for a half-dozen lines of code that will solve the problems of the universe, then thisisn’t the book for you PHP is not a point-and-click language You need to roll up your sleeves andcode by hand Similarly, the only way to get the best out of a database—not just MySQL—is to learnthe basics of database design and Structured Query Language (SQL), the language used to interactwith databases But don’t let that put you off Neither PHP nor MySQL is particularly difficult tolearn—that’s one reason they’re so popular Creating the code yourself puts great power and flexi-bility at your fingertips Instead of being shoehorned into a rigid and, perhaps, inappropriate solu-tion, you gain the freedom to create your own solutions

If you’re still using Flash MX, and you recoil in horror at the thought of Expert Mode in the Actionspanel, you’re in for a bit of a shock The dialog boxes in Normal Mode were removed in MX 2004,and it became Expert Mode or nothing Again, don’t worry By the time you’ve worked through acouple of chapters, you’ll realize that typing in the code directly is much faster You’ll also notice that

I don’t sprinkle ActionScript all over the place; most of the time it goes on frame 1 of a layer reservedsolely for ActionScript In the projects toward the end of the book, this produces long scripts thatmay look off-putting at first glance Take a closer look and you’ll quickly realize that they’re made up

of short code blocks Keeping them in one place makes updating and maintenance far, far easier thanplaying “hunt the script” for an action buried in a movie clip nested three levels deep

What if you’re someone with a fair knowledge of PHP, but you’re looking for ways to integrate itwith Flash? Although I don’t set out to teach ActionScript, your knowledge of programming com-bined with reference to the ActionScript Dictionary in Flash (Help ➤ ActionScript Dictionary)should make the transition relatively painless Welcome on board

What you need

First of all you need a copy of Flash Ideally, you should be using MX 2004 or later, but the minimumrequirement is Flash MX (see Appendix B for details on how to convert ActionScript 2.0 to workwith MX) You also need the Apache web server, PHP, MySQL, and a copy of a graphical interface forMySQL called phpMyAdmin—all available for download free of charge over the Internet If you’reusing Mac OS X, Apache and PHP should already be installed on your computer, although you mayneed to enable them Installation isn’t difficult, but the correct configuration seems to cause prob-lems for many beginners, so I’ve given detailed instructions for both Windows and Mac in Chapters 1and 6, highlighting points that seem to trip up many people The size of downloads varies with youroperating system, but some are as big as 20MB, so give yourself plenty of time if you’re on a dialupconnection

Trang 15

The only other software needed is a text editor or, preferably, a dedicated script editor PHP scriptsneed to be saved as plain text files (but with a php filename extension), so Notepad or TextEdit areperfectly adequate Your life will be made a lot easier, though, by a script editor that displays linenumbers and uses syntax coloring I find working in Code view of Dreamweaver MX 2004 the mostconvenient, but other script editors you might wish to consider are TextPad or SciTEFlash (Windows),

or BBEdit (Mac) For more information, including where to obtain these programs, see the section

“Using a script editor to reduce syntax errors” in Appendix A

What you’ll get out of this book

First of all, I hope you get a lot of fun Although the book is project driven, I’ve structured eachchapter around a particular aspect of PHP or working with a database, such as string manipulation,arrays, or joining tables Hands-on projects are a good way to learn new skills, but it can be a night-mare trying to dig out that vital nugget of information if it’s buried deep in a series of step-by-stepinstructions So, wherever possible, I’ve split each chapter into clearly identifiable sections so thatyou can come back much later and use it as a reference book The projects are intended to be chal-lenging, rather than the lightweight examples you find in a lot of beginners’ books By the end ofChapter 12, you will have built the following applications in Flash and PHP:

An online feedback form

A tool that converts 24 different types of weights and measures

An RSS feed aggregator

A word game with a vocabulary of more than 21,000 words

A scoring system that remembers a player’s score on returning to a site

An online registration system

An intelligent Flash component to format and display dates (intelligent enough to know howmany days there are in each month, even in a leap year)

A multitable relational database

Along the way, you’ll also learn how to protect sensitive parts of your website using PHP sessions, aswell as cover the basics of database management, and you’ll take some first steps in OOP with PHP.The focus throughout is on learning how to work with PHP and MySQL, so I’ve deliberately kept thegraphical aspects of design simple, but—I hope—elegant

Mac-friendly, too

I have a confession to make For many years, I worked with a Mac enthusiast who loathed Windows

so much that he rarely began a conversation without cursing Bill Gates and all his works (I knowsome Windows users like that, too, but that’s beside the point.) As a result, he turned me into aMac-hater (sorry) Then, one day, I read lots of good things about Mac OS X and decided to try itout I liked what I saw, but it’s difficult to change the habits of two decades of working with DOSand Windows Still, I’ve tested everything on a PowerBook G4 running OS X 10.3, and I’ve given sep-arate instructions for the Mac wherever appropriate Fortunately, PHP and MySQL are almostentirely operating system–neutral, so if I don’t give specific instructions for the Mac, it’s not because

I have forgotten or am ignoring you

Trang 16

Layout conventions used in this book

I’ve tried to keep this book as clear and easy to follow as possible, so I’ve used the following textconventions throughout

When you first come across an important word, it will be in bold type, then in normal type thereafter.

I’ve used a fixed-width font for code, file names, and any other text you need to type in for yourself.Sections of code that need to be added to an existing script or that deserve special attention areadditionally highlighted like this.

You’ll see menu commands written in the form Menu➤ Submenu ➤ Submenu

When there’s some information I think is really important, I’ll highlight it like this:

When I ask you to enter code that spills onto two lines without using a carriage return, I’ll use a

code continuation character, like this: ➥

Getting help when you’re stuck

We all make mistakes (although I hope there aren’t any in this book!), so it’s useful to know where

to go for help when things don’t turn out as expected Throughout the text, I’ve identified the mostcommon pitfalls, but if the answer isn’t there, the first place to look for it is this book’s page on thefriends of ED website (www.friendsofed.com/books/1590594665/index.html) Check to see if anyerrata or updates have been posted The download files are also provided to help you troubleshootproblems If the download file works, but not yours, it’s a clear sign that there’s a mistake in yourcode Finding it is just a matter of searching patiently

If you still draw a blank, go through the troubleshooting steps outlined in Appendix A, and makesure that your system is using versions no earlier than the ones used by me and the friends of EDtechnical team during testing All the code in the book has been tested on Windows 2000, Windows

XP Pro, and Mac OS X Panther, using the following versions:

PHP: 4.3.4, and all versions from 5.0.0 through 5.0.3

MySQL: 3.23.38, 4.0.20, 4.0.21, and all versions from 4.1.5 through 4.1.9

Apache: 1.3.33, 2.0.40, and 2.0.46

phpMyAdmin: 2.5.5 and 2.6.0

This is very important stuff—don’t skip it!

Support for PHP 5 on versions of Mac OS X prior to 10.3 appears to be very thin on the ground If you are running Jaguar or earlier, you will probably be restricted to using PHP 4 Most of the code in this book will run on PHP 4, but the only Mac testing has been done

on Panther.

Trang 17

If the answer still eludes you, then post a question in the friends of ED support forums atwww.friendsofed.com/forums Try to give a brief description of the problem; indicate which version

of Flash, PHP, and MySQL you are using; and note any remedies that you have tried, but failed.Someone, maybe even me, should soon be along to share the misery—and hopefully provide ananswer that puts a smile back on your face

Stop the presses: Changes to MySQL 4.1.9

The development team at MySQL, never slouches at any time, were particularly hyperactive duringthe last few months of this book being written I managed to incorporate all the relevant changesinto the main text, but two more were announced in January 2005, after Chapters 1 and 6 hadalready been typeset

New filename for the Windows Essentials installer

The name of the installation file for MySQL Windows Essentials has

been changed Instead of mysql-4.1.x-essential-win.msi, it is now

mysql-essential-4.1.x-win32.msi (The value of x will depend on

the number of the latest release.) The installation instructions in

Chapter 6 are otherwise unaffected

New MySQL startup method for Mac OS X 10.3

The changes affect steps 3 and 4 of the instructions in the section titled “Installing MySQL on

Mac OS X” in Chapter 1, but they do not apply to Mac OS X 10.2 (Jaguar).

When the DMG file is mounted on your desktop, you should see something similar to the imageshown here It includes an extra icon labeled MySQL.prefPane As of late January 2005, the ReadMe.txtfile had not been updated to reflect the changes, so it’s not clear whether MySQLStartupItem.pkg willcontinue to be included in later versions, as it no longer seems to be necessary

Even if you have the most up-to-date versions on your local computer, your applications could fail when uploaded to a remote server that uses an older configuration The PHP

Database classes in Chapter 7 are designed to get around these incompatibilities, by

enabling the same code to work regardless of server configuration, so make sure you upload the correct one.

Trang 18

Double-click the icon of the PKG file that begins with mysql-standard-4.1.x and follow the onscreeninstructions to install MySQL When installation is complete, drag the MySQL.prefPane icon ontoSystem Preferences, either in your Dock or in Finder ➤ Applications This will open a dialog box ask-ing if you want to install it (see image below) Select whether you want to install it just for yourself

or for all users, and then click Install

When the MySQL preference pane has been installed, it will open and should show you that MySQLserver is running The preference pane (as shown in the following image) is self-explanatory It notonly provides a convenient Mac-friendly way of starting and stopping MySQL, but also gives you theoption to start MySQL automatically whenever your computer starts up

Trang 19

Close the preference pane in the normal manner by clicking the close button at the top left of thepane To access it again, open System Preferences The MySQL icon will be at the bottom of theSystem Preferences window in the Other section.

Continue with the installation instructions from step 5

If you have installed the MySQL preference pane, always use this method to start and stop MySQL instead of the instructions in the main text of the book This applies to Mac

OS X only The Windows instructions are not affected.

Trang 21

What this chapter covers:

Expanding Flash’s horizons by linking to external data sources

Choosing the appropriate server-side technology

Examining similarities and differences between PHP and

ActionScript

Installing Apache and PHP

Testing the installation

Setting up your work environment

GETTING READY TO WORK WITH PHP

Trang 22

Flash is fun It’s also extremely powerful Its power lies not only in its incredible animationcapabilities, but also in ActionScript With the release of Flash MX 2004, ActionScript wasupgraded to version 2.0 and became a fully object-oriented programming (OOP) languagewith support for classes, inheritance, interfaces, and other common OOP concepts Whetheryou’re making your first personal website, creating immersive online games, or building a seri-ous business site, Flash offers a rich development environment.

Yet, in spite of its power, Flash on its own has a severe limitation: the need to embed virtually

all content and processing logic within the same medium as the user interface Even the mostminor change means republishing and uploading a new version of the Flash movie Sensitivecontent is easily extracted by anyone with a decompiler, several of which are freely available.Most important of all, even with the rapid spread of broadband, download times restrict theoptimum size of a movie and therefore the amount of information it can contain Fortunately,all these limitations are easily overcome by linking your SWF movie to an external data sourcesuch as a database or RSS feed That’s what this book is all about, using the latest version ofthe most popular open source server-side technology, PHP By the end of this chapter, youshould understand how PHP interacts with ActionScript, and you will have installed PHP andthe Apache web server on your development computer (By the way, if you’re not sure what anRSS feed is, it’s one of those online news feeds that seem to be popping up all over the placethese days Take a quick peek at “What an RSS feed does” in Chapter 5, where you’ll be work-ing with two of them.)

Accessing external data with Flash

A Flash movie—the SWF file—is frequently its own self-contained world Everything is therewithin the one file: graphics, timeline animations, and ActionScript functions to control themovie and respond to events initiated by the user The more you have going on withinthe movie, the bigger the file gets To get around this problem, you can load other SWF or JPGfiles into the main movie only if and when required Although this can be regarded as access-ing external data, it’s extremely limiting Everything has to be fixed in advance and scriptedinside the main movie Real flexibility comes only once you connect to an external database,news feed, or similar source of independent data This makes possible such things as onlinereservation systems, news sites, or online forums, all built in Flash And it’s not just a one-wayprocess Once you’ve tied up with a server-side technology, you can capture user input, insert-ing it into a database or sending it across the Internet through email By tying up Flash withPHP, you open up a whole new range of possibilities and rich Internet applications—not justfixed sources of information or entertainment, but ones that offer real interactivity withthe user

Choosing the right technology

There are three ways of communicating between a Flash movie and an external data source:Flash Remoting

Web servicesDirect interaction with a server-side technology, such as ASP, ASP.NET, ColdFusion,

or PHP

Trang 23

Flash Remoting is a proprietary technology developed by Macromedia, the makers of Flash Its

major advantages are speed and the ability of Flash to handle external data as native

ActionScript objects Its major disadvantage is that it requires the installation of a Flash

Remoting Server at a cost of approximately $1,000 per CPU

Flash MX 2004 Professional introduced the concept of connecting to web services using

Simple Object Access Protocol (SOAP) or XML through specialized data components This led

many developers to believe the curtain was coming down on Flash Remoting However, the

Flash web services approach is often slower than Flash Remoting, and it’s far from clear

whether these technologies will continue to exist side by side, or whether one will prevail

For an in-depth analysis of the advantages and disadvantages of the two methods, see

www.macromedia.com/devnet/mx/flash/articles/ria_dataservices.html

The third method—direct interaction with Flash using a server-side technology—should

not be regarded as “second best” or inferior in any way The Ujiko search engine at

www.ujiko.com/flash.php is built entirely in Flash, and it displayed the results shown in

Figure 1-1 just as quickly on a broadband connection as the same search on Google or Yahoo

did using ordinary HTML pages Flash is used not simply to give the search engine a “pretty

face,” but also to add extra functionality through using the Flash SharedObject to enable you

to refine your searches and set individual preferences As you hover your mouse pointer over

each result, a trash can and a heart appear on either side Choosing the trash can or the heart

removes the result from the list or adds it to your favorites, respectively, helping to refine

fur-ther searches A context-sensitive list on the right side of the page presents furfur-ther keywords to

help burrow further down and filter the results until you find what you want Creating such a

rich user experience with a standard HTML interface would be very difficult, if not impossible

Trang 24

Arguments of almost religious intensity rage over whether one server-side technology is rior to the rest, but I’m not going to be drawn down that path Each has its merits anddrawbacks, and all do just about the same with equal efficiency You have to choose one, andthe choice for this book is PHP in conjunction with the Apache web server and the MySQLrelational database system.

supe-What PHP, Apache, and MySQL have to offer

Several factors stand behind the decision to choose this particular combination:

Cost: They’re free While this is an obvious attraction to individuals on a limited

budget, don’t be put off by the thought that “you get what you pay for.” The release ofPHP 5 in mid-2004 brought full object-oriented capability to the language, as well asgreatly improved methods of handling XML MySQL is used by many leading organiza-tions, including NASA, the U.S Census Bureau, Yahoo!, and the New York StockExchange The fact that more than two out of every three web servers run on Apachespeaks for itself

Open source: As open source technologies, all three benefit from a rapid upgrade

pol-icy based on need rather than commercial pressures If a bug or security risk is fied, the input of many volunteers helps the core development teams solve anyproblems rapidly Future versions are available for beta testing by anybody who wants

identi-to take part, and they aren’t declared stable until they really are The same thrivingcommunity offers assistance and advice to newcomers and experienced programmersalike

Cross-platform capability: PHP, Apache, and MySQL all work on Windows, Linux, and

Mac OS X You can develop on your personal computer and deploy exactly the samecode on the production server, even if it’s running on a different operating system

Security: Although it is impossible to predict future developments, Apache servers are

rarely targeted by virus attacks Sensitive content can also be stored more securely in adatabase, with access restricted through PHP session control (this is the subject ofChapter 9)

Widespread use: Both PHP and Apache are the most widely used technologies in their

respective spheres A regular survey by Netcraft (http://news.netcraft.com/archives/web_server_survey.html) shows that Apache has consistently maintained a marketshare in excess of 60% of all web servers In November 2004, it stood at more than67%—more than three times that of Windows-based servers PHP availability seems tomarch on ever upward; in late 2004, it was in use on nearly 17 million domains Andaccording to the MySQL website (www.mysql.com), MySQL is the world’s most popularopen source database, with more than 5 million active installations in late 2004

The Flash SharedObject offers functionality very similar to cookies by storing information

on the user’s local hard drive However, the SharedObject is much more powerful and can store up to 100KB of information Like cookies, though, the SharedObject can be disabled

by the user You’ll use the SharedObject to store a player’s score in Chapter 7.

Trang 25

One thing missing from that list is “ease of learning.” That’s not because they’re difficult—far

from it All are relatively easy to pick up, but they do require a bit of effort on your part If you

have experience with other programming languages, your progress is likely to be much faster

than a complete beginner This book is designed to ease your progress, whatever your level of

expertise

How everything fits together

To understand how to work with PHP, Apache, and MySQL, it helps to know how they interact

with each other and the role they play in bringing greater data-processing power to Flash

movies As noted before, Flash movies are frequently self-contained A single request from a

web browser is sent to the remote server, resulting in the SWF movie being downloaded to

the client computer Thereafter, all interaction between the user and the Flash movie is

conducted locally on the user’s computer, as illustrated in Figure 1-2 Normally, the only times

further requests are made to the remote server are when other movies, images, or

predeter-mined assets are loaded into the main movie

Figure 1-2 Once a Flash movie has been downloaded, all interaction with it is

normally conducted entirely on the client computer

One final point in favor of PHP: although Macromedia does not support Flash Remoting

with PHP, a project called AMFPHP ( www.amfphp.org) is developing an open source

alternative that enables objects in PHP to be recognized as objects by ActionScript At

the time of this writing, the project was at an advanced stage, but still subject to

con-siderable change Although this book touches only briefly on PHP objects, the

funda-mental knowledge contained in these pages will be essential to anyone contemplating

exploring AMFPHP in the future The AMF in the project’s name, by the way, refers to

Action Message Format, the Macromedia protocol used in Flash Remoting.

Trang 26

When you add PHP to the equation, what happens depends on what you want to do In manycases, the Flash movie will be downloaded in exactly the same way as illustrated in Figure 1-2.There is no interaction with PHP until the user triggers an event that calls a PHP script This isthe case with the application you’ll build in the next chapter—a feedback form that uses PHP

to format user input and email it to your mailbox If the user decides not to use the form, thePHP script will never be called In other cases, the Flash movie calls a PHP script as soon as itloads into the client computer, and what appears on the screen is determined by the result ofthat script For instance, the headlines on a news site are likely to be drawn from a databaseand will be different each time someone visits the site At other times, the changing contentdepends on user input, as with the Ujiko search engine shown in Figure 1-1 The sequence ofevents is depicted in Figure 1-3

Figure 1-3 A diagrammatic representation of what happens when a Flash movie makes a request to PHP

The words client and server tend to get bandied around a lot when talking about

data-bases and technologies like PHP A server can mean either a computer or a program on a computer that responds to requests from clients (or users) For instance, your website is more than likely hosted on a remote computer known as a server Running on that com- puter will be a web server—a program, such as Apache, that sends web files to any client computer that requests them To be able to work with databases, you also need a database server, which is another program that responds to requests to either store or retrieve infor- mation from the database For development purposes, it’s normal to install both a web server and database server on your local computer These are simply programs that you install like any other—and they do not involve the need to buy any extra hardware.

Trang 27

1.The client computer sends a request to the web server (normally Apache).

2.The server delivers the Flash movie

3.If the Flash movie sends a request to a PHP script (either automatically through

ActionScript when initially loading or in response to user interaction), the web server

passes the script to the PHP engine for parsing

4.If the PHP script initiates a database query, a request is sent to the MySQL server

5.The results of the database query are sent back to the PHP engine for processing

6.The web server sends the processed data back to the client

7.The Flash movie reacts in accordance with the data received

There’s a lot going on, and this process can be repeated many times as the user interacts with

the movie Sometimes all seven stages of this process are required At other times, PHP may

simply do all the processing itself without having to query the database Although it sounds

complicated, PHP, MySQL, and Apache can search through many thousands of records in a

frac-tion of a second, so the user may be totally unaware of anything going on in the background

The biggest delay is often caused by a slow Internet connection or network bottlenecks

As Figure 1-3 shows, Apache, PHP, and MySQL are frequently located on the same computer

(although in large operations, they may be distributed across several) Apache and MySQL are

daemons (what Windows calls services) that run unobtrusively in the background, consuming

very few resources, and that are ready to spring into action whenever a request comes in The

most efficient way of running the PHP engine is as an Apache module, and that’s the way you’ll

install it later in the chapter First, though, let’s take a look at the similarities and differences

between PHP and ActionScript

PHP and ActionScript: Distant cousins

PHP and ActionScript both trace their roots back to the mid-1990s The first version of PHP

appeared in 1995, and JavaScript (on which ActionScript is closely based) followed a year later

ActionScript didn’t actually emerge until the release of Flash 4 in 1999, and it underwent

signif-icant changes with each subsequent version of Flash, culminating with a major version upgrade

to ActionScript 2.0 in September 2003 PHP underwent fundamental changes with the release

of version 4 in 2000, followed by a major, evolutionary upgrade to version 5 in July 2004

One of the main driving forces behind the great upheavals in the way ActionScript has evolved

has been Macromedia’s commitment to compliance with ECMAScript In spite of its name

sounding like a rather unpleasant skin disease, ECMAScript is a universally recognized standard

set by ECMA International (www.ecma-international.org) (The organization was originally

called the European Computer Manufacturers Association [ECMA], but since 1994 it has been

known as ECMA International, the European association for standardizing information and

communication systems.) ECMAScript is the standard behind JavaScript, making it easier for

programmers to migrate their skills from one language to another PHP follows no

interna-tionally recognized standard (other than itself), but both PHP and ActionScript can now be

considered mature programming languages They will continue to evolve, but the highly

dis-ruptive changes of the previous few years are likely to be a thing of the past That means the

methods taught in this book should continue to be of relevance even when a new version of

Trang 28

The common heritage shared by PHP and ActionScript is that both have been strongly enced by the classic C programming language As a result, they share a lot of structures incommon The syntax of conditional statements using if, else, and switch is almost identical.They also share the same methods of looping through repetitive processes using while andfor Virtually all the arithmetic and conditional operators are the same, too Don’t worry ifyou’re not familiar with these; everything will be explained as the book progresses.

influ-Another feature they used to have in common was loose typing This will be explained in

more detail in Chapter 2, but it basically relieves the developer of the need to decide inadvance whether to use a number or a string (text) in a particular situation, because the lan-guage automatically chooses what it thinks is most appropriate That has changed with theintroduction of ActionScript 2.0; although you can still create scripts that use loose typing, it’s

no longer recommended, and this book adheres to strict typing throughout PHP 5, on theother hand, remains a loose-typed language, with one exception: the new OOP model in PHPallows developers to enforce strict typing in classes

Although these many similarities speed up the learning process, PHP and ActionScript are verydifferent, and it takes a bit of adjustment to get used to the differences Throughout the book,I’ll highlight those differences most likely to catch you out The thing most likely to trip you up

is the need to prefix all variables in PHP with a dollar sign ($) When moving back and forthbetween ActionScript and PHP, it’s easy to leave it out, but doing so will bring your PHP scripts

Variables Declared with var keyword No keyword, except in

No distinguishing prefix classes

Always prefixed with $Variable typing Strict (ActionScript 1.0 was Loose, except in classes

loose typed)Case sensitivity Yes (ActionScript 1.0 was not Yes

case sensitive)

(Continued)

ActionScript 2.0 is supported by Flash Player 6, so there is no reason to avoid adhering

to strict typing, unless you need to support older versions If you are using Flash MX, though, you will need to adapt the scripts by removing the datatype declarations (see Appendix B for details) The download files for this book also contain versions compati- ble with Flash MX, so you can always check your code against them if you get stuck.

Trang 29

Feature ActionScript PHP

Concatenation operator Plus sign (+) Dot or period (.)

OOP Fully object-oriented Not object-oriented, but

has extensive OOPcapabilities

Built-in functions Applied as object methods Applied directly by passing

through dot notation variable as argument (e.g., myVar.toUpperCase()) (e.g., strtoupper($myVar))

User-defined functions Yes Yes

Callback functions Yes Anonymous functions can

be created but are rarelyused

Don’t worry if you’re not familiar with some of this terminology All will be explained in good

time Things will become a lot clearer (I hope!) once you have Apache and PHP installed

Installing the necessary software

As I mentioned earlier, it’s normal for development purposes to install a web server and

data-base server on your local computer This avoids the need to constantly upload files to your

website for testing In effect, what you’re doing is re-creating the setup shown in Figure 1-3 on

a single computer This involves no extra hardware, and it doesn’t require a particularly

high-spec computer, although the more processor power and memory you have, the better

The instructions for Windows and Mac OS X are completely different, so this is a parting of the

ways I’ll deal with Windows first Mac OS X users should skip ahead to the section titled

“Setting up on Mac OS X.”

Setting up on Windows

Some people are so terrified of installing programs not originally designed for Windows that

they freeze at the thought of having to do any manual configuration and will desperately seek

a precompiled package that bundles Apache, PHP, and MySQL together If you have the skill to

work with ActionScript, installing and configuring this trio should present few, if any,

difficul-ties A precompiled package robs you of a great amount of control You may not get the most

up-to-date version of each program, and many people have reported problems uninstalling

some packages when things go wrong I strongly recommend using only the individual

pro-grams directly from their source, and I’m here to guide you through the process

If you’re using Windows 2000 or later, make sure you’re logged on as an Administrator

Trang 30

Getting Windows to display filename extensions

By default, most Windows computers hide thethree- or four-letter filename extension, such as.doc or html, so all you see in dialog boxesand Windows Explorer is thisfile, instead ofthisfile.doc or thisfile.html The ability to seethese filename extensions is essential for installingthe necessary software for this book

If you haven’t already enabled filename extensions

on your computer, open My Computer (it’s on theStart menu on some systems and on the desktop as

an icon on others) Then from the menu at the top

of the window, choose Tools ➤ Folder Options ➤View Uncheck the box marked Hide extensions forknown file types, as shown in Figure 1-4 Click OK

I recommend you leave your computer permanently

at this setting, as it is more secure— you can tell if avirus writer has attached an EXE or SCR executablefile to an innocent-looking document It will alsomake changing HTML files to PHP ones a lot easierwhen you come to do so later in the book

Which version of Apache?

Apache is currently available in two versions: the 1.3 series and the more recent 2 series (firstreleased in 2002) When you visit the Apache site, you will notice it describes the 2 series as

“the best available version” while the 1.3 series is simply “also available.”

You naturally want the best—we all do The more important question is, which version isbetter for the job? As of late 2004, the PHP documentation still contains a warning against

using PHP on Apache 2 in a production environment A full explanation can be found at

www.php.net/manual/en/faq.installation.php#faq.installation.apache2, but it basicallyboils down to the fact that some of the code libraries that PHP relies on cause unpredictablebugs in Apache 2’s threaded environment What makes the choice for Windows users moredifficult is that Apache 2 performs much better on Windows

Technically, the 1.3 series is the safer option; is recommended by Rasmus Lerdorf, the creator

of PHP; and is still being updated by the Apache development team However, I have been ning PHP on both Apache 1.3 and 2 on Windows computers for a long time without any prob-lems My advice, therefore, is to find out which version of Apache is being used by yourhosting company or remote server, and to install that on your local computer It makes sense

run-to replicate the setup on your website as closely as possible on your local testing computer.That way, you get a much better idea of what to expect when you finally deploy your PHP-driven applications on the Internet

The instructions here are based on Apache 1.3, but note any important differences if youdecide to opt for Apache 2

Figure 1-4 Setting Windows so that it automatically

displays the extension on all filenames

Trang 31

1.Go to http://httpd.apache.org/download.cgi Scroll down to the section for Apache

1.3.xx, as shown in Figure 1-5, and select the file marked Win32 Binary The download

for Apache 1.3 is approximately 5MB; for Apache 2, it is 6.4MB Save the file to a

tem-porary folder on your hard disk

Figure 1-5 Selecting the Windows download for Apache 1.3.xx

2.Open the folder where you downloaded the Apache installer Double-click the icon

A wizard will appear to take you through the installation process

Installing Apache

Trang 32

3.Click Next to continue the installation The first thing to appear is the Apache Licenseagreement Read the conditions and terms of use, select the Accept terms radio but-ton, and click Next.

4.The following screen contains useful information about Apache Read it If you’re usingWindows XP, don’t worry if XP isn’t listed as being supported by Apache 1.3—it worksjust fine Click Next

5.Next is the Server Information screen, as shown in Figure 1-6 This is where you enterthe default settings for your web server In the Network Domain and Server Namefields, enter localhost, and in the last field, enter an email address The localhostaddress tells Apache you will be using it on your own computer The email addressdoes not need to be a genuine one It has no bearing on the way the program runs and

is normally of relevance only on a live production server

Figure 1-6 This is the most important dialog box in the Apache

installation process

6.If you are running Windows NT, 2000, or XP Professional, select the Run as a service forAll Users option That way, Apache runs as a service in the background and you don’tneed to worry about starting it If you are running Windows 98, ME, or XP Home, selectthe Run when started manually option because you will be unable to run Apache as aservice and must manually start it each time Click Next

7.Select the Complete option (as shown in Figure 1-7) This also installs the Apache umentation on your local computer Click Next to continue

doc-8.Specify the location where Apache will be installed The default location, C:\ProgramFiles\Apache Group, is fine Click Next and Install to finish the Apache installation

Trang 33

Figure 1-7 Choose the complete installation.

9.That completes the first part of Apache installation process Check that Apache is

run-ning by operun-ning your browser and entering http://localhost/ in the address bar If all

went well you should see the default Apache test page in your browser, as shown in

Figure 1-8

If you are running a version of Windows that requires Apache to be started manually,

choose Start➤ Programs ➤ Apache HTTP Server ➤ Start Apache in Console This will

open a Command Prompt (DOS) window, which must be kept open the entire time you

are using Apache Click the icon in the top-right corner to minimize the window to

your taskbar

Trang 34

10.If you get an error message, check that the server is running You can do this by ing Apache HTTP Server ➤ Control Apache Server from your program menu andselecting Start If you don’t have the Control Apache Server option on your menu, andyou are running Windows 2000, XP Professional, or NT, open the Windows ControlPanel, and then double-click Administrative Tools followed by Services HighlightApache and click Start, as shown here:

select-You need to make some manual changes to the Apache configuration file, but before you do

so, you must install PHP

Downloading and installing PHP

Forgoing the luxury of a Windows installer means you have to roll up your sleeves a bit, and

do some manual configuration, but the process is very straightforward It also means youknow exactly what is happening to your system files, because you are in charge—not ananonymous installer program There are quite a few steps involved, so give yourself plenty oftime, and you should have no problems

1.Go to www.php.net/downloads.php and select the Windows binaries ZIP file for the est stable version of PHP At the time of this writing, it was PHP 5.0.3 Make sure youchoose the right file The version you need should be marked PHP 5.x.x zip package,

lat-and it’s about 7.5MB You do not want the PHP Windows installer This runs PHP in a

very restricted way and is not suitable for the projects in this book

These instructions are for a completely new installation of PHP The recommended method of installing PHP on Windows changed in August 2004, and it no longer involves copying DLL files and the configuration file php.ini to the Windows system

folders If PHP has never been installed on your computer, simply follow the instructions.

If you are upgrading an earlier version of PHP, you need to remove any PHP related files from your main Windows folder ( C:\WINDOWS or C:\WINNT, depending on your system)

and the system32 subfolder Changing the contents of the Windows system folders is

not to be undertaken lightly, so I suggest that, rather than just deleting them, you cut and paste them to a temporary folder Then, if anything goes wrong, you can easily restore them The PHP files you need to remove are php.ini (in the main Windows

folder) and php4ts.dll or php5ts.dll in the system32 subfolder You should also

remove any other PHP-related DLL files from the system32 subfolder They are easy to

recognize because they all begin with php.

Trang 35

When you click the download link, you will be presented with a list of mirror sites.

Choose the one closest to your location, and download the ZIP file to a temporary

folder on your hard disk

2.Unzip the contents of the ZIP file to a new folder called C:\php5 You can choose a

dif-ferent location, but this is where PHP will be run from, so you will need to substitute

the name of your new folder in later steps The instructions given here should be

suffi-cient, but if you run into difficulties, there are more details in the text file called

install.txt in the new folder you have just created

Trang 36

3.Locate the file php.ini-dist in the same folder, copy it, and rename the copy php.ini.This is the main configuration file for PHP, which you need to edit slightly to get every-thing running correctly You should now be able to open php.ini by double-clicking itsicon It will open as a plain text file in Notepad.

You may find it easier to open php.ini in a dedicated script editor such as TextPad orSciTEFlash instead, because the file contains more than 1,000 lines Most script editorshave a feature that allows you to display line numbers, which will make finding the rel-evant sections much easier (PHP is under constant development, so the line numbersgiven in the following steps should be taken only as a rough guide Also note that the

line numbers shown in the following screenshots are not part of php.ini; they have

been generated by a script editor.)All lines that begin with a semicolon (;) are treated as comments, so make sure all thechanges you make in the following steps are to actual configuration settings and not tocomments

4.Scroll down (or use a search facility—C TRL +F in Notepad and SciTEFlash or F5 in

TextPad) until you find the following line (around line 288):

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICTChange it to

error_reporting = E_ALL

This sets error reporting to the highest level, and it will help you debug your PHPscripts so they don’t cause problems for your Flash movies As the following screenshotshows, this is one of the cases where there is an identical line in a comment about 12lines above Make sure you edit the second one (marked here with an arrow), whichdoes not begin with a semicolon

PHP comes with two files that can be used as the basis for php.ini:

php.ini-dist and php.ini-recommended If you’re wondering why I didn’t

tell you to use the “recommended” version, it’s because it contains much stricter settings and is designed for production servers The settings in

php.ini-dist are better suited to a development environment.

Trang 37

5.About seven lines further down, there should be a setting for display_errors Make

sure it looks like this:

display_errors = On

This should be the default setting If it’s set to Off, check that you didn’t use

php.ini-recommended by mistake It’s important to be able to see the output of any

error messages during development, although their display should be turned off when

you deploy PHP pages live on the Internet

6.As you scroll down, you will notice a setting called register_globals in the Data

Handling section (around line 385):

register_globals = Off

This is the default setting, and under no circumstances should you be tempted to alter

it Even though turning register_globals on makes PHP scripts easier to run, it also gives

crackers an open invitation to your site A lot of scripts you will find online and in older

books were written on the assumption that register_globals was On, so they no longer

work I will show you later how to adapt such scripts and keep your site more secure

7.A few lines further down (around line 404), you will see this line:

magic_quotes_gpc = On

Opinions are divided as to whether this setting should be On or Off When On, it

auto-matically inserts backslashes in front of quotes to prevent them from terminating user

input prematurely Some developers dislike this and prefer to control everything

them-selves The best advice I can offer is to leave the setting On for the time being, and

check the setting on the production server to which you’ll eventually be deploying your

scripts You can always come back and change the setting later

8.In the Paths and Directories section, locate the final line in the following screenshot:

Change it to

Trang 38

This is the name of the folder where PHP will look for any extensions This assumes youextracted the PHP files to the recommended location If you chose a different location,you will need to change the path from C:\php5\.

9.Scroll further down until you come to Dynamic

Extensions You will see a long alphabetically orderedlist titled Windows Extensions (around line 549), all

of them commented out

These extensions add extra features to the core tionality of PHP You can enable any of them at anytime simply by removing the semicolon from thebeginning of the line for the extension you want, sav-ing php.ini, and restarting Apache This is a loteasier, incidentally, than on Mac OS X or Linux, whereenabling a new extension usually means completelyreinstalling PHP

func-Although you won’t install MySQL until Chapter 6, it’sworthwhile enabling the relevant extension now

Locate the following line (around line 578):

;extension=php_mysql.dll

Remove the semicolon at the beginning of the line Highlight the whole line, and then

copy (C TRL +C/ +C) and paste (C TRL +V/ +V) it on the line immediately below Amend

the two lines so they look like this:

extension=php_mysql.dllextension=php_mysqli.dll

10.In the Module Settings section immediately following the

list of extensions, look for the code shown alongside:

It is quite possible that, by the time you read this, the line will have changed to

;extension=php_mysqli.dll

There are two separate PHP extensions for working with MySQL:

php_mysql.dll and php_mysqli.dll The first one works with older

versions of MySQL; the second works only with MySQL 4.1 and above For maximum flexibility, I suggest you install both.

Trang 39

Unless you have already installed and configured SMTP on your computer (and if you

don’t know what I’m talking about, you almost certainly haven’t), change the line

shown in the screenshot as line 608 to the name of the SMTP server you normally use

for sending email This is the name your ISP will have given you for outgoing mail If

your email address is, for instance, david@example.com, your outgoing address is most

probably smtp.example.com In that case, you would change the line indicated to this:

SMTP = smtp.example.com

If you can’t immediately identify the correct outgoing mail address, don’t worry It’s not

vital for getting PHP to work, although it means you won’t be able to test the

applica-tion in the next chapter on your local computer, but will have to upload it to your

remote server instead

11.Remove the semicolon from the beginning of line 612, and put your own email address

in place of me@example.com:

sendmail_from = your email address

This puts your correct email address in the From: field of emails sent through PHP

12.The final change you need to make to php.ini is considerably further down (around

line 879) Locate the line at the bottom of this screenshot:

Remove the semicolon from the beginning of the line, and change the setting in quotes

to your computer’s Temp folder On most Windows computers, this will be C:\WINDOWS\

Temp or C:\WINNT\Temp Use either of the following, depending on your system setup:

session.save_path = "C:\WINDOWS\Temp"

session.save_path = "C:\WINNT\Temp"

13.Save php.ini In the past, it used to be necessary to copy this file to your main Windows

folder This should no longer be done, and any PHP-related files from previous

installations should be removed as described at the beginning of this section.

Adding PHP to your Windows startup procedure

The installation of PHP is complete, but it still needs to be added to your Windows startup

pro-cedure The method differs depending on your Windows system

Trang 40

1.Open the Windows Control Panel (Start➤ Settings ➤ Control Panel or Start ➤ ControlPanel) Double-click the System icon Select the Advanced tab, and click EnvironmentVariables, as shown in the following screenshot.

2.In the System variables pane at the bottom of the

dialog box that opens, highlight Path and clickEdit This will open a smaller dialog box, as shownhere Click inside the Variable value field, andmove your cursor to the end of the existing value

Type a semicolon followed by the name of thePHP folder you created in step 2 of the previoussection (;C:\php5) As shown in the screenshot,there should be no spaces between the existingvalue or in the new path name

3.Click OK With the Environment Variables dialog

box still open, click New in the System variablespane This will open another small dialog box foryou to enter the details of the new system vari-able In the Variable name field, type PHPRC Inthe Variable value field, enter the path of the PHPfolder (C:\php5)

4.Click OK to close all the dialog boxes The

changes will take place the next time you restartyour computer

Adding PHP to Windows NT, 2000, XP, and 2003

Ngày đăng: 24/01/2014, 14:35

TỪ KHÓA LIÊN QUAN

w