Chapter 1. PHP: What, Why, and Where?

PHP is ultimately just text that is taken by your web server and turned into a set of commands and information for your web browser. And because you’re just working in text, there’s not a lot you have to do to get going as a PHP programmer. You need to become familiar with PHP itself, and the best way to do that is to install PHP on your own computer as well as becoming familiar with how PHP runs on a remote web server.

Then, you need to run an actual script. Don’t worry; it’s amazingly easy to write your first program in PHP. Not only that, you’ll run your script, upload it to your web server, and access your script with a web browser…and that’s all in the first two chapters!

Throughout the process, you’ll begin taking control. With PHP, you become an active participant in your web pages. PHP lets you listen carefully to your users and say something back. So get going; there’s no reason to leave your users with passive HTML pages any longer.

PHP Comes in Two Flavors: Local and Remote

One of the most difficult things to get a handle on when it comes to PHP programming doesn’t have much to do with programming at all. It’s figuring out just how PHP runs, how it interacts with your web browser and web server, and why it’s not possible to just double-click a PHP file on your hard drive and see the script in that file run.

HTML and CSS Run Within a Web Browser

First, it’s worth thinking back to when you were a wee programmer, writing your first HTML page. You could save that page in a file, name that file with a .html extension, and boom—you had a web page. Double-click that file, and on most computers, you see that page open up in a web browser. That’s because just as a .doc file is connected to the Microsoft Word program, a .html file is connected to a web browser (specifically, the browser you’ve chosen as the default on your computer). Figure 1-1 should give you an idea.

Web browsers know all they need to know in order to load and display an HTML page. No extra software or configuration is necessary.

Figure 1-1. Web browsers know all they need to know in order to load and display an HTML page. No extra software or configuration is necessary.

If you keep thinking back, you probably added some styling to your HTML pages. Using the style attribute and <style></style> tags in your HTML document, you could change fonts, add striping to your table rows, and generally spice up otherwise boring text.

Then, at some point, some well-meaning web designer slapped your hand and insisted that you start writing all your CSS in external style sheets, and referencing those files in the head of your HTML, like this:

<link rel="stylesheet" href="styles/mysite.css" type="text/css" />

You might even have a few style sheets for the benefit of people viewing your website on mobile devices or printing out a page:

<link rel="stylesheet" href="styles/mysite.css" type="text/css" media="all" />
<link rel="stylesheet" href="styles/print.css" type="text/css" media="print"
/>

But you can still double-click that HTML file, and your browser knows what to do (see Figure 1-2). That’s because, once again, the web browser is completely capable of not just rendering HTML, but applying all those CSS styles to the page, too. Again, no extra software needed.

At this point, even though you’re using only two technologies—HTML and CSS—you need only a single program to handle those technologies: the web browser.

As was the case with HTML, web browsers don’t need any extra help or plug-ins to turn your textual CSS descriptions into styles and apply those styles to your HTML elements.

Figure 1-2. As was the case with HTML, web browsers don’t need any extra help or plug-ins to turn your textual CSS descriptions into styles and apply those styles to your HTML elements.

JavaScript Adds Complexity, but Not Software

Next up in the pantheon of web technologies that every designer and fledgling programmer needs to learn: JavaScript. Suddenly, you weren’t limited to elements that never moved and text that never changed. Whether it was simple phone number validation, more advanced jQuery functions that turned boring gray boxes into animated buttons and <div> elements into tabs, or even the new HTML5 canvas object, within which you could build entire JavaScript-based 3D games, your pages suddenly had new life with JavaScript.

But just as with HTML and CSS, JavaScript is at heart a web technology, and even more specifically, a browser-based technology. In other words, support for JavaScript is part and parcel of your web browser. In fact, if a new version of JavaScript were to appear—something that rarely happens these days—you’d need to download a new version of your browser to get that version of JavaScript. Just as you can’t upgrade your HTML installation outside of your browser, you can’t upgrade your JavaScript installation outside of your browser.

Figure 1-3 shows you how JavaScript fits in (hint: just as HTML and CSS do).

The web browser can handle your JavaScript, too. That browser is doing a lot behind the scenes.

Figure 1-3. The web browser can handle your JavaScript, too. That browser is doing a lot behind the scenes.

Note

The code that handles your HTML and CSS isn’t quite as disconnected as it might appear from Figure 1-2 and Figure 1-3. In other words, there are no individual components in your web browser that render HTML or CSS. But you get the idea; your browser can handle all these different tasks and technologies and turn them into a web page.

PHP Is Not Part of Your Browser

And here’s where things change from the easy, browser-centric view of the world. When you download a web browser, you get HTML, CSS, and JavaScript, but you do not get PHP. PHP scripts—which you’ll soon be writing—have to be interpreted by the PHP interpreter program, called php. And, you can’t just add a PHP interpreter to your browser. It doesn’t know what to do with scripts and isn’t built to interpret PHP.

Instead, you need PHP on a web server. It’s the web server—not the web browser—that can interact with a PHP interpreter. Your browser can handle HTML on its own, but it has to make a request to a web server to deal with PHP scripts. That server can take your PHP scripts and run them, and then take the response and send it back to your browser. Your browser can then understand and handle the response.

So, Figure 1-4 adds a couple of new wrinkles: the PHP interpreter, the magical thing that takes the PHP scripts you’ll be writing and does something useful with them; and a web server to communicate with that interpreter. These both live outside of your web browser. In this scenario, the browser now makes a request to the server and then takes the response and shows it to you.

Web browsers handle HTML, CSS, and JavaScript using the browser’s own code. But PHP scripts have to be handed off to another program, and that program deals with the scripts, returning something useful (hopefully!) to a web server, which then can pass a response back to the web browser. (As was the case with earlier diagrams, this is a bit of an over-simplification. The PHP interpreter interacts closely with your web server, and so doesn’t stand quite so far outside the server as it might appear.)

Figure 1-4. Web browsers handle HTML, CSS, and JavaScript using the browser’s own code. But PHP scripts have to be handed off to another program, and that program deals with the scripts, returning something useful (hopefully!) to a web server, which then can pass a response back to the web browser. (As was the case with earlier diagrams, this is a bit of an over-simplification. The PHP interpreter interacts closely with your web server, and so doesn’t stand quite so far outside the server as it might appear.)

Here’s the basic process:

  1. A web browser makes a request for some page. That page might be a URL on a remote web server, or a local file on your computer.

    Warning

    Right away, there’s potential for trouble here. If the browser requests a local HTML, CSS, or JavaScript file, there’s no problem. That’s because, as you now know, browsers can handle those file types. But if it requests a PHP file without going through a web server you’re not going to get a response that the browser can handle on its own.

  2. Assuming that the request goes to a web server, the web server returns HTML (and CSS and JavaScript) or, in the case of PHP, passes the PHP request on to the PHP interpreter.

  3. The PHP interpreter does what it’s supposed to: it interprets, or runs, the PHP. The result of that should be something that a browser can understand, like HTML. It passes this result, or response, back to the web server.

  4. The web server gives the browser back something that the browser can understand: the HTML result of interpreting a PHP script, or CSS, or JavaScript, or a combination of all of the above.

Understanding this difference in how PHP works, as opposed to HTML, CSS, and JavaScript, is important because it determines the approach you’ll take to writing PHP scripts and getting those scripts to run.

Write Anywhere, Run Where There’s PHP

The cool thing about HTML, CSS, and JavaScript is that because they’re built in to browsers and you can download browsers so easily, those technologies become instantly available. It’s tough to even find a computer without a browser preinstalled. So, you turn on your computer for the first time, and boom, you can start creating web pages immediately. Double-click the HTML file, your browser fires up, and you’re good to go.

But PHP isn’t part of that browser. It’s not always preinstalled. If you write a PHP script and then double-click it, you’ll probably see a code editor launch, but not something that will actually run that script. Even worse, if your browser does open up your PHP script, it’s not a web server. It doesn’t have a PHP interpreter. It will just show you your code, rather than run it, and what good is that to anyone?

This long prelude is just a big warning: although it’s easy enough to start writing PHP scripts, you can’t just open them in Dreamweaver or Firefox and expect them to run. You’ll end up frustrated and annoyed, and that’s no good for anyone.

The bottom line is this: You can write PHP on your own local computer, but you’ve got two choices for actually running that PHP:

  1. You can go through the lengthy process detailed in the next section and install PHP on your local computer. This process will take some time, and you’ll have to monkey around a bit with your computer at a system and network level. You’ll also need a local web server to handle the PHP interpreting part of the gig. This way, you’ll not only have a browser that can handle HTML, CSS, and JavaScript, but a complete setup that can take on PHP without a problem, too—right on your own computer.

  2. You can write your scripts locally and always upload them to an Internet Service Provider (ISP) or web hosting company. Every ISP and web hosting company supports PHP, and you usually don’t have to do anything more than name your scripts with a .php extension. This option involves less initial setup, but it means that every time you edit your script, you need to upload it again to your ISP. It also means that double-clicking your PHP script won’t do anything more than, at best, open your editor. You can’t test your scripts on your own computer.

