BUY THIS BOOK
Add to Cart

Print Book $29.95


Add to Cart

Print+PDF $38.94

Add to Cart

PDF $23.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £20.95

What is this?

Looking to Reprint or License this content?


PHP in a Nutshell
PHP in a Nutshell

By Paul Hudson
Book Price: $29.95 USD
£20.95 GBP
PDF Price: $23.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction to PHP
PHP hasn't always been around, so what came before it? More importantly, why was PHP created in the first place? In this chapter, we'll look at the history behind PHP, where it has advantages over other programming languages, and where you can get help to further your PHP programming career.
Contrary to what some might have you believe, there was a lot of activity on the web development front before PHP was invented. Prior to its invention, code for server-side scripting was usually written in C or Perl, both of which are general programming languages that were adapted to use on the Internet.
The original PHP release was created by Rasmus Lerdorf in June 1995, to make various common web programming tasks easier and less repetitive. The name originally stood for "Personal Home Page," but has since become a recursive acronym, standing for "PHP: Hypertext Preprocessor." The goal of that release was to minimize the amount of code required to achieve results, which led to PHP being HTML-centric—that is, PHP code was embedded inside HTML.
The second PHP release, known as PHP/FI 2.0, was the first to achieve widespread popularity, and despite the parsing inconsistencies, it managed to attract a few converts.
The release of PHP 3 was largely driven by Zeev Suraski and Andi Gutmans, who rewrote PHP from the ground up and removed the parsing problems. PHP 3 also made it much easier for others to extend the language—particularly keen developers could now easily write their own modules for the language, adding functionality at the core level.
With PHP 3, the language had also gained limited object-oriented support, and this added extra fuel to the fire of PHP's growth. By the time PHP 3 was replaced in the middle of 2000, it was installed on over 2.5 million web site domains, as compared to 250,000 just 18 months before. Its successor, PHP 4, contained numerous major changes, including the switch to what is called the Zend Engine .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
PHP History
Contrary to what some might have you believe, there was a lot of activity on the web development front before PHP was invented. Prior to its invention, code for server-side scripting was usually written in C or Perl, both of which are general programming languages that were adapted to use on the Internet.
The original PHP release was created by Rasmus Lerdorf in June 1995, to make various common web programming tasks easier and less repetitive. The name originally stood for "Personal Home Page," but has since become a recursive acronym, standing for "PHP: Hypertext Preprocessor." The goal of that release was to minimize the amount of code required to achieve results, which led to PHP being HTML-centric—that is, PHP code was embedded inside HTML.
The second PHP release, known as PHP/FI 2.0, was the first to achieve widespread popularity, and despite the parsing inconsistencies, it managed to attract a few converts.
The release of PHP 3 was largely driven by Zeev Suraski and Andi Gutmans, who rewrote PHP from the ground up and removed the parsing problems. PHP 3 also made it much easier for others to extend the language—particularly keen developers could now easily write their own modules for the language, adding functionality at the core level.
With PHP 3, the language had also gained limited object-oriented support, and this added extra fuel to the fire of PHP's growth. By the time PHP 3 was replaced in the middle of 2000, it was installed on over 2.5 million web site domains, as compared to 250,000 just 18 months before. Its successor, PHP 4, contained numerous major changes, including the switch to what is called the Zend Engine .
Zend is a company founded by Zeev Suraski and Andi Gutmans to promote PHP in the corporate environment, and the engine they produced brought with it numerous advantages. By taking over the core of PHP, the Zend Engine introduced reference counting to ensure there were no memory leaks; introduced web server abstraction so that PHP ran on Apache 1.3.x, Apache 2, Microsoft's IIS, Zeus, AOLServer, and more; and also changed the way that PHP code was executed so that code was read once, converted to an internal format, then executed. This new execution paradigm allowed the use of external code caches, also known as PHP accelerators, that further boost performance.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Advantages of PHP
If you ask a group of PHP programmers why they use PHP, you will hear a range of answers—"it's fast," "it's easy to use," and more. This section briefly summarizes the main reasons for using PHP as opposed to a competing language.
When used to output text, PHP is embedded inside the text in code islands, in contrast to languages like Perl, where text is embedded inside the Perl script. The most common way to open and close PHP code blocks is by <?php and ?>. Here is an example of a simple page, shown in Perl first and then in PHP—don't worry about what the code means for now:
    #!/usr/bin/perl
    print <<"EOHTML"
    <html>
    <body>
    <p>Welcome, $Name</p>
    </body>
    </html>
    EOHTML
