PHP Tutorials

Writing a Basic PHP Program

Before we get into an actual program, let’s take a look at the steps we’ll take to create one. The steps aren’t complicated; in fact, they’re basically the same as the steps you use when creating an HTML page and publishing it to your server.

Unlike creating an HTML page, creating a PHP program requires that you actually work with the source code of the file as opposed to a “what you see is what you get” (WYSIWYG) approach. If you’re used to using a WYSIWYG program (such as Microsoft FrontPage, Macromedia Dream Weaver, or Microsoft Word), it may take you some time to get used to looking at the source code.

The good news is there’s no reason that you can’t continue to use a WYSIWYG editor to create an HTML design for your program. However, you may be disappointed to find that many WYSIWYG editors mangle or even delete vital PHP code from your files. For this reason, it is important to find out how your particular editor handles PHP code. If you want to test your WYSIWYG to see how it handles PHP code, create a new file, naming it with a .php extension. Then, switch to your editor’s source view or open the file in a separate program, such as Notepad and enter the program shown in the first example later in the chapter, making sure not to make any mistakes.

When you’re finished, save the file and switch back to the WYSIWYG editor. If you see your PHP code, work around it and type a few lines of text. If you want, add some common elements that you include in your Web pages, such as tables and images. Save the file again and close all the open editors.

Now, open the file in Notepad and look at the PHP code. Look for any changes, including changes in the way the code is formatted, special characters that have been converted into codes (such as < to <), and code that has been completely removed.

You will probably find that the PHP code has been changed in some way. Because PHP is sensitive to some of the changes a WYSIWYG editor might make, it's almost impossible to use a WYSIWYG editor once you've started adding PHP code. The PHP community won't tell you that using a WYSIWYG editor is a sign of weakness; doing so can speed things up a lot sometimes.

For now, try using a plain-text editor when you're reading and experimenting with the examples in this book. When you're comfortable with that, feel free to try it with whatever editor you want. By that time, you'll be able to recognize code that the editor has mangled, and you'll have an easier time finding what works best for you.