Both choices are equally good, and which one you choose depends largely on your circumstances. Even though it might seem perfectly natural to jump right into uploading your scripts, you aren’t always going to have a network connection. (The sound you just heard was the cheering of all the programmers who have an hour-long commute into work on their local metro or subway!) For those unwired situations, it’s nice to be able to keep developing on your own computer without the need to access your hosting provider. Note only that, installing PHP on your own computer is great for understanding what the PHP interpreter actually does.

So, before you start writing scripts that you can’t even run, it’s time to get PHP working on your own computer (if you want to), and then talk about getting scripts running out there in the wild, as well.

Note

In the long run, you probably want to have both a way to use of PHP and MySQL without an Internet connection and a hosting provider or ISP set up. That way, you can work on your own computer whenever you want, and then upload your scripts when they’re ready to see the light of day.

PHP: Going Local

It’s not difficult to install PHP on your own computer. This is typically called a local installation, which just means that all your programs are running on your own local machine. (For more detail on how the whole thing works, see the box on Local Software Runs on localhost.)

Although PHP isn’t preloaded on every computer like web browsers are, it’s still easy to download PHP from the Internet, get it working on your computer, and get up and running fast…all without spending a dime. On top of that, most of the easiest and best tools for writing PHP code are also free. You just have to know where to find them.

Note

The next section explains how to install PHP on computers running Microsoft Windows. If you have a Macintosh, flip to PHP on the Mac (Default Installation).

PHP on the Windows-Based Computers (WampServer Installation)

Open your favorite web browser and head to www.wampserver.com. This is the online home of WAMP, which stands for Windows, Apache, MySQL, PHP. The site is shown in Figure 1-5.

Note

Although the website is called WampServer—and describes the grouping of software “Apache, PHP, MySQL on Windows”—the WAMP acronym lives on.

Select the relevant Download link for your version of Windows. If you’re not sure, you can go to your Control Panel, select System, and then poke around. You’ll see either “32-bit Operating System” or “64-bit Operating System,” and that tells you what you want. Just select the first link on the top-left of the page that matches your system.

When downloading starts, you see a warning—actually, a couple of them—about needing some C++ extensions. Click the link for your system (see Figure 1-6), download the extensions (see Figure 1-7), and then run the downloaded file. You’ll need to allow the downloaded program to update your system, accept a license agreement, and install the extensions. When that’s complete, a screen appears like the one in Figure 1-8.

Wampserver.com brings together everything you need for getting PHP and MySQL going and behaving on your Windows PC.

Figure 1-5. Wampserver.com brings together everything you need for getting PHP and MySQL going and behaving on your Windows PC.

WampServer requires some extra work on your part before it can install, most notably, you need to download some C++ extensions to get everything in the PHP interpreter behaving.

Figure 1-6. WampServer requires some extra work on your part before it can install, most notably, you need to download some C++ extensions to get everything in the PHP interpreter behaving.

Microsoft hosts the C++ libraries that WampServer depends on to install.

Figure 1-7. Microsoft hosts the C++ libraries that WampServer depends on to install.

Finally! The C++ extensions are installed. Now you can get back to actually installing WampServer.

Figure 1-8. Finally! The C++ extensions are installed. Now you can get back to actually installing WampServer.

Once you’ve installed the C++ extensions, go back to Wampserver.com, select Downloads again, and then click the download link. This time, you can ignore the warning. Click the words “you can download it directly.”

The ad-heavy site you’re taken to will trigger a download in a few seconds. Then, save and run that file; you’re finally installing WampServer. Figure 1-9 is what you’re aiming for.

All that work for the little pink “W” logo. It’s worth it, though. Installing PHP manually (as detailed in the appendixes) makes this look like a walk in the park.

Figure 1-9. All that work for the little pink “W” logo. It’s worth it, though. Installing PHP manually (as detailed in the appendixes) makes this look like a walk in the park.

Accept the license and default installation directory (typically C:\wamp). You might want to create a quick link icon, or at least a desktop shortcut, and then let installation take off. Select your default browser. You’ll then be asked about allowing Apache to access public networks (Figure 1-10). The best option here is usually the default supplied by the WampServer installer.