And now in PHP:
    <html>
    <body>
    <p>Welcome, <?php print $Name; ?></p>
    </body>
    </html>
The PHP version is only three lines shorter but easier to read, because it doesn't have the extra complexity around it. Some modules for Perl (particularly CGI.pm) help, but PHP continues to have a lead in terms of readability. If you wanted to, you could write your PHP script like the Perl script: switch to PHP mode and print everything out from there.
Apart from legibility, another advantage to having most of the page in HTML is that it makes it possible to use integrated development environments (IDEs), whereas products like Dreamweaver and FrontPage muddle up Perl's print statements.
Behind the scenes, PHP compiles your script down to a series of instructions (called opcodes), and these instructions are then executed one by one until the script terminates. This is different from conventional compiled languages such as C++ (but unlike Java), which compile the code into an executable run time and then run that executable whenever the code is encountered again. This constant recompilation may seem a waste of processor time, but it helps because you no longer need worry about recompiling your scripts when you make any changes. On the flip side, many scripts take longer to compile than they do to execute; fortunately, that is nullified by the use of PHP code caches.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Help
If you have tried debugging and failed, don't fret—there are still support options where you might find your solution.
The first place to check should always be the PHP documentation , available online from http://www.php.net/manual. The manual contains documentation on all PHP functions, as well as various usage examples, and also user comments. Very often it's the user comments that are most helpful, because people recount problems they've experienced in the past and how they got around them. The PHP manual is an excellent resource that should help you deepen your understanding of all aspects of the language.
There are several mailing lists that focus specifically on PHP, the most popular of which are hosted by the PHP web site itself. Visit http://www.php.net/mailing-lists.php to see a list of possibilities. You will most likely want the general mailing list, as it includes hundreds of questions and answers being sent each day.
Before you post:
  • Read the list for a while to get a flavor of how to ask questions and to make sure the list covers the right area for your question.
  • Make sure you have HTML mail disabled in your email client; only plain-text emails are accepted.
  • Never attach files to your email.
  • If you are having a problem, give a code example showing the problem in the simplest way. It helps people more if you say what you expected to get as output, what you did get, as well as other information such as what version of PHP you have, etc.
  • Do not post to the Internals list unless you really know what you are doing. This list is not for questions about how to install PHP, how to use a certain function, or why a script does not work—it is for the actual developers of PHP to discuss code changes and new releases of PHP. You do not need to post to this list asking whether you can use or redistribute PHP—the answer is "yes."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Certified
