PHP Tutorials

Why PHP?

PHP is an excellent choice for Web programming. It has many advantages over other languages, including other Web-oriented languages. To get a very general understanding of how the common Web programming languages compare, let’s compare them.

ASP is Microsoft’s Web programming environment. (It’s not a language itself because it allows the programmer to choose from a few actual languages, such as VBScript or JScript.) ASP is simple, but too simple for programs that use complex logic or algorithms.

TIP

An algorithm is a formula-like method for accomplishing a particular task. Here’s a simple example: Some bank accounts use the last four digits of a person’s Social Security number as his PIN number. An algorithm could be formed to create this PIN number based on the already-known Social Security number.

Besides ASP’s over-simplicity, many companies find it hard to budget for the expense of Microsoft licenses. Without even considering hardware costs, a Microsoft server could cost thousands of dollars in licensing, whereas a comparable Unix-based operating system running PHP could be free.

TIP

Many people new to open source software find the idea of free software hard to believe. However, once you’ve spent some time looking into it, you realize how much open source software makes sense. In addition to open source software being free, it is generally updated and patched more frequently, and it’s usually easy to find help from other users and even from the developers of the software.

You may be interested in visiting http://www.OpenSource.org for more information.

Another language well known for its use on the Web is Sun Microsystems’ Java. Java is praised for being platform-independent (a program written in Java can be run on virtually any computer without having to make any modifications to the program).

NOTE

The term platform means the same thing as operating system. Some examples include Windows, Solaris, Linux, FreeBSD, and NetWare.

Although Java does have its advantages, it has serious downsides in development time, development cost, and execution speed. Java development is time-consuming because projects in Java must follow strict rules (imposed by Java) that require extensive planning. In addition to high development time, the cost is also high because Java developers are expensive to hire. The cost is therefore potentially much higher than it would be if the project were done in another language. Even after the project is built, a program written in Java takes longer to run than one written in one of the other languages to which we’re comparing.

Overall, when compared to Java, PHP comes out with flying colors. It is not unheard of for a Java project to take two or three times the time to develop compared to a similar project in PHP. On top of that, the final program runs on a wide array of platforms (like Java), except the PHP program runs faster.

Another language commonly used for writing Web programs is Perl (practical extraction and report language). Perl, like PHP, is an open-source project developed to run on many platforms. In fact, Perl has been around longer than PHP. Before PHP, Perl was generally accepted as the best Web programming language. However, during the past few years, PHP has earned a reputation for being better than Perl for Web programming because PHP provides a vast number of features as part of PHP itself, whereas you would have to download separate modules to get the same functionality in Perl. This leads to problems when programs are transferred from one system to another because the modules have to be downloaded from Perl’s exhaustive (and confusing) module archive known as CPAN.

The last language to compare PHP to is C. C has been around for a long time; it has been used in a variety of computers, from mainframes to consumer PCs. The problems creating a Web program in C are obvious if you know C. To develop a Web program in C, you have to develop all of the basic functionality of Web programming (such as collecting the data from HTML forms) before you can even begin to think about the actual task at hand. Since PHP provides for all the common (and many uncommon) Web programming tasks, writing such a program in PHP allows the programmer to get straight to the point.

You could write volumes on PHP’s advantages over other programming languages when it comes to Web programming. There are many, many articles on the Internet comparing PHP to Java, Perl, ASP, and others. Once you’ve earned some experience programming in PHP, you might find yourself trying to convince your client or employer to allow you to use it instead of another language. If that problem arises, you should find plenty of helpful information by doing a Web search.

PHP has an unlimited number of uses. The original version was used solely to track who was viewing the creator’s résumé. Over time, however, that simple tracking program evolved into a language of its own.

TIP

If you’re interested in knowing how PHP came to be what it is today, I recommend visiting http://php.net/manual/en/intro-history.php, where you will find a brief history of the language.

PHP’s primary use certainly isn’t to track résumés anymore; it has grown to be able to do that and just about anything else. To giveyou a better idea of what PHP can do, here are some of its common uses:

Feedback forms

Shopping carts and other types of e-commerce systems

User registration, access control, and management for online subscription services

Guest books

Discussion and message boards

Filed under: Chapter 1 @ 8:01 am

If You’re New to Programming

If you’ve never written a computer program before, the whole idea may be quite intimidating. Most programmers will probably tell you (if they aren’t embarrassed to admit it) that they were intimidated when they began. However, the programming process isn’t all that difficult and, contrary to popular belief, you don’t have to have an extremely high IQ to be good at it.

When you write a program, your main goal is to translate your idea into a language that the computer can understand. For example, if you were teaching a person how to cook hamburgers, you would first describe the process of forming the ground beef into patties. Then, you would tell the person how to put the burgers on the grill, how long to leave them there, and finally how to remove them.

Of course, just because you can describe the process of making hamburgers doesn’t mean PHP is going to be cooking anything for you anytime soon. The point is, if you can describe a process like I just described making hamburgers, you can write a program.

Writing a PHP program is simply the process of describing to PHP how to do something. By the time you’ve finished reading this book, you will understand all the concepts behind writing a PHP program. Those concepts are like the words and sentences used to describe hamburgers. The more you read this book, the more “words” you will understand, and the better you will be able to “describe” your task to PHP. Thus, you will learn to write PHP programs to suit whatever need or idea you have, and soon it won’t be any more intimidating than telling someone how to cook hamburgers.

Some programming problems might be very complex when examined as a whole. For example, creating a shopping cart is definitely not a simple task. However, a shopping cart can be broken into a few smaller tasks. Those tasks might include adding and removing items, which are both tasks that can break into even smaller tasks. You will find that any task, no matter how complex, can be broken into smaller ones until each task is simple enough that breaking it down further is unnecessary. This process is explained in more detail when you begin creating programs with more complexity (especially in Chapter 17, “Putting It All Together,” when we walk through the whole process of creating a complex program step-by-step).

Filed under: Chapter 1 @ 8:20 pm

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
Next Page »

Powered by WordPress