Unless your computer is directly connected to the Internet and has its own dedicated, publicly available IP address, the default options are just fine here.

Figure 1-10. Unless your computer is directly connected to the Internet and has its own dedicated, publicly available IP address, the default options are just fine here.

You then have a few other options for PHP mail, and then you’re finished. Launch WampServer, and you should see…nothing! Well, almost nothing. On the right side of the taskbar, notice there is now a little green “W” (check out Figure 1-11).

Now you’ve got WampServer running happily in the background. For your troubles, though, it appears you’ve only got this little green “W” icon.

Figure 1-11. Now you’ve got WampServer running happily in the background. For your troubles, though, it appears you’ve only got this little green “W” icon.

Click the green W icon to see all of the things you’ve been reading about, like PHP, MySQL, and Localhost, as shown in Figure 1-12.

You can do a lot from the WampServer icon: start and stop the new programs you’ve installed, use the handy-dandy phpMyAdmin tool (which you’ll see more of in Chapter 7), and more. You’ll use almost everything here before you’re done.

Figure 1-12. You can do a lot from the WampServer icon: start and stop the new programs you’ve installed, use the handy-dandy phpMyAdmin tool (which you’ll see more of in Chapter 7), and more. You’ll use almost everything here before you’re done.

You’re almost done. Select the top option, Localhost. (If you don’t remember what localhost means, see the box on Local Software Runs on localhost.) A new web browser window or tab opens with an address that references your own locally installed web server. This Server Configuration page presents information about your own web server setup (see Figure 1-13). It isn’t particularly impressive to look at, but it ’s proof that your Windows computer can now serve up web pages.

While on the Server Configuration page, in the Tools section (about halfway down the page), click the phpinfo() link. A page opens that looks something like Figure 1-14, which is everything you’ll ever need to know about your local PHP installation.

More important, it means that your browser made a request to a web server, and that web server processed some PHP (the phpinfo function) and handed back a response to your browser. Not only can you run PHP on your computer, you just did.

Having a web server running on your local computer isn’t necessary for developing HTML, CSS, or most JavaScript applications. But because a browser can’t interpret PHP, a local web server is essential if you want to write PHP scripts on that computer and run them without uploading them to a server somewhere.

Figure 1-13. Having a web server running on your local computer isn’t necessary for developing HTML, CSS, or most JavaScript applications. But because a browser can’t interpret PHP, a local web server is essential if you want to write PHP scripts on that computer and run them without uploading them to a server somewhere.

And the big win: PHP is running! Actually, your browser made a request to your local web server, your local web server executed some PHP, and then it responded to your browser with the response from that PHP command.

Figure 1-14. And the big win: PHP is running! Actually, your browser made a request to your local web server, your local web server executed some PHP, and then it responded to your browser with the response from that PHP command.

You’ve got PHP! Now it’s time to get scripting.

PHP on the Mac (Default Installation)

If you’ve got a Mac, you’ve got more than just a sleek, shiny machine and way too many ways to spend even more money with Apple, you’ve already got PHP installed. To prove it, open the Terminal application on your Mac. If you’ve never used Terminal, don’t worry; you’ll get used to it quickly and find it’s one of your best friends for working with PHP. Go to Applications→Utilities→Terminal.

Note

You can also get to the Applications folder in a flash by pressing Shift-⌘-A. However, this keyboard shortcut works only in the Finder. If you’re currently viewing this book in an e-reader or online, for example, click your desktop and then press Shift-⌘-A. Shift-⌘-A is a little-known shortcut, but if you’re the programming type, you’re probably all about keyboard shortcuts.

Once you’ve found the Applications folder, open it and find the Terminal application. It looks like a computer monitor with a black screen and a little white arrow, as shown in Figure 1-15.

The Terminal program lets you use a command line on Macintosh computers. A lot of your PHP coding will be done by using Terminal, so you’ll get used to this application quickly.Open it, and you see a barebones screen like the one in Figure 1-16.

Figure 1-15. The Terminal program lets you use a command line on Macintosh computers. A lot of your PHP coding will be done by using Terminal, so you’ll get used to this application quickly. Open it, and you see a barebones screen like the one in Figure 1-16.

Tip

You’ll often use Terminal for testing your PHP programs before you upload them to your server. To make it easier to launch Terminal, drag the icon onto your dock.

When you first open Terminal, you won’t be too impressed. You’ll get a line that probably matches your computer’s name and then a weird dollar sign. Don’t worry…this will all soon be old hat.