Regardless of how your current editor handles PHP code, if you are using a WYSIWYG editor, I suggest that you use an editor such as Notepad or one of the many free syntax-highlighting editors out there. Using one of these programs will ensure that your code stays just as you typed it (WYSIWYG editors tend to reformat things as they see fit, which isn't desirable when coding PHP). Even if your editor passed the test, if it's not a strictly text-based (not WYSIWYG) editor, you might find yourself running into problems later.

Here is the process you might use in creating and viewing an HTML file:

Create your HTML file (add text, tables, images, or sounds).

Save your HTML file as filename.html.

Use an FTP program to upload your file to the Web server.

Point your browser to the address of the file on your Web server (for example, http://www.example.com/filename.html).

The process you would use to create a PHP program is much the same:

Create your HTML file (containing text, tables, images, or sounds) and insert PHP code where desired.

Save your PHP file as filename.php.

Use an FTP program to upload your file to the Web server.

Point your browser to the address of the file on your Web server (such as http://www.example.com/filename.php).

The process of creating a PHP program isn't much different from the process you follow to create a regular HTML page.

CAUTION

Many FTP servers (primarily those on Unix-based systems) require you to use a certain FTP "mode": either binary (for images, sounds, and other non-ASCII files) or ASCII (for plain-text files, such as HTML, PHP, and TXT).

Although the FTP transfer appears to be successful, a program transferred in binary mode may not run at all. If this happens, you will receive a "500 Internal Error" response from the server.

Now that you've seen the overall process, let's take a look at our first PHP program. After reading the following example, you'll learn what separates it from a normal HTML file, how to upload it to your Web server, and what the page should look like viewed in your browser.



<!-- File: ch01ex01.php -->
<html>
<head><title>PHP By Example :: Chapter 1 :: Example 1</title></head>
<body bgcolor="white" text="black">
<h4>PHP By Example :: Chapter 1 :: Example 1</h4>
<?php
/* Display a text message */

echo "Hello, world! This is my first PHP program.";

?>

</body>
</html>



This file looks a lot like a regular HTML file. Notice that the file has HTML tags typical of those you would find in any HTML file. In fact, if you disregard everything between the tags, you might as well rename this file with an .html extension.

However, this file does contain PHP code, so it must be named with a .php extension. The PHP code lies between the PHP tags () as shown in Figure 1.1. The command between the PHP tags is echo (PHP’s word for “add the following text to the page”) followed by the text to display. The output, which will be shown soon, looks just as if the text after echo had been in an HTML file itself and no PHP code ever existed.

Figure 1.1. This diagram shows the different parts of a basic PHP program.

Before we look at the output, let’s upload this file to a Web server and run it. Follow the process outlined previously to write the program, save it as a PHP file (with a .php extension), and upload it to your Web server.

CAUTION

Don’t forget you shouldn’t be typing the previous code into a WYSIWYG program such as Microsoft Word or FrontPage. If you do, the code will probably show up in your Web browser just as it appeared previously. Instead, use a plain-text editor such as Notepad.

Once your program is uploaded to your Web server, type its address into your browser. You should get a page back that looks very similar to the screenshot in Figure 1.2.

Figure 1.2. This is what you should see in your browser when you go to the address of your new program.

Programming Syntax
When you accessed the program you just uploaded with your browser, the PHP program went through a process before it was returned to the browser. The process performed the PHP commands within the file; in this case, that was a single echo statement. Figure 1.3 shows what happens when a request is made for a PHP file.

Figure 1.3. Unlike HTML files, PHP files are routed through a special process that performs the PHP commands within the file before it is returned.

The PHP interpreter (or parser) is the program that performs the processing mentioned previously. It reads the PHP program file and executes the commands it understands. (If PHP happens to find a command it doesn’t understand, it stops parsing the file and sends an error message back to the browser.)

NOTE

Just as “interpreter” and “parser” are interchangeable terms to refer to the PHP interpreter, “interprets” and “parses” may be used interchangeably to refer to the process PHP performs when it processes a PHP file.

TIP

If you are an administrator for the Web server you’re using, you may be interested in knowing that the executable file you installed (a Windows EXE or DLL, or an Apache module or CGI binary on Unix-based systems) is the PHP interpreter.

Every time a request for a particular PHP file is made to a Web server, the PHP interpreter must process the file prior to returning anything to the browser. Because PHP must interpret a PHP program every time that program runs, it is known as a scripting language.

This is quite different from a compiled language, such as C or C++, which is only interpreted from a human-readable form once; a C program is simply translated into machine code (code that is processed directly by the computer’s processor).

TIP

In a very strict sense, parsing is the process of splitting commands into smaller segments, whereas interpreting is the process of actually comparing those segments to known commands in order to actually perform the correct command.

Since PHP has to interpret the commands included within a program, the commands must be given in such a way that PHP understands them. For example, if someone walked up to you and asked you in German for the time, you probably wouldn’t know what he was talking about (unless you know German or the person pointed to his wrist). Likewise, if I walked up to you and said, “Is time it what?” you probably wouldn’t know what I was talking about, even though I used English words.

PHP has similar limitations. A statement (the construction of commands and certain characters to make a sentence that PHP will understand) must be given using the correct commands. For example, the command show text has no meaning in PHP; you must instead use a command PHP recognizes, such as echo. Also, just as you must put your words in the correct order to talk to another person in English, you must format the statements you give PHP so that they follow the format PHP expects.

Syntax, then, is the process of putting together statements that PHP will be able to interpret and carry out. Examples of this are PHP’s opening and closing tags. PHP only parses code that is between PHP tags. Anything else in the file is returned as part of the HTML page, just as seen earlier in the first example.

Here’s another example. The following statement does not work, even though the command is part of PHP’s language:



echo "This won't work."

The statement won’t work because it doesn’t follow a basic syntax rule that requires all statements to be terminated with a semicolon. Some special statements must have the semicolon left out, but not many. (The ones that do will be pointed out as we come to them.) For now, just remember that statements should end with a semicolon. The following statement is a corrected version of the preceding line of code:



echo "This works!";


You may notice that leaving the semicolon off a single statement doesn’t cause PHP to display an error message. This is a feature of PHP to make it easier to insert a single echo statement. To see the error when you try to run the first echo statement, copy the statement to two separate lines so it looks like this:




echo "This won't work."
echo "This won't work."


The code will not run and PHP will return an error because there isn’t a semicolon separating the statements.

Good Style: Using Whitespace and Comments
You may be curious why PHP requires a semicolon at the end of every statement. The answer is that semicolons allow other aspects of PHP code to be more flexible. By signaling the end of a command with a semicolon instead of a new line, new lines can be added or taken out of the code without affecting the code itself. In fact, new lines are only a portion of what can be changed without changing what the interpreter sees when it processes the file.

Whitespace— all spaces, tabs, and line breaks—is left to be used at the discretion and preference of the programmer. This may seem trivial at first, but think about the difference the indentation in an outline makes; the indentation divides topics into subtopics and even subtopics under the subtopics into separate sections. Take a look at the following example, which contains no whitespace.




<?php
/* ch01ex02.php – an example of code with no whitespace */
echo"Hithere.";echo"Thisprogramhasnowhitespace";echo"It'salmostimpossibletoread.";
?>



NOTE

Although the line with all of the echo statements contains no whitespace, the program file as a whole does. The line breaks have been left to separate the PHP tags, the comment, and all the echo statements so at least the purpose of the program is easily decipherable.

You can see how hard it would be to read line after line of code like that. This code should be split into separate lines, with one for each echo statement.

By placing curiouscode on the same line, a new line, or a few blank lines apart, a programmer can group certain parts of his code together and separate other parts. This helps him keep up with how he divided a certain task into smaller, simpler tasks.

Spaces or tabs can be used in PHP to create the same kind of clarity and organization found in an outline as mentioned before. The following example demonstrates this principle:




<?php
/* ch01ex03.php – program to show usefulness of indenting */

if ($gotPHP) {
echo "Got PHP?";

if ($PHPMustache) {
echo " :)";
}
}

?>


Even though you haven’t really learned anything about the statements this program uses, you can easily see how everything follows a form similar to that of an outline. Also, the separation of



echo "Got PHP?";

and

if ($PHPMustache) {

by a blank line signifies that the statements serve two different purposes.

As you curiousread this book, keep whitespace in mind. Think about what makes code easy to understand or hard to understand. Read the statements in each example as it is presented and then go back and look at how it’s formatted. Good style in coding PHP is just as important as knowing the syntax; if your code is formatted into logical sets of statements, no one will have to break it down on his own as he reads it.

The other curiousvery useful element of style is commenting. Comments are descriptions, notes, and other information enclosed in a special character sequence that tells the parser to ignore whatever is within. Therefore, comments are treated the same way as whitespace; they are completely ignored by PHP.

Comments can be done either of two ways: single line or multiline. The one you pick depends on what you want to comment out. The following example is a file header using multiline comments that might be found in a PHP program file:




<?php
/*
All this is comments+-------------------------------------------------+ */

echo "This is Example_Program 1.0";

?>


As demonstrated in this example, to create a multiline comment, the programmer must enclose all of his comment text within /* and */.

TIP

Multiline comments can be used to comment out a block of code you don’t want PHP to evaluate. Simply place a /* before the code and a */ after the code and PHP will ignore it.

The other comments that are available are single-line comments. These comments are used to comment out everything from the comment marker, which is //, to the end of the line.

CAUTION

Although single-line comments may appear within a block of commented-out code, multiline comments are not allowed within multiline comments. Doing so would cause PHP to stop ignoring the commented text immediately after the first */ instead of after the second one, as the programmer intends.

You can find a few different examples of single line comments in the following code:



<?php
// File: example_file.php

echo "This is an example file!"; // Show some text

/* Don't plead insanity anymore

// Plead insanity
echo "This program did not consciously commit the crime, therefore it pleads insanity.";
*/

?>

The first comment found is a very short file header that tells the file’s name. Following it there is a comment describing the action taken by the first echo command. Comments such as this can help clarify things, but use them with discretion. The comment has no good use in this case because it doesn’t say anything we can’t pick up directly from the statement. Generally, use a comment if you (or someone else who might read your code) don’t immediately understand the code when you look at it.

Following that we have a multiline comment that is commenting out a block of code that we wanted to stop from being processed by PHP. PHP will therefore ignore the last echo statement. Notice that it’s perfectly legal to have a single-line comment within multiline comments.

Take note of how comments are used and make use of them in your own code. It’s much easier to read a comment and know what something does rather than having to read the code and figure it out step-by-step. With that in mind, use comments liberally to explain what your programs are doing.

How Embedded Programming Works
Before now, I’ve only mentioned that PHP code must be enclosed in the PHP tags. Using tags to separate PHP code and HTML code within the same file allows programming code to be mixed directly with information that is going to be sent to the browser just as it is. This makes PHP an embedded programming language because PHP code is embedded directly in HTML code.

This concept is relatively new: Before languages like PHP, programs had no real need to display data using a structured formatting language as complex as HTML. Information displayed on the screen was usually just letters, numbers, and spaces, without many colors, sizes, or other formatting markups.

Since PHP was made for Web programming, it is intended to be used with HTML, which significantly increases the amount of information that has to be sent back to the browser. Not only does PHP have to send back the information the user sees, but also the markup tags required to format the information correctly.

To make the mixing of information and markup tags simpler, PHP code is embedded directly in the HTML page where the information is desired. The example at the beginning of this chapter demonstrates this concept quite clearly; the program is mostly regular HTML code, but PHP is also used to insert some information.

Embedded programming will make your job as a programmer much easier; you can add programming where you need it and use regular HTML the rest of the time. However, be sure to enclose your PHP code in PHP tags or your code will not be parsed, but rather displayed on the HTML page.

The following program provides another example of embedded programming:



<?php
/* File: hello_world.php – displays "Hello, World!" */
?>

<html>
<head><title>Hello, World!</title></head>
<body bgcolor="white" text="black">

Hello,
<?php
// Send "World!" to the visitor's browser
echo "World!";
?>

</body>
</html>

When this file is accessed through a Web server, the PHP interpreter will process the file line by line from the top to bottom. Thus, the information before the opening PHP tag is sent to the browser, along with the result of the echo statement. The Web browser receives an HTML file that looks like this:



<html>
<head><title>Hello, World!</title></head>
<body bgcolor="white" text="black">

Hello, World!

</body>
</html>

The browser then displays the file just as it would any other HTML file.

TIP

As mentioned before, a single echo statement doesn’t have to be terminated with a semicolon to be understood by PHP. However, you may want to come back and add more statements later. For this reason, it’s a good idea to consistently include the semicolon, regardless of its necessity.

Filed under: Chapter 1 @ 8:29 pm

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress