logo资料库

PHP Solutions, 3rd Edition.pdf

第1页 / 共499页
第2页 / 共499页
第3页 / 共499页
第4页 / 共499页
第5页 / 共499页
第6页 / 共499页
第7页 / 共499页
第8页 / 共499页
资料共499页,剩余部分请下载后查看
Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: What Is PHP—And Why Should I Care?
How PHP Has Grown
How PHP Makes Pages Dynamic
Creating Pages That Think for Themselves
How Hard Is PHP to Use and Learn?
Can I Just Copy and Paste the Code?
How Safe Is PHP?
What Software Do I Need to Write PHP?
What to Look for When Choosing a PHP Editor
So, Let’s Get on with It . . .
Chapter 2: Getting Ready to Work with PHP
Checking Whether Your Website Supports PHP
Deciding Where to Test Your Pages
What You Need for a Local Test Environment
Individual Programs or an All-in-one Package?
Setting Up on Windows
Getting Windows to Display Filename Extensions
Choosing a Web Server
Installing an All-in-one Package on Windows
Setting Up on Mac OS X
Installing MAMP
Testing and configuring MAMP
Where to Locate Your PHP Files (Windows & Mac)
Using Virtual Hosts
Checking Your PHP Settings
Displaying the Server Configuration with phpinfo()
Editing php.ini
What’s Next?
Chapter 3: How to Write PHP Scripts
PHP: The Big Picture
Telling the Server to Process PHP
Embedding PHP in a Webpage
Storing PHP in an External File
Using Variables to Represent Changing Values
Naming Variables
Assigning Values to Variables
Ending Commands With a Semicolon
Commenting Scripts
Single-line Comments
Multi-line Comments
Using Arrays to Store Multiple Values
PHP’s Built-in Superglobal Arrays
Understanding When to Use Quotes
Special Cases: True, False, and Null
Making Decisions
Making Comparisons
Using Indenting and Whitespace for Clarity
Using Loops for Repetitive Tasks
Using Functions for Preset Tasks
Understanding PHP Classes and Objects
Displaying PHP Output
Using Echo Shortcut Syntax
Joining Strings Together
Working With Numbers
Understanding PHP Error Messages
Why is My Page Blank?
Handling Exceptions
PHP: A Quick Reference
Using PHP in an Existing Website
Data Types in PHP
Doing Calculations with PHP
Arithmetic Operators
Determining the Order of Calculations
Combining Calculations and Assignment
Adding to an existing string
All You Ever Wanted to Know About Quotes—and More
How PHP Treats Variables Inside Strings
Using Escape Sequences Inside Double Quotes
Embedding Associative Array Elements in a String
Avoiding the Need to Escape Quotes with Heredoc Syntax
Creating Arrays
Building an Indexed Array
Building an Associative Array
Creating an Empty Array
Multidimensional Arrays
Using Print_r( ) to Inspect An Array
The Truth According to PHP
Explicit Boolean Values
Implicit Boolean (“Truthy” and “Falsy”) Values
Making Decisions by Comparing Two Values
Testing More Than One Condition
Using the Switch Statement for Decision Chains
Using the Ternary Operator
Creating Loops
Loops Using While and Do . . . While
The Versatile for Loop
Looping Through Arrays and Objects with Foreach
Breaking Out Of a Loop
Modularizing Code with Functions
Passing Values to F unctions
Variable Scope—Functions as Black Boxes
Returning Values from Functions
Passing by Reference—Changing the Value of an Argument
Where to Locate Custom-Built Functions
Creating New Variables Dynamically
PHP Quick Checklist
Chapter 4: Lightening Your Workload with Includes
Including Code from External Files
Introducing the PHP Include Commands
Where PHP Looks for Include Files
PHP Solution 4-1: Moving the Menu and Footer to Include Files
Choosing the Right Filename Extension for Includes
PHP Solution 4-2: Testing the Security of Includes
PHP Solution 4-3: Automatically Indicating the Current Page
PHP Solution 4-4: Generating a Page’s Title From its Filename
Creating Pages with Changing Content
PHP Solution 4-5: Automatically Updating a Copyright Notice
PHP Solution 4-6: Displaying a Random Image
PHP Solution 4-7: Adding a Caption to the Random Image
Preventing Errors with Include Files
Checking the Existence of Variables
Checking Whether a Function or Class has Been Defined
Suppressing Error Messages on a Live Website
Using the Error Control Operator
Turning Off display_errors in the PHP Configuration
Turning Off display_errors in an Individual File
PHP Solution 4-8: Redirecting when an Include File Can’t be Found
Choosing where to Locate your Include Files
Adjusting your include_path
Editing the include_path in php.ini or .user.ini
Using .htaccess to Change the include_path
Using set_include_path( )
Why can’t I Use Site-root-relative Links with PHP Includes?
Document-relative Links
Links Relative to the Site Root
Links Inside Include Files
Nesting Include Files
Security Considerations with Includes
Chapter Review
Chapter 5: Bringing Forms to Life
How PHP Gathers Information from a Form
Understanding the Difference Between Post and get
Getting form Data with PHP Superglobals
Processing and Validating User Input
Creating a Reusable Script
PHP Solution 5-1: Making Sure Required Fields aren’t Blank
Preserving User Input when a Form is Incomplete
PHP Solution 5-2: Creating Sticky form fields
Filtering Out Potential Attacks
PHP Solution 5-3: Blocking Emails that Contain Specific Phrases
Sending Email
Using Additional Email Headers Safely
PHP Solution 5-4: Adding Headers and Automating the Reply Address
PHP Solution 5-5: Building the message Body and Sending the Mail
Troubleshooting mail()
Handling Multiple-Choice Form Elements
PHP Solution 5-6: Handling Radio-Button Groups
PHP Solution 5-7: Handling Check-Box Groups
PHP Solution 5-8: Using a Drop-down Option Menu
PHP Solution 5-9: Handling a Multiple-choice List
PHP Solution 5-10: Handling a Single Check Box
Chapter Review
Chapter 6: Uploading Files
How PHP Handles File Uploads
Checking whether your server supports uploads
Adding a file upload field to a form
Understanding the $_FILES array
Inspecting the $_FILES array
Establishing an upload directory
Creating an upload folder for local testing on Windows
Creating an upload folder for local testing on Mac OS X
Uploading Files
Moving the temporary file to the upload folder
PHP Solution 6-1: Creating a basic file upload script
Creating a PHP File Upload Class
Defining a PHP class
Using a namespace to avoid naming conflicts
Importing a namespaced class
PHP Solution 6-2: Creating the basic file upload class
Checking upload errors
PHP Solution 6-3: Testing the error level, file size, and MIME type
Changing protected properties
PHP Solution 6-4: Allowing different types and sizes to be uploaded
Explicitly changing a data type
Neutralizing potentially dangerous files
PHP Solution 6-5: Checking and amending filenames
Preventing files from being overwritten
PHP Solution 6-6: Renaming duplicate files
Uploading Multiple Files
How the $_FILES array handles multiple files
PHP Solution 6-7: Adapting the class to handle multiple uploads
Using the Upload Class
Points to Watch with File Uploads
Chapter Review
Chapter 7: Using PHP to Manage Files
Checking that PHP Can Open a File
Configuration Settings that Affect File Access
Creating a File Storage Folder for Local Testing
Reading and Writing Files
Reading Files in a Single Operation
PHP Solution 7-1: Getting the Contents of a Text File
Opening and Closing Files for Read/Write Operations
Reading a File with fopen( )
PHP Solution 7-2: Extracting data from a CSV file
Replacing Content with fopen( )
Appending Content with fopen( )
Locking a File Before Writing
Preventing Overwriting an Existing File
Combined Read/Write Operations with fopen( )
Moving the Internal Pointer
Exploring the File System
Inspecting a Folder with Scandir( )
Inspecting the Contents of a Folder with FilesystemIterator
Restricting File Types with the RegexIterator
PHP Solution 7-3: Building a Drop-Down Menu of Files
PHP Solution 7-4: Creating a Generic File Selector
Accessing Remote Files
Consuming News and Other RSS Feeds
Using SimpleXML
PHP Solution 7-5: Consuming an RSS news feed
Creating a Download Link
PHP Solution 7-6: Prompting a User to Download an Image
Chapter Review
Chapter 8: Generating Thumbnail Images
Checking Your Server’s Capabilities
Manipulating Images Dynamically
Making a Smaller Copy of an Image
Getting Ready
Building the Thumbnail Class
PHP Solution 8-1: Getting the Image Details
PHP Solution 8-2: Creating the Setter Methods
PHP Solution 8-3: Calculating the thumbnail’s dimensions
Using GD Functions to Create a Scaled Copy of an Image
PHP Solution 8-4: Generating the thumbnail image
Resizing an Image Automatically on Upload
Extending a Class
PHP Solution 8-5: Creating the ThumbnailUpload Class
Using the ThumbnailUpload Class
Chapter Review
Chapter 9: Pages That Remember: Simple Login and Multipage Forms
What Sessions Are and How They Work
Creating PHP Sessions
Creating and Destroying Session Variables
Destroying a Session
Regenerating the Session ID
The “Headers Already Sent” Error
Using Sessions to Restrict Access
PHP Solution 9-1: A Simple Session Example
PHP Solution 9-2: Buffering the Output with ob_start( )
Using File-based Authentication
PHP Solution 9-3: Building the Login Page
PHP Solution 9-4: Restricting Access to a Page with a Session
PHP Solution 9-5: Creating a Reusable Logout Button
Making Passwords More Secure
PHP Solution 9-6: Creating a Password-strength Checker
PHP Solution 9-7: Creating a File-based User Registration System
Checking Encrypted Passwords with password_verify()
PHP Solution 9-8: Using an Encrypted Login
Keeping Encryption Up to Date
Setting a Time Limit on Sessions
PHP Solution 9-9: Ending a Session after a Period of Inactivity
Passing Information Through Multipage Forms
PHP Solution 9-10: Using Sessions for a Multipage Form
Chapter Review
Chapter 10: Getting Started with a Database
Which Database Should You Choose?
Compatibility of MariaDB and MySQL
How a Database Stores Information
How primary keys work
Linking tables with primary and foreign keys
Breaking down information into small chunks
Checkpoints for good database design
Using a Graphical Interface
Launching phpMyAdmin
Setting Up the phpsols Database
MySQL naming rules
Case sensitivity of names
Using phpMyAdmin to create a new database
Creating database-specific user accounts
Granting user privileges
Creating a database table
Defining the images table
Inserting records into a table
Using phpMyAdmin to insert records manually
Loading the images records from an SQL file
Creating an SQL file for backup and data transfer
Choosing the Right Data Type in MySQL
Storing text
Storing numbers
Storing dates and times
Storing predefined lists
Storing binary data
Chapter Review
Chapter 11: Connecting to a Database with PHP and SQL
Checking Your Remote Server Setup
How PHP Communicates with a Database
Connecting with the MySQL Improved extension
Connecting with PDO
PHP Solution 11-1: Making a reusable database connector
Troubleshooting database connection problems
Querying the database and displaying the results
PHP Solution 11-2: Counting records in a result set (MySQLi)
PHP Solution 11-3: Displaying the images table using MySQLi
MySQLi connection crib sheet
PHP Solution 11-4: Counting records in a result set (PDO)
Counting records with PDO in other databases
PHP Solution 11-5: Displaying the images table using PDO
PDO connection crib sheet
Using SQL to Interact with a Database
Writing SQL queries
SQL is case-insensitive
Whitespace is ignored
Strings must be quoted
Handling numbers
Refining the data retrieved by a SELECT query
Selecting specific columns
Changing the order of results
Searching for specific values
Searching for text with wildcard characters
Understanding the Danger of SQL Injection
PHP Solution 11-6: Inserting an integer from user input into a query
PHP Solution 11-7: Inserting a string in MySQLi with real_escape_string()
Using Prepared Statements for User Input
Embedding variables in MySQLi prepared statements
Initialize the statement
Prepare the statement
Bind values to the placeholders
Execute the statement
Binding the results (optional)
Store the result (optional)
Fetch the result
Close the statement
PHP Solution 11-8: Using a MySQLi prepared statement in a search
Embedding variables in PDO prepared statements
Using anonymous placeholders
Using named placeholders
Preparing the statement
Binding values to the placeholders
Executing the statement
Binding the results (optional)
Fetching the result
PHP Solution 11-9: Using a PDO prepared statement in a search
PHP Solution 11-10: Changing column options through user input
Chapter Review
Chapter 12: Creating a Dynamic Photo Gallery
Why Not Store Images in a Database?
Planning the Gallery
Converting the Gallery Elements to PHP
PHP Solution 12-1: Displaying the First Image
Building the Dynamic Elements
Passing Information Through a Query String
PHP Solution 12-2: Activating the Thumbnails
Creating a Multicolumn table
PHP Solution 12-3: Looping Horizontally and Vertically
Paging Through a Long set of Records
Selecting a Subset of Records
PHP Solution 12-4: Displaying a Subset of Records
Navigating Through Subsets of Records
PHP Solution 12-5: Creating the Navigation Links
Chapter Review
Chapter 13: Managing Content
Setting Up a Content Management System
Creating the Blog Database Table
Creating the Basic Insert and Update Form
Inserting New Records
PHP Solution 13-1: Inserting a New Record with MySQLi
PHP Solution 13-2: Inserting a New Record with PDO
Linking to the Update and Delete Pages
PHP Solution 13-3: Creating the Links to the Update and Delete Pages
Updating Records
PHP Solution 13-4: Updating a Record with MySQLi
PHP Solution 13-5: Updating a Record with PDO
Deleting Records
Reviewing the Four Essential SQL Commands
SELECT
INSERT
UPDATE
DELETE
Security and Error Messages
Chapter Review
Chapter 14: Formatting Text and Dates
Displaying a Text Extract
Extracting a Fixed Number of Characters
Using the PHP substr( ) Function
Using the LEFT( ) Function in an SQL Query
Ending an Extract on a Complete Word
Extracting the First Paragraph
Displaying Paragraphs
Storing Database Records as HTML
Converting Newlines to
Tags
Creating a Function to Insert

Tags

Extracting Complete Sentences
PHP Solution 14-1: Displaying the First Two Sentences of an Article
Let’s Make a Date
How MySQL Handles Dates
Formatting Dates in a SELECT Query with DATE_FORMAT( )
PHP Solution 14-2: Formatting a MySQL Date or Timestamp
Adding to and Subtracting from Dates
PHP Solution 14-3: Displaying Items Updated within the Past Week
Inserting Dates into MySQL
PHP Solution 14-4: Validating and Formatting Dates for MySQL Input
Working with Dates in PHP
Setting the Default Time Zone
Creating a DateTime Object
Formatting Dates in PHP
Creating a DateTime Object From a Custom Format
Choosing Between Date( ) and the DateTime Class
Handling Overflows with Relative Dates
Using the DateTimeZone Class
Adding and Subtracting Set Periods with the DateInterval Class
Finding the Difference Between Two Dates with the diff( ) Method
Calculating Recurring Dates with the DatePeriod Class
Chapter Review
Chapter 15: Pulling Data from Multiple Tables
Understanding Table Relationships
Linking an Image to an Article
Altering the Structure of an Existing Table
PHP Solution 15-1: Adding an Extra Column to a Table
Inserting a Foreign Key in a Table
PHP Solution 15-2: Adding the Image Foreign Key ( MySQLi)
PHP Solution 15-3: Adding the Image Foreign Key ( PDO)
Selecting Records from Multiple Tables
PHP Solution 15-4: Building the Details Page
Finding Records that don’t have a Matching Foreign Key
Creating an Intelligent Link
PHP Solution 15-5: Returning to the Same Point in a Navigation System
Chapter Review
Chapter 16: Managing Multiple Database Tables
Maintaining Referential Integrity
Support for foreign-key constraints
PHP Solution 16-1: Checking whether InnoDB is supported
Inserting records into multiple tables
Creating a cross-reference table
Setting up the categories and cross-reference tables
Getting the filename of an uploaded image
PHP Solution 16-2: Improving the Upload class
Adapting the insert form to deal with multiple tables
PHP Solution 16-3: Adding the category and image input fields
PHP Solution 16-4: Inserting data into multiple tables
Main differences in the PDO version
Updating and Deleting Records in Multiple Tables
Updating records in a cross-reference table
PHP Solution 16-5: Adding categories to the update form
Preserving referential integrity on deletion
PHP Solution 16-6: Converting tables to the InnoDB storage engine
PHP Solution 16-7: Setting up foreign-key constraints
Creating delete scripts with foreign-key constraints
Creating delete scripts without foreign-key constraints
Chapter Review
Chapter 17: Authenticating Users with a Database
Choosing an Encryption Method
Using One-Way Encryption
Creating a Table to Store Users’ Details
Registering New Usersin the Database
PHP Solution 17-1: Creating a User Registration Form
PHP Solution 17-2: Authenticating a user’s credentials with a database
Using Two-Way Encryption
Creating the table to store users’ details
Registering new users
User authentication with two-way encryption
Decrypting a password
Updating User Details
Where Next?
Index
For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info
Contents at a Glance About the Author ���������������������������������������������������������������������������������������������������������������� xv About the Technical Reviewer ������������������������������������������������������������������������������������������ xvii Acknowledgments ������������������������������������������������������������������������������������������������������������� xix Introduction ����������������������������������������������������������������������������������������������������������������������� xxi ■ Chapter 1: What Is PHP—And Why Should I Care? �����������������������������������������������������������1 ■ Chapter 2: Getting Ready to Work with PHP ���������������������������������������������������������������������7 ■ Chapter 3: How to Write PHP Scripts �������������������������������������������������������������������������������19 ■ Chapter 4: Lightening Your Workload with Includes �������������������������������������������������������63 ■ Chapter 5: Bringing Forms to Life �����������������������������������������������������������������������������������97 ■ Chapter 6: Uploading Files ���������������������������������������������������������������������������������������������133 ■ Chapter 7: Using PHP to Manage Files ��������������������������������������������������������������������������173 ■ Chapter 8: Generating Thumbnail Images ���������������������������������������������������������������������207 ■ Chapter 9: Pages That Remember: Simple Login and Multipage Forms �����������������������235 ■ Chapter 10: Getting Started with a Database ����������������������������������������������������������������273 ■ Chapter 11: Connecting to a Database with PHP and SQL ���������������������������������������������299 ■ Chapter 12: Creating a Dynamic Photo Gallery �������������������������������������������������������������337 ■ Chapter 13: Managing Content ��������������������������������������������������������������������������������������357 ■ Chapter 14: Formatting Text and Dates �������������������������������������������������������������������������383 www.it-ebooks.info iii
■ Contents at a GlanCe ■ Chapter 15: Pulling Data from Multiple Tables ��������������������������������������������������������������417 ■ Chapter 16: Managing Multiple Database Tables ����������������������������������������������������������435 ■ Chapter 17: Authenticating Users with a Database �������������������������������������������������������465 Index ���������������������������������������������������������������������������������������������������������������������������������479 iv www.it-ebooks.info
Introduction When the first edition of PHP Solutions was published, I was concerned that the subtitle, Dynamic Web Design Made Easy, sounded overambitious. Even with this third edition, it still makes me a little apprehensive about unduly raising readers’ expectations. PHP is not difficult, but nor is it like an instant cake mix: just add water and stir. Every website is different, so it’s impossible to grab a script, paste it into a webpage, and expect it to work. My aim was to help web designers with little or no knowledge of programming gain the confidence to dive into the code and adjust it to their own requirements. The fact that the book has remained so popular since it was first published in 2006 suggests that many readers took up the challenge. Members of Boston PHP did so in large numbers when they adopted the second edition as the text for three series of PHP Percolate, a virtual self-study group for beginners. Hundreds signed up to study the book one chapter a week. It worked for them, so I hope it will work just as well for you. What’s New in this Edition One useful piece of feedback from PHP Percolate participants and other readers was disappointment when I glossed over a section of advanced code, explaining only what it did rather than how it worked. That omission has been corrected in this edition. Occasionally, I point out that you might want to skip the detailed explanation, but it’s there if you’re intrigued by how a technique works. As a result, the reference section of Chapter 3 has been expanded to include such esoteric delights as variable variables. No, it’s not a typo; “variable variable” is a genuine concept in PHP. It’s also quite useful. This edition brings the content up to date with PHP 5.6, which was released in August 2014. Because hosting companies are often slow to upgrade the version of PHP that they offer, I’ve made PHP 5.4 the minimum version for the code used in this book. PHP 5.4 made some important changes, introducing a simplified array syntax and dropping support for safe mode and “magic quotes.” As well as bringing the code up to date, I’ve revised every chapter, going through it line by line, clarifying explanations. I’ve also eliminated a number of errors—without, I hope, introducing new ones. The biggest changes are to the custom classes for uploading files and creating image thumbnails in Chapters 6 and 8. They now use namespaces to avoid naming clashes with other third-party code. More important, the class definitions have been extensively rewritten to make them more efficient. Another significant change is the use of the new password hashing functions in Chapters 9 and 17. These functions weren’t introduced until PHP 5.5, but you can emulate them in PHP 5.4 by including the password_compat library in your scripts. Details of how to obtain the library, which consists of a single file, can be found in Chapter 9. The chapters on working with a database have been reorganized to make them easier to follow. I’ve also strengthened the explanation of prepared statements, using both MySQL Improved (MySQLi) and the database- neutral PHP Data Objects (PDO). Some Linux distributions now install MariaDB as a drop-in replacement for MySQL. To avoid unnecessary repetition, I normally refer only to MySQL, but all the PHP solutions in this book work equally well with MariaDB. www.it-ebooks.info xxi
■ IntroduCtIon How This Book Is Organized Each chapter takes you through a series of stages in a single project, with each stage building on the previous one. By working through each chapter, you get the full picture of how everything fits together. You can later refer to the individual stages to refresh your memory about a particular technique. Although this isn’t a reference book, Chapter 3 is a primer on PHP syntax, and some chapters contain short reference sections—notably Chapter 7 (reading from and writing to files), Chapter 9 (sessions), Chapter 10 (data types in MySQL/MariaDB), Chapter 11 (PHP prepared statements), Chapter 13 (the four essential SQL commands), and Chapter 14 (working with dates and times). So, how easy is easy? I have done my best to ease your path, but there is no magic potion. It requires some effort on your part. Don’t attempt to do everything at once. Add dynamic features to your site a few at a time. Get to understand how they work, and your efforts will be amply rewarded. Adding PHP and MySQL/MariaDB to your skills will enable you to build websites that offer much richer content and an interactive user experience. Using the Example Files All the files necessary for working through this book can be downloaded from the Apress website at www.apress. com/9781484206362. Make sure you select the download link for PHP Solutions: Dynamic Web Design Made Easy, Third Edition. The code is different from the first two editions. Set up a PHP development environment, as described in Chapter 2. Unzip the files and copy the phpsols folder and all its contents into your web server’s document root. The code for each chapter is in a folder named after the chapter: ch01, ch02, and so on. Follow the instructions in each PHP solution, and copy the relevant files to the site root or the work folder indicated. Where a page undergoes several changes during a chapter, I have numbered the different versions like this: index_01.php, index_02.php, and so on. When copying a file that has a number, remove the underscore and number from the filename, so index_01.php becomes index.php. If you are using a program like Dreamweaver that prompts you to update links when moving files from one folder to another, do not update them. The links in the files are designed to pick up the right images and style sheets when located in the target folder. I have done this so you can use a file comparison utility to check your files against mine. If you don’t have a file comparison utility, I strongly urge you to install one. It will save you hours of head scratching when trying to spot the difference between your version and mine. A missing semicolon or mistyped variable can be hard to spot in dozens of lines of code. Windows users can download WinMerge for free from http://winmerge.org/. I use Beyond Compare (www.scootersoftware.com), which is now available for Windows, Mac OS X, and Linux. It’s not free but is excellent and reasonably priced. BBEdit on a Mac includes a file comparison utility. Alternatively, use the file comparison feature in TextWrangler, which can be downloaded free from www.barebones.com/products/textwrangler/. Layout Conventions To keep this book as clear and easy to follow as possible, the following text conventions are used throughout: Important words or concepts are normally highlighted on the first appearance in bold type. Code is presented in fixed-width font. New or changed code is normally presented in bold fixed-width font. Pseudo-code and variable input are written in italic fixed-width font. Menu commands are written in the form Menu ➤ Submenu ➤ Submenu. Where I want to draw your attention to something, I’ve highlighted it, like this: ■ ahem, don’t say I didn’t warn you. xxii www.it-ebooks.info
Chapter 1 What Is PHP—And Why Should I Care? Officially, PHP stands for PHP: Hypertext Preprocessor. It’s an ugly name that gives the impression that it’s strictly for nerds or propellerheads. Nothing could be further from the truth. A lighthearted debate on the PHP general mailing list (http://news.php.net/php.general) several years ago suggested changing what PHP stands for to Positively Happy People or Pretty Happy Programmers. This book aims to help you put PHP to practical use—and in the process help you understand what makes PHP programmers so happy. PHP is a scripting language that brings websites to life in the following ways: • • • • • • • • Sends feedback from your website directly to your mailbox Uploads files through a webpage Generates thumbnails from larger images Reads and writes to files Displays and updates information dynamically Uses a database to display and store information Makes websites searchable And much more . . . By reading this book, you’ll be able to do all that. PHP is easy to learn; it’s platform-neutral, so the same code runs on Windows, Mac OS X, and Linux, and all the software you need to develop with PHP is open source and therefore free. In this chapter, you’ll learn about the following: • • • • • How PHP has grown into the most widely used technology for dynamic websites How PHP makes webpages dynamic How difficult—or easy—PHP is to learn Whether PHP is safe What software you need in order to write PHP How PHP Has Grown PHP is now the most widely used technology for creating dynamic websites, but it started out in 1995 with rather modest ambitions—and a different name. It was originally called Personal Home Page Tools (PHP Tools). One of its main goals was to create a guestbook by gathering information from an online form and displaying it on a webpage. Within three years, it was decided to drop Personal Home Page from the name, because it sounded like something for hobbyists and didn’t do justice to the range of sophisticated features that had since been added. www.it-ebooks.info 1
Chapter 1 ■ What Is php—and Why should I Care? PHP has continued to develop over the years, adding new features all the time. According to W3Techs (http://w3techs.com/technologies/details/pl-php/all/all), PHP is used to create dynamic content by more than 80 percent of the 10 million websites it regularly surveys. It’s the language that drives highly popular content management systems (CMSs) such as Drupal (http://drupal.org/), Joomla! (www.joomla.org), and WordPress (http://wordpress.org/). It also runs some of the most heavily used websites, including Facebook (www.facebook.com) and Wikipedia (www.wikipedia.org). One of the language’s great attractions, though, is that it remains true to its roots. PHP’s original creator, Rasmus Lerdorf, once described it as “a very programmer-friendly scripting language suitable for people with little or no programming experience as well as the seasoned web developer who needs to get things done quickly.” You can start writing useful scripts without needing to learn lots of theory, yet be confident in knowing that you’re using a technology with the capability to develop industrial-strength applications. Note at the time of this writing, the current version is php 5.6. the code assumes you’re using a minimum of ■ php 5.4, which removed several outdated features, such as “magic quotes.” If you have a hosting plan, make sure the server is running at least php 5.4. the next major version of php will be called php 7. It’s been decided to skip php 6 to avoid confusion with a version that was abandoned in 2010 for being too ambitious. the emphasis in this book is on code that works now, not on what might work at some unspecified time in the future. however, I fully expect that most if not all of the code and techniques will continue to work in php 7. How PHP Makes Pages Dynamic PHP was originally designed to be embedded in the HTML of a webpage, and that’s the way it’s often still used. For example, if you want to display the current year in a copyright notice, you could put this in your footer:

© PHP Solutions

On a PHP–enabled web server, the code between the tags is automatically processed and displays the year like this: This is only a trivial example, but it illustrates some of the advantages of using PHP: • • Anyone accessing your site after the stroke of midnight on New Year’s Day sees the correct year. The date is calculated by the web server so it’s not affected if the clock in the user’s computer is set incorrectly. Although it’s convenient to embed PHP code in HTML like this, it’s repetitive and can lead to mistakes. It can also make your webpages difficult to maintain, particularly once you start using more complex PHP code. Consequently, it’s common practice to store a lot of dynamic code in separate files and then use PHP to build your pages from the different components. The separate files—or include files, as they’re usually called—can contain only PHP, only HTML, or a mixture of both. 2 www.it-ebooks.info
分享到:
收藏