Zend and MySQL offer certification for PHP and MySQL respectively, which means that if you take a few tests and pass with sufficiently high grades you can add "Qualified PHP and MySQL developer" to your résumé. The exams themselves aren't too hard, and both have study guides to help you brush up on your skills, but you should have at least six months' experience using PHP/MySQL before you try them.
If you want to be sure of high grades, you could try taking a course in the topic of your choice—there are training partners around the world who can coach you toward Zend/MySQL certification, and this vastly increases your chances of success.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
PHP Resources
If you're looking to learn more about PHP and related topics like databases, security, and XML, try starting with something from these lists.
A Practical Guide to Curl by Kevin Hanegan (Charles River Media)
Quite a slow read, but you will learn a lot from it despite it being relatively short.
Advanced PHP Programming by George Schlossnagle (Sams)
Pitched at quite a high level, but it is the only book currently available that deals exclusively with making PHP work in highly scalable environments.
Beyond Fear by Bruce Schneier (Springer)
If you want a general introduction to the field of security, this is for you.
Disappearing Cryptography by Peter Wayner (Morgan Kaufmann)
Highly recommended as a general introduction to Crypto topics.
Database Systems by Thomas Connolly et al. (Addison-Wesley)
An excellent all-around reference to database theory and SQL.
Essential PHP Security by Chris Shiflett (O'Reilly)
Soon to be released, but my copy is already on pre-order.
HTML and XHTML by Chuck Musciano and Bill Kennedy (O'Reilly)
A long but worthwhile read that can take you quite far in the topic.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Installing PHP
Even if you intend to use a remote web server for your site, where PHP is already installed, it is still beneficial to be able to install PHP on your own machine so that you can test your pages more easily.
Installing PHP yourself opens up many possibilities: you get to choose exactly which extensions are available, which options are enabled, and the filesystem layout that you want. Of course, if you intend to upload your scripts to a different server at the end of the process, you should be careful to mimic the remote configuration on your local machine.
This chapter goes through a full install of PHP on Windows and Unix, installing extensions, and also configuring settings in the php.ini configuration file.
For installation on Windows, you need to download the Windows binary zip package from http://www.php.net/downloads.php. This contains the main PHP executables and DLLs, plus many extensions pre-compiled and ready to use.
When you extract the zip file, it should create a folder similar in name to php-5.0.4-Win32. I suggest you rename it to "php" and move it to the root of your hard drive, giving c:\php.
Browse to the new c:\php directory, and you'll see a number of files. Copy the php5ts.dll file into your c:\windows\system32 directory (note: this may be c:\winnt on some versions of Windows), then copy the php.ini-recommended file into your c:\windows directory, renaming it to php.ini. This is the file where you will be setting all your PHP configuration options.
Your basic Windows PHP installation is now complete. If you want to set up PHP to use a web server, read the appropriate section below. You may also want to enable some extensions—that, too, is covered in subsequent pages.
The first step to install Apache is to download the Windows installer from http://httpd.apache.org. This is packaged using the Microsoft Installer system (MSI), so you may be prompted to install the MSI software if you have an older release of Windows.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing on Windows
For installation on Windows, you need to download the Windows binary zip package from http://www.php.net/downloads.php. This contains the main PHP executables and DLLs, plus many extensions pre-compiled and ready to use.
When you extract the zip file, it should create a folder similar in name to php-5.0.4-Win32. I suggest you rename it to "php" and move it to the root of your hard drive, giving c:\php.
Browse to the new c:\php directory, and you'll see a number of files. Copy the php5ts.dll file into your c:\windows\system32 directory (note: this may be c:\winnt on some versions of Windows), then copy the php.ini-recommended file into your c:\windows directory, renaming it to php.ini. This is the file where you will be setting all your PHP configuration options.
Your basic Windows PHP installation is now complete. If you want to set up PHP to use a web server, read the appropriate section below. You may also want to enable some extensions—that, too, is covered in subsequent pages.
The first step to install Apache is to download the Windows installer from http://httpd.apache.org. This is packaged using the Microsoft Installer system (MSI), so you may be prompted to install the MSI software if you have an older release of Windows.
As Apache is packaged into a friendly installer, you need only answer a few basic questions and click "Next" until you have completed the installation. The default installation is placed into c:\program files\apache group\apache2. Inside there is the conf directory, which contains Apache's configuration files.
Inside the conf directory, you'll find the httpd.conf file. This contains most of the configuration settings for Apache, and you need to edit this in order to enable PHP. Any line that starts with a # symbol is a comment, and may provide further documentation to guide you in your edits. First, search for the string "LoadModule." There should be a collection of these LoadModule lines in there already, so scroll to the bottom and add this new one:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing on Unix
Installation on Unix can be done in one of two ways: you can use a package manager (such as YaST on SUSE Linux, Yum on Red Hat Linux, or URPMI on Mandriva Linux), or you can compile the programs from source code. If you are configuring a production web server, it is highly recommended that you use your package manager so that patching is kept easy. However, if you're installing PHP onto a local machine for test and programming purposes, you will probably want to compile it yourself to get you extra control.
One major advantage to installing from source code is that you can easily get the latest version of PHP. Many Linux distributions ship only older releases of PHP and Apache in order to ensure the system is stable enough for enterprise use. If you compile from source, you can choose to use an older, more mature release, or the very latest cutting-edge release.
Installing PHP and Apache through your distributions package manager is fast, easy, and usually also provides some extra extensions. For the purpose of this guide, Mandriva Linux 2005 was used, but the process is similar for other distributions.
To get started, open up the Mandriva Control Center and select Add Software. Type apache2 in the Search box, and click Search to list all packages that relate to Apache. In that list will be a package similar to apache2-2.0.53-9mdk. Select that, and you'll be prompted to include all the dependencies also (these are required). If you scroll down the list of search results, you should also see apache2-mod_php-2.0.53-4.3.10-7mdk, which is the package for PHP 4.3. Yes, that's quite out of date, but that's the result of installing through a package manager.
Once you have selected the Apache and PHP packages (and their dependencies), you might also want to run a search for "php" to look for any other software you want. For example, php-mysql-4.3.10-7mdk installs the PHP MySQL extension, and php-cli-4.3.10-7mdk installs the command-line interpreter (CLI) for PHP 4.3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Testing Your Configuration
To test your configuration, create the file info.php in your HTML directory. Enter this text in there, and save it:
    <?php
            phpinfo() 
;
    ?>
That calls the phpinfo() function, which outputs basic configuration information about your PHP installation. To access this script, go to http://localhost/info.php in your web browser. All being well, you should see a lot of information printed out about your PHP configuration. This is actually a handy script to keep around for debugging purposes, as it tells you exactly what extensions you have installed and what their configuration options are. Of course, it also tells any hackers about your system configuration , so don't advertise its existence!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
System Configuration
Now that you have PHP and your web server up and running, you will probably want to configure PHP to your liking. All of PHP's settings are available in its php.ini file, which, if you followed these installation instructions, is available either in /usr/local/lib/php (Unix) or c:\windows\php.ini (Windows). Open this in your text editor of choice (you will need to be root on Unix).
A list of popular options, what they do, and their default values (if you use php.ini-recommended as the default) is given in Table 2-2. Note that lines starting with a semicolon (;) are comments, and are ignored by PHP.
Table 2-2: Configuration options for PHP
Option
Meaning
Default
assert.active
Enables the assert() function
On
display_errors
Sets whether PHP should output error messages to the screen
Off
error_reporting
Decides what types of errors PHP should notify you of
E_ALL
expose_php
Allows PHP to identify itself to clients through the web server
On
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: The PHP Interpreter
This chapter discusses how PHP runs, both through the command line and through a web server, how PHP can be extended through built-in and third-party modules, and what can cause your scripts to terminate unexpectedly.
You can execute your scripts in one of two ways: through a web server where the output is sent to a web browser, or through the command-line interface (CLI) where the output is sent to standard output. Of the two, the former is more popular, but the latter is steadily growing in popularity.
The primary difference between outputting text to the command line and to a web browser is the format of new lines—through the CLI, you need to use \n for a new line, whereas for web browsers, you need to use the HTML line break, <br />. If you want to take a script designed for CLI and make it work through the Web, swap \n for <br />, and vice versa for converting web scripts to command line scripts.
If everything is configured properly, running scripts through your web server is as simple as putting the PHP script into your web server's public directory, then navigating to the appropriate URL with your browser. Running scripts through the command line is done using the CLI interpreter, which, if you are using Windows, is php.exe in the directory of your PHP installation. That is, if you have installed PHP into c:\php, the CLI program will be c:\php\php.exe. If you are using Unix, the availability of CLI PHP is down to how you installed PHP—make sure and issue the command make install-cli after the rest of the configure and make install process in order to install it.
The technical term for the command-line interpreter version of PHP is the CLI SAPI. SAPI stands for Server Application Programming Interface, and this standard interface allows PHP to work on multiple web servers, or, in the CLI SAPI's case, the command line.
If you are unsure whether PHP is set up correctly, run the following script:
    <?php
            phpinfo();
    ?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running PHP Scripts
You can execute your scripts in one of two ways: through a web server where the output is sent to a web browser, or through the command-line interface (CLI) where the output is sent to standard output. Of the two, the former is more popular, but the latter is steadily growing in popularity.
The primary difference between outputting text to the command line and to a web browser is the format of new lines—through the CLI, you need to use \n for a new line, whereas for web browsers, you need to use the HTML line break, <br />. If you want to take a script designed for CLI and make it work through the Web, swap \n for <br />, and vice versa for converting web scripts to command line scripts.
If everything is configured properly, running scripts through your web server is as simple as putting the PHP script into your web server's public directory, then navigating to the appropriate URL with your browser. Running scripts through the command line is done using the CLI interpreter, which, if you are using Windows, is php.exe in the directory of your PHP installation. That is, if you have installed PHP into c:\php, the CLI program will be c:\php\php.exe. If you are using Unix, the availability of CLI PHP is down to how you installed PHP—make sure and issue the command make install-cli after the rest of the configure and make install process in order to install it.
The technical term for the command-line interpreter version of PHP is the CLI SAPI. SAPI stands for Server Application Programming Interface, and this standard interface allows PHP to work on multiple web servers, or, in the CLI SAPI's case, the command line.
If you are unsure whether PHP is set up correctly, run the following script:
    <?php
            phpinfo();
    ?>
That calls the function phpinfo(), which outputs information on your PHP configuration—how it was configured, what server it is running on, what modules are available, and more. It is handy to keep around when you are developing, as it will answer most questions you have about configuration.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Extending PHP
The base of the PHP language is simple, having just enough to set and retrieve variables, work with loops, and check whether a statement is true or not. The real power behind PHP comes with its extensions —add-ons to the base language that give it more flexibility. PHP has hundreds of extensions, which can be broken down into five types: core, bundled, PECL, third party, and DIY.
  • Core extensions are extensions bundled with PHP itself and enabled by default. For all intents and purposes they are part of the base language, because, unless you explicitly disable them (few people do, and sometimes you cannot), they are available inside PHP. For example, the mechanism to handle reading and saving files in PHP is handled by an extension automatically compiled into PHP.
  • Bundled extensions are extensions included with PHP but not enabled by default. They are commonly used, which is why they are included, but they are not available unless you specifically enable them. For example, the mechanism to handle graphics creation and editing is handled by an extension that is bundled with PHP but not enabled by default in php.ini.
  • PECL (pronounced "pickle") stands for "PHP Extension Code Library" and was created as a place where rarely used or dormant extensions could be moved if they were no longer considered relevant to the core PHP distribution. PECL has grown since its founding, and is now the home of many interesting and experimental extensions that are not yet important enough for the mainstream.
  • Third-party extensions are written by programmers who wanted to solve a particular problem that was unsolvable without a new extension. A variety of third-party extensions are available, with the sole difference between a third-party extension and a PECL extension being that there are various rules about submitting code to PECL. Third-party extensions can sometimes be unstable.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
PEAR
The PHP Extension and Application Repository, or PEAR for short, contains re-usable code written by others that enables you to create powerful scripts using just a few simple commands.
PEAR contains two types of pre-written code: PECL code and PHP code . PECL code, as mentioned already, are full extensions written in C that interact with external libraries. Extensions reside in PECL when they are considered useful, but not popular or much used. However, most of PEAR is PHP code, which means you can use it on any PHP server without enabling any extensions or recompiling PHP.
The most famous package in PEAR is called PEAR::DB, and provides an object-oriented, database-independent framework for reading from and writing to your database. PEAR::DB is covered in depth in Chapter 14.
PHP comes with "go-pear," an easy way to configure PEAR for use on your computer. To use it, simply run go-pear from the command line and follow the on-screen instructions. Windows users will need to change to the directory where PHP is, e.g., c:\php.
The output of go-pear is shown in Figure 3-1.
Once you have PEAR installed on your system, you will see the pear command—this allows you to search for and download new PEAR modules for your PHP installation.
Figure 3-1: Running go-pear will set up PEAR on your computer
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Abnormal Script Termination
Most scripts will execute from start to finish, but sometimes they might end prematurely. There is a variety of reasons why this will happen:
  1. You've screwed up somewhere, and PHP cannot execute your code.
  2. PHP has screwed up somewhere due to a bug and cannot continue.
  3. Your script has taken too long to execute and gets killed by PHP.
  4. Your script has requested more memory than PHP can allocate and gets killed by PHP.
To be brutally honest, the first situation is unequivocally the most common. This will change a little as your skill with PHP improves, but the first situation is still the most common, even among the most veteran programmers.
Common errors include missing semicolons and parentheses, for example:
    <?php
            $i = 10
            $j = 5;
            if (($i + 2) - ($j + 5) == 10 {
                    print "Success!";
            }
    ?>
The first line is missing a semicolon, which will cause PHP to flag an error on the second line. Also, the second line is missing a parenthesis after "== 10", causing another error.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: The PHP Language
This chapter forms a complete introduction to the basics of PHP programming, covering variables, comments, conditional statements , loops, and more. If you have little experience with PHP, this is the best place to start. Otherwise, you may only need to dip into parts of this chapter to refresh your memory.
By default, PHP operates with PHP mode turned off, which means that PHP will consider the content to be plain text (i.e., not PHP code) unless PHP mode has been enabled. This method of parsing means that the PHP elements of a script are "code islands"—standalone chunks of code that can work independently of the HTML "sea" around them.
PHP scripts are generally saved with the file extension .php to signify their type. Whenever your web server is asked to send a file ending with .php, it first passes it to the PHP interpreter, which executes any PHP code in the script before returning a generated file to the end user. The basic unit of PHP code is called a statement, and ends with a semicolon to signify it is a complete statement. For clarity, one line of code usually contains just one statement, but you can have as many statements on one line as you want. These two examples do the same thing:
    <?php
            // option 1
            print "Hello, ";
            print "world!";

            // option 2
            print "Hello, "; print "world!";
    ?>
PHP purists like to point out that print is technically not a function and, technically, they are correct. This is why print doesn't require brackets around the data you pass to it. Other language constructs that masquerade as functions (and are herein referred to as such for the sake of sanity) include array, echo, include, require, return, and exit.
You can use parentheses with these constructs, and doing so is harmless:
    <?php
            print("Hello!");
    ?>
Although on the surface, print and echo appear the same, they are not. The print construct behaves more like a function than echo
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Basics of PHP
By default, PHP operates with PHP mode turned off, which means that PHP will consider the content to be plain text (i.e., not PHP code) unless PHP mode has been enabled. This method of parsing means that the PHP elements of a script are "code islands"—standalone chunks of code that can work independently of the HTML "sea" around them.
PHP scripts are generally saved with the file extension .php to signify their type. Whenever your web server is asked to send a file ending with .php, it first passes it to the PHP interpreter, which executes any PHP code in the script before returning a generated file to the end user. The basic unit of PHP code is called a statement, and ends with a semicolon to signify it is a complete statement. For clarity, one line of code usually contains just one statement, but you can have as many statements on one line as you want. These two examples do the same thing:
    <?php
            // option 1
            print "Hello, ";
            print "world!";

            // option 2
            print "Hello, "; print "world!";
    ?>
PHP purists like to point out that print is technically not a function and, technically, they are correct. This is why print doesn't require brackets around the data you pass to it. Other language constructs that masquerade as functions (and are herein referred to as such for the sake of sanity) include array, echo, include, require, return, and exit.
You can use parentheses with these constructs, and doing so is harmless:
    <?php
            print("Hello!");
    ?>
Although on the surface, print and echo appear the same, they are not. The print construct behaves more like a function than echo because it returns a value (1). However, echo is more useful because you can pass it several parameters, like this:
    <?php
            echo "This ", "is ", "a ", "test.";
    ?>
To do the same using print, you would need to use the concatenation operation (.) to join the strings together, rather than a comma. If you have several things to print out, as in that example, then
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
Variables in PHP—that is, things that store data—begin with $ followed by a letter or an underscore, then any combination of letters, numbers, and the underscore character. This means you may not start a variable with a number. One notable exception to the general naming scheme for variables are "variable variables," which are covered in the next chapter. A list of valid and invalid variable names is shown in Table 4-1.
Table 4-1: Valid and invalid variable names
$myvar
Correct
$Name
Correct
$_Age
Correct
$_ __AGE_ __
Correct
$91
Incorrect ; starts with a number
$1Name
Incorrect ; starts with a number
$Name91
Correct; numbers are fine at the end and after the first character
$_Name91
Correct
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Whitespace
Spaces, tabs, and blank lines in between statements have no effect on how the code is executed. To PHP, this next script is treated like any other, regardless of the fact that some statements are on the same line, and others are separated by several line breaks:
    <?php
            $name = "Paul"; print "Your name is $name\n";
            $name2 = $name; $age = 20;



            print "Your name is $name2, and your age is $age\n";


            print 'Goodbye, $name!\n';
    ?>
You should use whitespace to separate your code into clear blocks, so that its meaning can be understood by visually inspecting the layout.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Heredoc
If you have a long string, you ought to consider using heredoc syntax. Put simply, heredoc allows you to define your own string delimiter so that you can make it something other than a double or single quote. So, for example, we could use the string EOT (end of text) for our delimiter, meaning that we can use double quotes and single quotes freely within the body of the text—the string only ends when we type EOT.
It is a little more complicated than that in practice, but not much—the string delimiter needs to be by itself on a line, in the very first column. That is, you cannot add spacing or tabs around it. Here is a working example:
    <?php
    $mystring = <<<EOT
            This is some PHP text.
            It is completely free
            I can use "double quotes"
            and 'single quotes',
            plus $variables too, which will
            be properly converted to their values,
            you can even type EOT, as long as it
            is not alone on a line, like this:
    EOT;

    ?>
There are several things to note about heredoc and the example above:
  • You can use anything you like; EOT is just an example.
  • You need to use <<< before the delimiter to tell PHP you want to enter heredoc mode.
  • Variable substitution is enabled, which means you need to escape dollar symbols if you don't want PHP to replace variables with their values.
  • You can use your delimiter anywhere in the text, but not in the first column of a new line.
  • At the end of the string, type the delimiter with no whitespace around it, followed by a semicolon.
Without heredoc syntax, complicated string assignments can become very messy.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Brief Introduction to Variable Types
Variables in PHP can be of type integer (a whole number), floating-point (usually called "float"; a fractional number), string (a set of characters), array (a group of data), object (a complex mix of data and functionality), or a resource (any external information, such as an image). We will be looking at data types in more depth later on; for now, you only need to know what variables are and how they work.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Code Blocks
PHP makes extensive use of code blocks —chunks of PHP code that are separate from the rest of the script. As you read the following sections in this chapter, you will notice that PHP uses braces, { and }, to open and close code blocks.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Opening and Closing Code Islands
There are many ways to open a PHP code island (to enter PHP parsing mode), and you are welcome to choose which you prefer. The recommended manner is to use <?php to enter PHP mode, and ?> to leave PHP mode, but you can also use the short tags version, <? and ?>.
The short version has one big advantage and two big disadvantages: you can output information from your script by using a special short tags hack, <?=, like this:
    <?="Hello, world!" ?>
Here is the equivalent, written using the standard open and closing tags:
    <?php
            print "Hello, world!";
    ?>
As you can see, the short tags version is more compact, if a little harder to read. However, the first downside to the short version is that it clashes with XML (and therefore XHTML), which also uses <? to open code blocks. This means that if you try to use XML and short-tagged PHP together, you will encounter problems—this is the primary reason people recommend using the normal open and close tags. Short tags are always dangerous because they can be disabled in the PHP configuration file, php.ini, which means your scripts may not be portable.
Two other, lesser-used variants exist: <% %>, which opens and closes code blocks in the same way as Microsoft's ASP, and also <script language="php"></script>. These two often work better with visual editor programs such as Dreamweaver and FrontPage, but they are not recommended for general use because they need to be enabled to work.
You can switch into and out of PHP mode by using <?php and ?> whenever and as often as you want to.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Comments
While in PHP mode, you can mark certain parts of your code as a comment that should not be executed. There are three ways of doing this: //, /* */, and #. // and # mean "Ignore the rest of this line," whereas /* means "Ignore everything until you see */." Some complications exist with /* and */ that make them less desirable to use.
    <?php
            print "This is printed\n";
            // print "This is not printed\n";
            # print "This is not printed\n";
            print "This is printed\n";
            /* print "This is not printed\n";
            print "This is not printed\n"; */
    ?>
That chunk of code shows all three types of comments in action, but does not demonstrate the problem with the /* */ form of commenting. If you were to start a /* comment on line one, and end it on the line near the bottom where the other /* comment is started, you would find that the script would fail to work. The reason for this is that you cannot stack up, or "nest," /* */ comments, and attempting to do so will fail spectacularly.
It is generally best to stick to // for your commenting purposes, simply because it is easy to spot, easy to read, and easy to control.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditional Statements
PHP allows you to choose what action to take based on the result of a condition. This condition can be anything you choose, and you can combine conditions to make actions that are more complicated. Here is a working example:
    <?php
            $Age = 20;
            if ($Age < 18) {
                    print "You're young - enjoy it!\n";
            } else {
                    print "You're not under 18\n";
            }

            if ($Age >= 18 && $Age < 50) {
                    print "You're in the prime of your life\n";
            } else {
                    print "You're not in the prime of your life\n";
            }

            if ($Age >= 50) {
                    print "You can retire soon - hurrah!\n";
            } else {
                    print "You cannot retire soon :( ";
            }
    ?>
At the most basic level, PHP evaluates if statements left to right, meaning that it first checks whether $Age is greater or equal to 18, then checks whether $Age is less than 50. The double ampersand, &&, means that both statements must be true if the print "You're in the prime of your life\n" code is to be executed—if either one of the statements is not true for some reason, "You're not in the prime of your life" is printed out instead. The order in which conditions are checked varies when operator precedence matters; this is covered in the next chapter.
As well as &&, there is also || (the pipe symbol printed twice) which means OR. In this situation, the entire statement is evaluated as true if any of the conditions being checked is true.
There are several ways to compare two numbers. We have just looked at < (less than), <= (less than or equal to), and >= (greater than or equal to). We will be looking at the complete list later, but first I want to mention one important check: = =, or two equals signs put together. That means "is equal to." Therefore 1 == 1 is true, and 1 == 2 is false.
The code to be executed if the statement is true is in its own block (remember, a block starts with { and finishes with }), and the code to be executed otherwise is in an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Case Switching
Your if...elseif blocks can become unwieldy when you have a series of conditions that all test against the same variable, as here:
    <?php
            $Name = "Bob";
            if ($Name =  = "Jim") {
                    print "Your name is Jim\n";
            } elseif ($Name =  = "Linda") {
                    print "Your name is Linda\n";
            } elseif ($Name =  = "Bob") {
                    print "Your name is Bob\n";
            } elseif ($Name =  = "Sally") {
                    print "Your name is Sally\n";
            } else {
                    print "I don't know your name!\n";
            }
    ?>
PHP has a solution to this: switch/case. In a switch/case block, you specify what you are checking against, then give a list of possible values you want to handle. Using switch/case statements, we can rewrite the previous script like this:
    <?php
            $Name = 'Bob';
            switch($Name) {
            case "Jim":
                    print "Your name is Jim\n";
                    break;
            case "Linda":
                    print "Your name is Linda\n";
                    break;
            case "Bob":
                    print "Your name is Bob\n";
                    break;
            case "Sally":
                    print "Your name is Sally\n";
                    break;
            default:
                    print "I don't know your name!\n";
            }
    ?>
Switch/case statements are frequently used to check all sorts of data, and they take up much less room than equivalent if statements.
There are two important things to note in the PHP switch/case statement code. First, there is no word "case" before "default"—that is just how the language works. Second, each