Figure 1-16. When you first open Terminal, you won’t be too impressed. You’ll get a line that probably matches your computer’s name and then a weird dollar sign. Don’t worry…this will all soon be old hat.

To ensure that PHP is installed on your system, type php (all in lowercase letters) and press Enter. Unfortunately, the way to know things are working is if you don’t see anything but that blank cursor, a little further down in Terminal. It won’t even blink at you anymore; it’s just a boring, dark gray square.

Press Control-C to stop that single eye from hanging around and to display the blinking cursor again. This time, type which php. The which command lets you know where on your computer the program you type is located. In this case, you’re asking where the php program is located. You’ll probably get something back that looks like Figure 1-17; for the computer in this example, php is in the /usr/bin directory. You’ll probably get a similar result.

Lots of the programs you’ll use in Terminal are scattered around your Mac’s hard drive. The which command lets you know exactly where a program resides on your machine.

Figure 1-17. Lots of the programs you’ll use in Terminal are scattered around your Mac’s hard drive. The which command lets you know exactly where a program resides on your machine.

Once you’ve seen where php is, you’re ready to go. It was installed all along.

PHP on the Mac (MAMP Installation)

Although it’s nice that Macs come with PHP already installed, there might just be a better option—one worth doing a bit of downloading and installing for yourself. That better option is MAMP, which stands for Mac, Apache, MySQL, PHP. This is the Mac counterpart to WAMP, the easy Windows PHP installation (PHP on the Windows-Based Computers (WampServer Installation)) that you, as a Mac user, probably skipped.

MAMP doesn’t improve on the PHP installation that came on your Macs; it does integrate MySQL—which you’ll need before you know it—as well as the Apache web server and several helpful tools for working with PHP scripts and MySQL databases. You even get a simple control panel for starting up your local web server and MySQL database. Those additions are a nice perk, and coupled with how easy it is to install MAMP, you might just want to ditch the default PHP installation and get MAMP going.

First, using your favorite web browser, visit www.mamp.info. A site like the one shown in Figure 1-18.

The MAMP site is a PHP developer’s best friend. The free MAMP download gives you almost everything you could want for developing great PHP scripts and the databases with which they work.

Figure 1-18. The MAMP site is a PHP developer’s best friend. The free MAMP download gives you almost everything you could want for developing great PHP scripts and the databases with which they work.

Simply click the “Download now” button under MAMP and then grab a coffee and wait for the installer to download.

Now, launch the installer. Click Next a few times to select your hard drive and agree to the license. Keep going until the installer informs you that MAMP is ready to install, as shown in Figure 1-19.

Note

Some versions of MAMP don’t have a correctly signed security certificate. This results in a nasty message popping up when you try to launch the installer: “MAMP_2.1.1.pkg can’t be opened because it is from an unidentified developer.”

Fortunately, you can safely ignore this for MAMP. Just Control-click the installer, and then in the popup menu that appears, you can click “Open.” This will in turn give you a dialog box, and you can click “Open” yet again. Finally, you’ll have your program ready to run. Fortunately, you should only have to do this once.

MAMP is simple to install but it eats up about half a gigabyte of disk space. That’s ok; you’re getting a full-blown web server, PHP interpreter, MySQL database, and a suite of tools.

Figure 1-19. MAMP is simple to install but it eats up about half a gigabyte of disk space. That’s ok; you’re getting a full-blown web server, PHP interpreter, MySQL database, and a suite of tools.

Once the installation is complete, go to Applications → MAMP. You’ll see a nifty control panel, a la Figure 1-20.

This control panel is MAMP’s home base. You can start and stop software components and make all your configuration changes here. While you’re getting your PHP feet wet, you may want to move the MAMP icon into your dock; you’ll be using it a ton.

Figure 1-20. This control panel is MAMP’s home base. You can start and stop software components and make all your configuration changes here. While you’re getting your PHP feet wet, you may want to move the MAMP icon into your dock; you’ll be using it a ton.

Your installation might try to automatically start both an Apache server and the database. Still, you can configure these easily by clicking the Preferences button. You should probably check the Ports tab and ensure that there aren’t any issues with any other software on your computer. You can do this all within MAMP, as shown in Figure 1-21.

MAMP lets you change both the port that Apache (the web server) runs on, as well as the port that MySQL runs on. Be especially careful with the MySQL port. Most programs that use MySQL will need to be updated to the value you use here.

Figure 1-21. MAMP lets you change both the port that Apache (the web server) runs on, as well as the port that MySQL runs on. Be especially careful with the MySQL port. Most programs that use MySQL will need to be updated to the value you use here.

