Chapter 1
In This Chapter
Introducing server-side programming
Testing your installation
Inspecting phpinfo( )
Writing HTML with embedded PHP
Understanding various types of quotation
Managing concatenation and interpolation
Using heredocs to simplify coding
Welcome to the server-side programming portion of the book. In this minibook, you discover all the basics of PHP and how you can use PHP to make your pages dynamic and relevant in today's Internet.
In this chapter, you read about getting your server set up and ready to go. I walk you through the process as painlessly as possible, and by the end, you'll be up and running, and ready to serve up your own web pages in a test environment. (I talk about making them available to the rest of the world in Book VIII.)
I begin with an introduction to server-side programming. This is a bit different than the client-side programming you may have done in JavaScript.
Server-side programming is what you use to create pages dynamically on the server before sending them to the client. Whereas client-side programming is executed on the client's machine, server-side programming all happens on the server before the web page is even sent to the user.
Client-side programming (as done in JavaScript) does most of the work on the individual user's machine. This has advantages because those machines have doohickeys such as mice and graphics cards. Client-side programs can be interactive in real time.
The client has a big problem, though. Programs written on the client usually have a form of forced amnesia (no long-term memory). For security reasons, client-side applications can't store information in files and can't interact with other programs on the computer. Also, you never know exactly what kind of setup the user has, so you can't really be sure whether your program will work.
This is where server-side programming comes in. In a pure server-side programming environment, all the action happens on the web server. The user thinks she's asking for a web page like normal, but the address really goes to a computer program. The program does some magic and produces a web page. The user sees a web page, perhaps never knowing this wasn't a regular web page, but a page that was produced instead by a program.
A program running on a web server has some really nice advantages, such as
When using a browser to retrieve web pages, you send a request to a server. The server then looks at the extension (.HTML, .php, .js, and so on) of your requested file and decides what to do. If the server sees .HTML or .js, it says, “Cool. Nothing doing here. Just gotta send her back as is.” When the server sees .php, it says, “Oh, boy. They need PHP to build something here.”
The server takes the page and hollers for PHP to come along and construct the requested web page on the fly. PHP goes through and looks at the programmer's blueprint and then constructs the working page out of HTML.
The server then takes that page from PHP and sends back plain HTML to the client for the browser to display to the user.
When you write PHP programs, a web server must process the form before the browser can see it. To test your PHP programs, you need to have a web server available and place the file in a specific place on your computer for the server to serve it. You can't run a PHP file directly from your desktop. It must be placed in a special place — often, the htdocs or public_html directory under the server.
There are all sorts of different ways to go about dynamically creating web pages with server-side programming. Back in the day when the Internet was still in diapers, people used things like Perl and CGI scripting to handle all their server-side programming. Eventually, people placed more and more demand on their websites, and soon these technologies just weren't enough.
The prevalent languages today are
ASP.NET is event-driven, compiled, and object-oriented. ASP.NET replaced the ’90s language ASP in 2002. Microsoft repurposed it for use with the .NET framework to facilitate cross-compatibility with its desktop applications (apps) and integration into Visual Studio (although you can write ASP.NET apps from any text editor). ASP.NET runs on Microsoft's Internet Information Services (IIS) web server, which typically requires more expensive servers than most of the other technologies. Although ASP.NET is an excellent technology, I don't recommend it for cost-conscious users.
Java has been a strong contender for a long time now. The language is indeed named after coffee. If you work for a banking company or insurance company, or need to build the next eBay or Amazon.com, you might want to consider using Java. However, Java can consume a lot of time, and it's hard to figure out. You may have to write up to 16 lines of code to do in Java what could take a mere 4 lines of code in PHP. Java is absolutely free, as is the Apache Tomcat web server that it uses to serve its web components. Java was originally created to write desktop applications and is still very good at doing that. If you're comfortable with C/C++, you'll be very comfortable with Java because it's very similar. It's fully object-oriented and it's compiled. Java is powerful, but it can be challenging for beginners. It'd be a great second language to work with.
The Python language is used in a number of contexts, including server-side programming. Although Python has become much more popular as of late, it still isn't used as frequently as PHP for this purpose.
PHP was born from a collection of modifications for Perl and has boomed ever since (in a way, replacing Perl, which was once considered the duct tape and bubble gum that held the Internet together).
PHP works great for your server-side web development purposes. Media Wiki (the engine that was written to run the popular Internet encyclopedia Wikipedia) runs on PHP, as do many other popular large-, medium-, and small-scale websites. PHP is a solid, easy-to-learn, well-established language (it was introduced in 1994). PHP can be object-oriented or procedural: You can take your pick. PHP is interpreted rather than compiled.
For PHP to work usefully, you have to have some other things installed on your computer, such as
There are two main ways to work with a web server:
Please check out Book VIII, Chapter 1 for complete information on both techniques. After you have your machine set up or you have an account somewhere with PHP access, come back here. I'll wait.
Using your shiny new server is really quite simple, but a lot of beginners can get confused at this point.
One thing you have to remember is that anything you want the server to serve must be located in the server's file structure. If you have a PHP file on your desktop and you want to view it in your browser, it won't work because it isn't in your server. Although, yes, technically it might be on the same machine as your server (if you're using XAMPP), it is not in the server.
So, to serve a file from the server, it must be located in the htdocs directory of your server install. If you've installed XAMPP, go to the folder where you installed XAMPP (probably either c:/xampp or c:/Program Files/xampp) and locate the htdocs directory. This is where you'll put all your PHP files. Make note of it now.
If you're using a remote server, you'll need to use your host’s file management tools or FTP (both described in Book VIII, Chapter 1) to transfer the file. Often you'll have specially designated folders for placing your web content, usually related to your domain name. You may need to check with your server host to be certain.
To get the hang of placing your files in the correct place and accessing them, create a test file that will display all your PHP, Apache, and MySQL settings.
To test everything, make the PHP version of the famous “Hello World!” program. Follow these steps to make your first PHP program:
PHP files are essentially plain text files, just like HTML and JavaScript. You can use the same editors to create them.
Generally, your PHP pages start out as standard web pages, using your basic HTML template. However, start with a simpler example, so you can begin with an empty text file.
Write a tag to indicate PHP. The starting tag looks like <?php, and the ending tag looks like ?>. As far as HTML is concerned, all the PHP code is embedded in a single HTML tag.
You'll learn a lot more PHP soon, but one command is especially useful for testing your configuration to see how it works. Type the line phpinfo();. This powerful command supplies a huge amount of diagnostic information.
A PHP file can't be stored just anywhere. You need to place it under an accessible directory of your web server. If you're running XAMPP, that's the htdocs directory of your xampp directory. If you're running a remote server, you'll need to move the file to that server, either with your host's file transfer mechanism, an FTP program, or automatically through your editor. (See the nearby sidebar “Picking a PHP editor” for information on remote editing in Komodo.)
Use your web browser to look at the resulting page. Note that you cannot simply load the file through the file menu or drag it to your browser. If you have XAMPP installed, you need to refer to the file as http://localhost/fileName.php. If the file is on a remote server, use the full address of the file on that server: for example, http://myhost.freehostia.com/fileName.php.
Your code from Steps 3 and 4 should look like this:
<?php
phpinfo();
?>
Hmm. Only three lines of code, and it doesn't seem to do much. There's precious little HTML code there. Run it through the browser, though, and you'll see the page shown in Figure 1-1.
This phpinfo page of Figure 1-1 is critical in inspecting your server configuration. It displays all the different settings for your server, describing what version of PHP is running and what modules are active. This can be very useful information.
This test.php program shows one of the most interesting things about PHP. The program itself is just a few lines long, but when you run it, the result is a complex web page. Take a look at the source of the web page, and you'll see a lot of code that you didn't write. That's the magic of PHP. You write a program, and it creates a web page for you.
Don't panic if you don't understand anything in the page that gets produced with the phpinfo() command. It contains many details about how PHP is configured on your server, which may not mean much now. If you have trouble with PHP and ask me for help, however, it's the first thing I'll ask you for. An experienced developer can do a lot of troubleshooting by looking over a phpinfo so it's a handy skill to know.
The basic flow of PHP programming works like this:
PHP programs are almost always designed to create HTML code, which gets passed back to the user. The user will never see PHP code because it will get translated to HTML before it gets to the browser.
In PHP, you aren't actually printing anything to the user. Instead, you're building an HTML document that will be sent to the browser, which will interpret the HTML and then print that (the HTML) to the user. Therefore, all your code gets interpreted twice: first on the server to generate the HTML and then on the user's machine to generate the output display.
If you've used HTML, CSS, and JavaScript, you might have been frustrated because all these environments run on the client, and you have no control of the client environment. You don't know what browser the user will have, and thus you don't know exactly how HTML, CSS, and JavaScript will run there. When you program in PHP, you're working on a machine (the server) that you actually control. You know exactly what the server's capabilities are because (in many cases) you configured it yourself.
It's still not a perfect situation, though, because your PHP code will generate HTML/CSS pages (sometimes even with JavaScript), and those pages still have to contend with the wide array of client environments.
The first program you ever write in any language is invariably the “Hello World!” program or some variant thereof. Follow these steps:
I prefer using Komodo Edit because it has great support for PHP and remote file access.
If you're using some other text editor, just open a plain text file however you normally do that (often File ⇒ New) and be sure to save it under htdocs with a .php extension. If you're using a remote server, transfer your file to that server before testing.
PHP code is usually embedded into the context of an HTML page. Begin with your standard HTML template. (See Book I, Chapter 2 for a refresher on HTML.)
<?php
print “<h1>Hello World!</h1>”;
?>
Depending on your installation of Apache, you may be able to use the shorter <? ?> version of the PHP directive (instead of <?php ?>). However, nearly all installations support the <?php ?> version, so that's probably the safest way to go.
Note that you're not just writing text, but creating an HTML tag. PHP creates HTML. That's a really important idea.
Remember to save directly into htdocs or a subdirectory of htdocs. If you're using a remote server, save remotely to that server (with Komodo) or save it locally and transfer it to the server to view it.
The address of a web page begins with the http:// protocol and then the server name. If the page is on the local machine, the server name is localhost, which corresponds directly to your htdocs directory. If you have a file named thing.php in the htdocs directory, the address would be http://localhost/thing.php. Likewise, if it's in a subdirectory of htdocs called project, the address would be http://localhost/project/thing.php. If the page is on a remote server, the address will include the server's name, like this:
So, what is it that you've done here? You've figured out how to use the print statement. This allows you to spit out any text you want to the user.
There are many different ways to use print. The following are all legal ways to print text, but they have subtle differences:
print ("<p>Hello World!</p>");
print ("<p>Hello World!<br />
Hello Computer!</p>");
print '<p><a href="http://www.google.com">Hello Google!</a></p>';
Any way you cut it, you have to have some form of quotations around text that you want printed. However, PHP is usually used to write HTML code, and HTML code contains a lot of quote marks itself. All those quotations can lead to headaches.
What if you want to print double quotation marks inside a print statement surrounded by double quotation marks? You escape them (you tell PHP to treat them as literal characters, rather than the end of the string) with a backslash, like this:
print "<a href="link.HTML">A Link</a>";
This can get tedious, so a better solution is discussed in the “Generating output with heredocs” section, later in this chapter.
Variables are extremely important in any programming language and no less so in PHP.
A PHP variable can be named almost anything. There are some reserved words that you can't name a variable (like print, which already has a meaning in PHP), so if your program isn't working and you can't figure out why, try changing some variable names or looking at the reserved words list (in the online help at www.php.net) to find out whether your variable name is one of these illegal words.
PHP is very forgiving about the type of data in a variable. When you create a variable, you simply put content in it. PHP automatically makes the variable whatever type it needs. This is called loose typing. The same variable can hold numeric data, text, or other more complicated kinds of data. PHP determines the type of data in a variable on the fly by examining the context.
Even though PHP is cavalier about data types, it's important to understand that data is still stored in one of several standard formats based on its type. PHP supports several forms of integers and floating-point numbers. PHP also has great support for text data. Programmers usually don't say “text,” but call text data string data. This is because the internal data representation of text reminded the early programmers of beads on a string. You rarely have to worry about what type of information you're using in PHP, but you do need to know that PHP is quietly converting data into formats that it can use.
Concatenation is the process of joining smaller strings to form a larger string. (See Book IV, Chapter 1 for a description of concatenation as it's applied in JavaScript.) PHP uses the period (·) symbol to concatenate two string values. The following example code returns the phrase oogieboogie:
$word = "oogie ";
$dance = "boogie";
Print $word . $dance
When PHP sees a period, it treats the values on either side of the period as strings (text) and concatenates (joins) them. If PHP sees a plus sign, it treats the values on either side of the plus sign as numbers and attempts to perform mathematical addition on them. The operation helps PHP figure out what type of data it's working with.
The following program illustrates the difference between concatenation and addition (see Figure 1-3 for the output):
<?php
//from helloVariable.php
$output = "World!";
print "<p>Hello " . $output . "</p>";
print "<p>" . $output + 5 . "</p>";
?>
The previous code takes the variable output with the value World and concatenates it to Hello when printed. Next, it adds the variable output to the number 5. When PHP sees the plus sign, it interprets the values on either side of it as numbers. Because output has no logical numerical value, PHP assigns it the value of 0, which it adds to 5, resulting in the output of <p>5</p> being sent to the browser.
If you have a bunch of text to print with variables thrown in, it can get a little tedious to use concatenation to add in the variables. Luckily, you don't have to!
With PHP, you can include the variables as follows (see Figure 1-4 for the output):
<!DOCTYPE html>
<html lang = “en-US”>
<head>
<meta charset = "UTF-8" />
<title>helloInterpolation</title>
</head>
<body>
<?php
$firstName = "John";
$lastName = "Doe";
print "<p>Hello $firstName $lastName!</p>";
?>
</body>
</html>
This process is called interpolation. Because all PHP variables begin with dollar signs, you can freely put variables right inside your string values, and when PHP sees a variable, it will automatically replace that variable with its value.
The output of a PHP program is usually an HTML page. As far as PHP is concerned, HTML is just string data, so your PHP program often has to do a lot of string manipulation. You'll often be writing long chunks of text (HTML code) with several variables (generated by your PHP program) interspersed throughout the code. This type of text (HTML output) will often stretch over several lines, requires carriage returns to be preserved, and often contains special characters like quotes and <> symbols. The ordinary quote symbols are a little tedious if you want to use them to build a web page. Here's an example.
Say you wanted to create a program that could take the value of the $name and $address variables and put them into a table like this:
<table style = "border: 1px solid black">
<tr>
<td>name</td>
<td>John</td>
</tr>
<tr>
<td>address</td>
<td>123 Main St.</td>
</tr>
</table>
There are a few ways to combine the PHP and HTML code as shown in the following sections.
Using regular double quotes, the code would look something like this:
$name = "John";
$address = "123 Main St.";
$output = "";
$output .= "<table style = "border: 1px solid black">
";
$output .= " <tr>
";
$output .= " <td>name</td>
";
$output .= " <td>$name</td>
";
$output .= " </tr>
";
$output .= " <tr>
";
$output .= " <td>address</td>
";
$output .= " <td>$address</td>
";
$output .= " </tr>
";
$output .= "</table>
";
print $output
However, using quotes to generate HTML output is inconvenient for the following reasons:
PHP uses a clever solution called heredocs to resolve all these issues. A heredoc is simply a type of multiline quote, usually beginning and ending with the word HERE.
The best way to understand heredocs is to see one in action, so here's the same example written as a heredoc:
<?php
$name = "John";
$address = "123 Main St.";
print <<<HERE
<table style = "border: 1px solid black">
<tr>
<td>name</td>
<td>$name</td>
</tr>
<tr>
<td>address</td>
<td>$address</td>
</tr>
</table>
HERE;
?>
Figure 1-5 illustrates this code in action.
Heredocs have some great advantages:
The following are some things to keep in mind about heredocs:
Heredocs have one disadvantage: They tend to mess up your formatting because you have to indent heredocs differently than the rest of the code.
There's one more way to combine PHP and HTML code. The server treats a PHP document mainly as an HTML document. Any code not inside the <?php ?> symbols is treated as HTML, and anything inside the PHP symbols is interpreted as PHP.
This means you can switch in and out of PHP, like the following example:
<?php
$name = "John";
$address = "123 Main St.";
// switch 'out' of PHP temporarily
?>
<table style = "border: 1px solid black">
<tr>
<td>name</td>
<td><?php print $name; ?></td>
</tr>
<tr>
<td>address</td>
<td><?php print $address; ?></td>
</tr>
</table>
<?php
//I'm back in PHP
?>
This option (switching back and forth) is generally used when you have a lot of HTML code with only a few simple PHP variables. I prefer the heredoc approach, but feel free to experiment and find out what system works for you.