What Is PHP - And Why Should I Care - PHP Solutions: Dynamic Web Design Made Easy, Third Edition (2014)

PHP Solutions: Dynamic Web Design Made Easy, Third Edition (2014)

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.

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.

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

<p>© <?php echo date('Y'); ?> PHP Solutions</p>

On a PHP–enabled web server, the code between the <?php and ?> 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.

As a simple example, you can put your website’s navigation menu in an include file and use PHP to include it in each page. Whenever you need to make any changes to the menu, you edit just one file, the include file, and the changes are automatically reflected in every page that includes the menu. Just imagine how much time that saves on a website with dozens of pages!

With an ordinary HTML page, the content is fixed by the web developer at design time and uploaded to the web server. When somebody visits the page, the web server simply sends the HTML and other assets, such as images and the style sheet. It’s a simple transaction—the request comes from the browser, and the fixed content is sent back by the server. When you build webpages with PHP, much more goes on. Figure 1-1 shows what happens.


Figure 1-1. The web server builds each PHP page dynamically in response to a request

When a PHP–driven website is visited, it sets in motion the following sequence of events:

1. The browser sends a request to the web server.

2. The web server hands the request to the PHP engine, which is embedded in the server.

3. The PHP engine processes the code. In many cases, it might also query a database before building the page.

4. The server sends the completed page back to the browser.

This process usually takes only a fraction of a second, so the visitor to a PHP website is unlikely to notice any delay. Because each page is built individually, PHP sites can respond to user input, displaying different content when a user logs in or showing the results of a database search.

Creating Pages That Think for Themselves

PHP is a server-side language. The PHP code remains on the web server. After it has been processed, the server sends only the output of the script. Normally, this is HTML, but PHP can also be used to generate other web languages, such as JSON (JavaScript Object Notation).

PHP enables you to introduce logic into your webpages that is based on alternatives. Some decisions are made using information that PHP gleans from the server: the date, the time, the day of the week, information in the page’s URL, and so on. If it’s Wednesday, it will show Wednesday’s TV schedules. At other times, decisions are based on user input, which PHP extracts from online forms. If you have registered with a site, it will display personalized information—that sort of thing.

How Hard Is PHP to Use and Learn?

PHP isn’t rocket science, but don’t expect to become an expert in five minutes. Perhaps the biggest shock to newcomers is that PHP is far less tolerant of mistakes than browsers are with HTML. If you omit a closing tag in HTML, most browsers will still render the page. If you omit a closing quote, semicolon, or brace in PHP, you’ll get an uncompromising error message like the one shown in Figure 1-2. This affects all programming languages, such as JavaScript and C#, not just PHP.


Figure 1-2. Server-side languages like PHP are intolerant of most coding errors

If you’re the sort of web designer or developer who uses a visual design tool like Adobe Dreamweaver and never looks at the underlying code, it’s time to rethink your approach. Mixing PHP with poorly structured HTML is likely to lead to problems. PHP uses loops to perform repetitive tasks, such as displaying the results of a database search. A loop repeats the same section of code—usually a mixture of PHP and HTML—until all results have been displayed. If you put the loop in the wrong place or if your HTML is badly structured, your page is likely to collapse like a house of cards.