Note

If all this talk of ports is starting to give you a headache, that’s okay. It probably just means that your machine is set up without any software running on weird ports, and that makes things easy here: just accept the defaults. These are pretty standard ports, and will almost always work perfectly with a system.

You can also click the PHP Preferences option and see a few things that, honestly, probably don’t matter much to you (see Figure 1-22). Just leave these alone. In fact, there’s almost never a reason to mess with these selections. Mostly, it’s good to know that yes, MAMP did indeed install PHP (along with a web server and MySQL) with just a few mouse clicks.

There are some reasons you might one day want to jump back from PHP 5.3 to 5.2, but that’s far down the line. For now, just accept these options as they are and get ready to start scripting.

Figure 1-22. There are some reasons you might one day want to jump back from PHP 5.3 to 5.2, but that’s far down the line. For now, just accept these options as they are and get ready to start scripting.

There’s not much else to do now, so you can close Preferences and click the “Open start page” option to get a nice browser page like the one shown in Figure 1-23. Here’s where you’ll spend lots of your troubleshooting time as well as digging into databases once you’ve mastered the command line tools for MySQL that you’ll learn about in Chapter 4.

Here’s where you’ll do most of the work once you have your MAMP software running. Think of the MAMP control panel as the place you’ll control the programs, and this start page as where you’ll interact with those programs.

Figure 1-23. Here’s where you’ll do most of the work once you have your MAMP software running. Think of the MAMP control panel as the place you’ll control the programs, and this start page as where you’ll interact with those programs.

Before moving on, you can verify that this is all doing what it should. At the top of the MAMP start page, click the “phpInfo” tab. A screen appears, similar to that in Figure 1-24. What ’s significant here isn’t all the information listed; you needn’t concern yourself with that just yet. What is cool, though, is that you’re looking at a PHP script that’s been interpreted by a PHP interpreter (installed as part of MAMP). The interpreter then fed the output of that script to your new MAMP-installed web server, which in turn handed that response to your web browser. Proof that you’re already running PHP.

This page is actually the output of the phpinfo function in PHP. Here’s the proof that you’ve got what you need to run PHP scripts on your local machine. In fact, you just ran one.

Figure 1-24. This page is actually the output of the phpinfo function in PHP. Here’s the proof that you’ve got what you need to run PHP scripts on your local machine. In fact, you just ran one.

Get Out Your Text Editor

All the programs you’re going to write in PHP are plain, old text files. Writing PHP isn’t a lot different than writing HTML or CSS or JavaScript. You’ll type different things, of course, but these are all just text files saved with a special extension. You use .html for HTML, .css for CSS, .js for JavaScript, and now you’ll use .php for PHP files.

Because PHP is just text, you’ll want a good text editor in which to work. If you’re in Windows, you can use Notepad. As simple as that program is, it’s perfect for coding in PHP. If you’re on a Mac, TextEdit is a great choice. The good news is that each of these programs comes preinstalled on your computer, so you don’t have to download or buy anything. The bad news is that none of these programs know you’re writing PHP, so you don’t get much help if you type something wrong or want to organize your files without resorting to Windows Explorer or the Finder. These programs are simple, but limited.

On the other hand, there are quite a few editors out there that are built specifically to handle PHP. For instance, for Windows, you can download NuSphere PhpED (nusphere.com/products/phped.htm), which is shown in Figure 1-25. You’ll pay a bit for a program like NuSphere—usually between $50 and $100—but you’ll get fancy color coding, help with special language features, and in a lot of cases, some nifty file organization features and the ability to upload your PHP directly to your web server.

NuSphere PhpED gives you a ton of features and supports JavaScript, CSS, and HTML, as well as PHP. It also has great documentation for most of the PHP functions and libraries.

Figure 1-25. NuSphere PhpED gives you a ton of features and supports JavaScript, CSS, and HTML, as well as PHP. It also has great documentation for most of the PHP functions and libraries.

If you’re on a Mac, the two leading candidates for editors that do text plus lots of other cool things are BBEdit (www.barebones.com/products/bbedit/index.html) and TextMate (www.macromates.com). Both are Mac-only programs, and both offer similar features on the Mac as does PhpED for Windows: color-coding, file management, help documentation, and support for HTML, CSS, JavaScript, and a lot more. You can see BBEdit in action in Figure 1-26; you’ll need to drop $100 to get your own copy, though.

BBEdit is supposed to be bare bones, but you’ll find it has more than adequate PHP support. It’s tuned primarily for HTML, so there are a few oddities, but it’s a great choice for PHP work on the Mac.

Figure 1-26. BBEdit is supposed to be bare bones, but you’ll find it has more than adequate PHP support. It’s tuned primarily for HTML, so there are a few oddities, but it’s a great choice for PHP work on the Mac.

You can see what TextMate looks like in Figure 1-27. It ’s a little simpler than BBEdit, so if you’ve never used a programming editor, this might be easier to begin with. TextMate costs around $60, slightly less than BBEdit.

TextMate is an editor that seeks to provide color-coded editing and not much else. It does offer file management and FTP support, but it’s best at letting you type code and staying out of the way.

Figure 1-27. TextMate is an editor that seeks to provide color-coded editing and not much else. It does offer file management and FTP support, but it’s best at letting you type code and staying out of the way.

Once you’re comfortable writing PHP code, you can spend some time playing with all these different enhanced editors. You can see what you like, discover whether an editor is perfect for you, or realize you’re a Notepad or TextEdit programmer at heart. There’s no one right option for PHP; all of these choices work just fine.

If you’re just starting out, though, try to use a simple text editor—Notepad on Windows or TextEdit on the Mac. You’ll learn a lot more about PHP this way, even if you don’t get all the bells and whistles of one of the full-featured editors. Besides, once you understand PHP and have learned to work with it manually, you’ll appreciate and be able to use the features of the other editors a lot more effectively.

Note

Once you’ve become familiar with PHP, you can also check out Eclipse PHP (www.eclipse.org). The Eclipse IDE has long been a favorite for Java developers, and there are now enough plug-ins for PHP that it’s a legitimate option for PHP programmers, too. However, there’s a lot going on in Eclipse—tons of tools and gadgets—so you might want to wait a bit before you dive head first into it. Come back to it later, though; it’s well worth checking out.

Write Your First Program

You’ve got PHP installed locally and you’ve got a text editor. Now all you need is an actual program. Start your text editor and type the following code, exactly as shown here:

<?php

   echo "Hello there. So I hear you're learning to be a PHP programmer!\n";
   echo "Why don't you type in your name for me:\n";
   $name = trim(fgets(STDIN));

   echo "\nThanks, " . $name . ", it's really nice to meet you.\n\n";

?>

Note

You can find a copy of this script on this book’s Missing CD page at www.missingmanuals.com/cds/phpmysqlmm2e.

A lot of this probably looks weird, and that’s OK. You’ll soon understand every bit of this code. Right now, just get used to looking at PHP, which is quite different from HTML or JavaScript.

Warning

Some of the editors you might use, like TextEdit, will try to save the document as rich text. Rich text lets you use formatting, like bolding and underlining. You don’t want that in your PHP code, so look for the option to use plain text, which doesn’t provide formatting.

If you’re using TextEdit, choose Format→Make Plain Text. (You won’t see that option if you’re already working in plain text.) If you’re using Notepad, rich text isn’t an option, so you’ve got nothing to worry about.

Once you’re done, your editor should look similar to Figure 1-28.

PHP is just text, but it uses several weird characters. Start getting used to typing the dollar sign ($), angle brackets (< and >, just like in HTML), and the backslash (\). You’ll be using those characters a lot.

Figure 1-28. PHP is just text, but it uses several weird characters. Start getting used to typing the dollar sign ($), angle brackets (< and >, just like in HTML), and the backslash (\). You’ll be using those characters a lot.

Note

You won’t see the nice color-highlighted syntax until you save your file with a .php extension.

This program does just a few simple things:

  • Identifies itself as PHP by using <?php.

  • Prints out a welcome message by using the echo command.

  • Asks the user for her name, again by using echo.

  • Gets the user’s name and stores it in something called $name.

  • Says hello to the user by printing out a message that includes the information stored in $name.

  • Finishes up with the ?> characters.

It’s okay if not much on this list makes sense yet, especially the weird line beginning with $name =. There are also some strange characters like \n and STDIN that you’ll learn about soon. But see if you can follow the plain-English words through the basic path: the opening <?php, the printing, the request for the user’s name, another bit of printing, and the closing ?>.

Now, save this program. Name it sayHello.php, and ensure that you add that .php extension! Otherwise, you’ll have a lot of problems down the line. Save the file some place handy, like on your desktop, your home directory, or a folder you’re using to keep all your PHP programs in as you’re learning.