If you’re not already in the habit of doing so, it’s a good idea to check your pages using the World Wide Web Consortium’s (W3C) Markup Validation Service (http://validator.w3.org/unicorn).

Image Note The W3C is the international body that develops standardssuch as HTML and CSS to ensure the long-term growth of the web. It’s led by the inventor of the World Wide Web, Tim Berners-Lee. To learn about the W3C’s mission, see www.w3.org/Consortium/mission.

Can I Just Copy and Paste the Code?

There’s nothing wrong with copying the code in this book. That’s what it’s there for. I’ve structured this book as a series of practical projects. I explain what the code is for and why it’s there. Even if you don’t understand exactly how it all works, this should give you sufficient confidence to know which parts of the code to adapt to your own needs and which parts are best left alone. But to get the most out of this book, you need to start experimenting with the tools found in these pages and then come up with your own solutions.

PHP is a toolbox full of powerful features. It has thousands of built-in functions that perform all sorts of tasks, such as converting text to uppercase, generating thumbnail images from full-sized ones, or connecting to a database. The real power comes from combining these functions in different ways and adding your own conditional logic.

How Safe Is PHP?

PHP is like the electricity or kitchen knives in your home: handled properly, it’s very safe; handled irresponsibly, it can do a lot of damage. One of the inspirations for the first edition of this book was a spate of attacks that exploited a vulnerability in email scripts, turning websites into spam relays. The solution is quite simple, as you’ll learn in Chapter 5, but even a decade later, I still see people using the same insecure techniques, exposing their sites to attack.

PHP is not unsafe, nor does everyone need to become a security expert to use it. What is important is to understand the basic principle of PHP safety: always check user input before processing it. You’ll find that to be a constant theme throughout this book. Most security risks can be eliminated with very little effort.

The best way to protect yourself is to understand the code you’re using.

What Software Do I Need to Write PHP?

Strictly speaking, you don’t need any special software to write PHP scripts. PHP code is plain text and can be created in any text editor, such as Notepad on Windows or TextEdit on Mac OS X. Having said that, your life will be a lot easier if you use a program that has features designed to speed up the development process. There are many available—both free and on a paid-for basis.

What to Look for When Choosing a PHP Editor

If there’s a mistake in your code, your page will probably never make it as far as the browser, and all you’ll see is an error message. You should choose a script editor that has the following features:

· PHP syntax checking: This used to be found only in expensive, dedicated programs, but it’s now a feature in several free programs. Syntax checkers monitor the code as you type and highlight errors, saving a great deal of time and frustration.

· PHP syntax coloring: Code is highlighted in different colors according to the role it plays. If your code is in an unexpected color, it’s a sure sign you’ve made a mistake.

· PHP code hints: PHP has so many built-in functions that it can be difficult to remember how to use them, even for an experienced user. Many script editors automatically display tooltips with reminders of how a particular piece of code works.

· Line numbering: Finding a specific line quickly makes troubleshooting a lot simpler.

· A “balance braces” feature: Parentheses (()), square brackets ([]), and curly braces ({}) must always be in matching pairs. It’s easy to forget to close a pair. All good script editors help find the matching parenthesis, bracket, or brace.

The program you’re already using to build webpages might already have these features. For example, Adobe Dreamweaver CS5 and later does (www.adobe.com/products/dreamweaver/). It also has embedded PHP documentation.

Even if you don’t plan to do a lot of PHP development, you should consider using a dedicated script editor if your web development program doesn’t support syntax checking. The following dedicated script editors have all the essential features, such as syntax checking and code hints. It’s not an exhaustive list, but rather one based on personal experience.

· PhpStorm (www.jetbrains.com/phpstorm/): Although this is a dedicated PHP editing program, it also has excellent support for HTML, CSS, and JavaScript. It’s currently my favorite program for developing with PHP.

· Sublime Text (www.sublimetext.com/): If you’re a Sublime Text fan, there are plug-ins for PHP syntax coloring, syntax checking, and documentation.

· Zend Studio (www.zend.com/en/products/studio/): If you’re really serious about PHP development, Zend Studio is the most fully featured integrated development environment (IDE) for PHP. It’s created by Zend, the company run by leading contributors to the development of PHP. Zend Studio runs on Windows, Mac OS X, and Linux. It used to be expensive, but the price for individual developers is now more affordable, and it includes 12 months of free upgrades and support.

· PHP Development Tools (www.eclipse.org/pdt/): PDT is actually a cut-down version of Zend Studio and has the advantage of being free. It runs on Eclipse, the open-source IDE that supports multiple computer languages. If you have used Eclipse for other languages, you should find it relatively easy to use. PDT runs on Windows, Mac OS X, and Linux and is available either as an Eclipse plug-in or as an all-in-one package that automatically installs Eclipse and the PDT plug-in.

· Komodo Edit (http://komodoide.com/komodo-edit/): This is a free, open-source IDE for PHP and a number of other popular computer languages. It’s available for Windows, Mac OS X, and Linux. It’s a cut-down version of Komodo IDE, which is a paid-for program with more advanced features.

So, Let’s Get on with It . . .

This chapter has provided only a brief overview of what PHP can do to add dynamic features to your websites and what software you need to do so. The first stage in working with PHP is to set up a testing environment. The next chapter covers what you need for both Windows and Mac OS X.