Warning

Most programs in Windows and on the Mac append a default extension, like .txt. Make sure you replace this with .php. Windows especially tends to hide extensions, so verify that your full filename is sayHello. php, not something like sayHello.php.txt.

That’s it; you’ve written your first PHP program!

You can get to the TextEdit preferences via the Preferences menu, or by using the shortcut combination ⌘-period. In the Preferences box, you’ve got lots of options, but the text format and font used for plain text are the most important for now.

Figure 1-29. You can get to the TextEdit preferences via the Preferences menu, or by using the shortcut combination ⌘-period. In the Preferences box, you’ve got lots of options, but the text format and font used for plain text are the most important for now.

Run Your First Program

What good is it to get all this code typed in if you can’t see if it works? This particular program isn’t ready to run on the Web yet; first you need to add something to it in your command-line terminal program, so go ahead and fire that up. If you’re on the Mac, you should open up Terminal. In Windows 7 or earlier, go to Windows Start →Run and then run command or cmd from the menu to get a command line. In Windows 8, at the start screen, press Windows key + R and then type cmd (as shown in Figure 1-30).

In Windows 7 (left) and earlier, you can get to the command line via the Start menu. Since Windows 8 doesn’t have a Start menu, just go to the Start screen and press Windows key+R. That opens the Run box where you can type cmd.

Figure 1-30. In Windows 7 (left) and earlier, you can get to the command line via the Start menu. Since Windows 8 doesn’t have a Start menu, just go to the Start screen and press Windows key+R. That opens the Run box where you can type cmd.

Now, go to the directory in which you saved your program, sayHello.php. You can do a directory listing with dir (in Windows) or ls (on the Mac) to ensure that you’re in the right directory. Once you’re in the right directory, type this into your command line:

php sayHello.php

This instructs the php program to run and gives it your program, sayHello.php, as the script to run. In short order, you should see the welcome message you typed, and then the program asks you for your name. Type your name and press Enter. The program should then greet you, just as shown in Figure 1-31.

Eventually, you’ll run most of your PHP scripts through a web browser. For now, though, the command line lets you take control of the php command and give it a particular script to run so that you can see the output on the command line.

Figure 1-31. Eventually, you’ll run most of your PHP scripts through a web browser. For now, though, the command line lets you take control of the php command and give it a particular script to run so that you can see the output on the command line.

That’s it! Your first program works, and you’re ready to go deeper into PHP.

But Where’s That Web Server?

Before you take that well-deserved break, there’s one question left to answer. Remember way back to the discussion about a PHP interpreter interacting with a web server? All that business about PHP running locally or running remotely? Uploading files, web hosting providers; remember all that stuff? If not, Figure 1-32 should be a helpful refresher as to how PHP usually functions.

Remember this diagram from earlier? Even though it hasn’t applied to your first PHP program, it still holds true. As soon as you start writing scripts that interact with web pages, you’re going to need a web server.

Figure 1-32. Remember this diagram from earlier? Even though it hasn’t applied to your first PHP program, it still holds true. As soon as you start writing scripts that interact with web pages, you’re going to need a web server.

So what gives? You installed PHP locally and ran your script without problem, but a web browser wasn’t involved

The PHP Interpreter Is a Program You Can Run

The PHP interpreter that’s shown in Figure 1-32 is just a program, like dir or ls or which or anything else you can type into a command-line or terminal window. And just like those other programs, you can run it on your scripts manually. In fact, that’s just what you did. You ran the PHP interpreter (php) on your script, because you installed WampServer or, if you’re on a Mac, because php is already installed.

But, this sort of script—where all it does is output some text—is not the typical PHP script. It’s more of a “blow bubbles in the kiddie pool” script: helpful to get started, but just the tiniest taste of what’s coming.

So, you don’t need a web browser or a web server. You just needed the PHP interpreter. Because of that, there’s no sense uploading your script and trying to find the PHP interpreter on your hosting provider, which requires shell access, which in turn might require calling up tech support and spending 20 minutes on the phone giving out maiden names and birthdates…in other words, it’s just not worth it.

But, the HTML Is Coming…

Keep those credentials handy, though, because in the next chapter, you will start uploading your scripts. You’ll move beyond simply outputting text and begin to output HTML. You’ll take input from an HTML form and churn back out styled, web-friendly responses. And, you’ll move from using just a local PHP installation to using a remote one.

Buckle up, take that break, and head on over to Chapter 2.

Get PHP & MySQL: The Missing Manual, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.