32. Using PHP

An Introduction to PHP

Although ASP.NET is a popular standard when it comes to server-side application development, it’s certainly not the only one. Scripting technologies such as ColdFusion, Java Server Pages, and even the old stalwart Perl have all been used to perform similar work on the server to generate dynamic content. One of the most popular server-side scripting technologies, PHP, is so ubiquitous that Microsoft has decided to provide support for it in Expression Web.

PHP (a recursive acronym that stands for PHP: Hypertext Preprocessor) was designed as an alternative to Perl because it is better suited for generating dynamic web content. Whereas Perl requires all content to be generated by the Perl script, PHP’s model is much more like that of classic ASP code. PHP code is embedded directly into pages, but only content that is embedded inside special characters called PHP delimiters is interpreted as PHP code. All other content on the page is sent as is. This enables most of a page to be written as standard HTML, while only the portions of the page that need to be generated dynamically utilize the PHP code.

PHP Syntax

Whether you are actually coding in PHP or simply using other people’s PHP code in your pages, it is helpful to understand a bit about PHP syntax and how PHP programs are structured. Like ASP code, PHP is embedded directly into a page and requires special tags (called delimiters) to let PHP know what can be output directly and what needs to be handled by the PHP interpreter.

PHP code can be delimited in several ways. The first is through the use of the <script> tag:

<script language="php">
echo "Welcome to PHP! ";
</script>


Tip

image

The echo statement seen here is used to output information to the browser window when the page is browsed.


This method can cause problems with some HTML authoring tools because the content between the script tags is not recognizable as HTML content. Therefore, this method has been deprecated, although it can be found in older PHP pages.

The recommended syntax for PHP is to use <?php ?> instead. This syntax is referred to as full tags. For example:

<?php
echo "Welcome to PHP! ";
?>

In some cases, you might find PHP documents using a shorter version of this syntax referred to as short tags. For example:

<? echo "Welcome to PHP! "; ?>

You might even find them using ASP-style tags:

<% echo "Welcome to PHP! "; %>

Use of short tags is optional and can be disabled on a particular web host. Sticking with full tags is the best option for code portability.

Similar to JavaScript and other languages that share a C-like syntax, PHP code is case sensitive. Statement lines are followed with a semicolon, as you can see with the various echo statements listed previously.

PHP Comments

PHP comments make code easier to understand for people not familiar with the language and for other PHP developers reading your code. Three styles of comments are supported in PHP: C-style, C++/Java-style, and Perl-style. Here is an example of each style of comment:

/* C style */
// C++/Java style
# Perl style

The C-style comments can occupy more than one line, and everything between the opening and closing identifier is treated as part of the comment. With C++ and Perl-style comments, text up to the next newline is treated as a comment.

PHP Variables

PHP variables are declared with a preceding dollar sign ($) followed by the name. The name must consist of a leading letter (A–Z, a–z) or underscore, followed by any number of letters, underscores, or numbers. Variable names embedded in a string will be substituted by the value of the variable at runtime. Here is an example:

<?php
$first_name = 'John';
$last_name = 'Doe';
$age = 33;
echo "name: $last_name, $first_name age: $age ";
?>

In this example, three variables are declared: $first_name, $last_name, and $age. When the page runs, the variable values are output to the page and the following text is displayed:

name: Doe, John  age: 33

The type of a variable is not typically assigned by the programmer. Instead, the PHP interpreter sets the type based on the type of data that is first assigned to it.

Table 32.1 lists the variable types available in PHP.

Table 32.1. PHP Variable Types

image

PHP Program Flow

PHP supports language structures that are similar to those used by many other languages. It can use if/else/elseif, while, do-while, for, foreach, and more. Each of these structures can use either of two syntaxes. One will be more familiar to C++ or JavaScript programmers due to the use of braces to mark the beginning and end of a block. The alternative style will likely seem more familiar to Visual Basic programmers because it uses keywords to mark the end of a block instead of braces, as shown here:

image

The alternative style can also make the code more readable if the beginning and ending of the block are in different PHP script blocks:

image

Functions

Blocks of PHP code can be inserted into functions, allowing the code to be called from the main program flow or from another function. Functions should be used for code that needs to be called from multiple locations. They can also be used to pull out long sections of code from the main program flow, making it easier to read and follow. In this example, the code in the initialize function is not executed until it is called from the main program flow:


Note

image

It is outside the scope of this book to go into thorough detail about the use of PHP. If you are interested in learning more about PHP and how to write dynamic web content with it, read PHP 5 Unleashed from Sams Publishing (ISBN 067232511X).

You can also learn about PHP, follow tutorials, and browse documentation by visiting the PHP group’s site located at www.php.net.


image

Installing PHP

Installing PHP is straightforward enough, but until the release of IIS 7, getting it to work correctly with IIS was a fairly involved process. The Common Gateway Interface (CGI) for IIS can call PHP executable reliably and safely, but prior to IIS 7, this method was inefficient because it required the creation of a new Windows process for each request.

A more efficient method of calling PHP utilizes the Internet Server Application Program Interface (ISAPI) extension. With ISAPI, IIS calls into the PHP ISAPI DLL with its own thread. This is efficient because it bypasses the need to create a new process for each request, but a potential problem still exists with this method. The ISAPI interface demands that the code it calls be thread-safe, meaning multiple threads can safely access the same block of code in the same memory space. Although the core PHP is available in a thread-safe version, it doesn’t perform as well as the nonthread-safe (NTS) version. A fair number of popular PHP libraries aren’t thread-safe either, so if you intend to use them, you’d be forced into the standard CGI model.

The FastCGI protocol was created to address these problems. FastCGI provides a pool of processes to host CGI calls. When a call finishes, the process is returned to the pool instead of being terminated, so it can be reused. This greatly speeds up the process of calling CGI programs because it eliminates the process startup penalty. In addition, because CGI applications are running as their own process space with protected memory, thread safety issues don’t apply.


Tip

image

IIS 6 users can download the FastCGI extension for IIS 6 from www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1521.

IIS 7 users can download FastCGI from www.iis.net/downloads/default.aspx?tabid=34&i=1299&g=6.


To show its commitment to supporting the use of PHP on IIS, Microsoft has created FastCGI components for both IIS 6 and IIS 7. In this section, I show you how to get PHP up and running with IIS 7 using FastCGI. But first, I briefly cover how to install IIS itself.

Installing IIS 7 and FastCGI

To use FastCGI, you must have IIS 7 for Windows 7, Windows Vista SP1 or later, or Windows Server 2008. Because IIS is not part of the default installation for the operating system, you will have to add it yourself.

Installing IIS 7 and FastCGI in Vista and Windows 7

You install IIS 7 in Vista and Windows 7 through the Control Panel. Follow these steps to do it:

  1. Click Start, Control Panel.
  2. Select Classic View, double-click Programs and Features, and then select Turn Windows Features On or Off.
  3. Check the Internet Information Services box, as shown in Figure 32.1.

Figure 32.1. IIS is not installed in Windows Vista or Windows 7 by default.

image

To use FastCGI, you must now enable the CGI feature in IIS. Continuing in the Windows Features dialog box, do the following:

  1. Expand the Internet Information Services tree node.
  2. Expand World Wide Web Services.
  3. Expand Application Development Features.
  4. Check the CGI box, as shown in Figure 32.2.

    Figure 32.2. You must enable the CGI feature to use FastCGI.

    image

  5. Click OK when you are finished.

Installing IIS and FastCGI in Windows Server 2008

Installing IIS 7 in Windows Server 2008 is a somewhat different process. You must use the Server Manager to enable the Web Server role for the server. Follow these steps to enable this role:

  1. Click Start, Administrative Tools, Server Manager.
  2. Select Add Roles.
  3. On the Select Server Roles page, select the Web Server (IIS) check box.
  4. Click Next.
  5. Select any role services you want to install at the same time. For our purposes, be sure the CGI option is selected. This service is necessary for FastCGI to function.
  6. Click Next.
  7. Click Install.

Installing PHP

At the time of this writing, PHP version 5.3.3 is the current release of PHP, and it can be downloaded from www.php.net/downloads.php. This download page is shown in Figure 32.3. The NTS binaries are preferred for use with FastCGI and will perform better. Don’t download the installer version because it is unnecessary when using FastCGI. Simply download the Windows binaries Zip file.

Figure 32.3. Download the most recent version of PHP directly from www.php.net.

image

If you need to use an older version of PHP for a particular application, you can use FastCGI with versions 4.4 and higher. Versions 5.2.3 and higher, however, include optimizations that enable better performance when running on Windows with FastCGI.


Tip

image

Because of problems in version 5.2.4 that cause performance degradation, it’s recommended that you not use version 5.2.4. These problems have been fixed in version 5.2.5 and later.


When the download is complete, extract the contents of the Zip file to C:PHP. Then, in that folder, rename the file php.ini-development to php.ini when you are developing your site and the file php.ini-production to php.ini when you are ready to release.

Configuring the Microsoft Expression Development Server for PHP

After you’ve installed PHP, you can configure your preview settings in Expression Web so you can use the Microsoft Expression Development Server to test your PHP pages in cases where IIS is not available. To configure PHP for use with the Microsoft Expression Development Server, follow these steps:

  1. Select Tools, Application Options.
  2. In the PHP section of the General tab, click Browse and browse to the php-cgi.exe file you installed previously.
  3. Click OK.

Alternatively, you can use the Preview tab in the Site Settings dialog to specify preview options for a particular site.

Enabling PHP for IIS Using FastCGI

After you have IIS 7 and PHP installed, you need to tell IIS where it can find the PHP installation and which file extensions to use for it. This is done in the IIS Manager; this configuration process is the same for Vista SP1, Windows 7, and Windows Server 2008. Follow these steps to enable PHP using FastCGI:

  1. Click Start, type INETMGR in the search box, and press Enter.
  2. Select the server name in the pane on the left, and look for the Handler Mappings item in the Features View (see Figure 32.4). Double-click this item.

    Figure 32.4. The IIS Manager is used to configure PHP.

    image

  3. Click Add Module Mapping from the Action menu on the right. This opens the Edit Module Mapping dialog box, shown in Figure 32.5.

    Figure 32.5. You must tell IIS to route PHP files to the PHP CGI executable.

    image

  4. Type *.php in the Request Path.
  5. Select FastCgiModule from the Module drop-down list.
  6. Enter the path to your PHP CGI module under Executable. If you followed the instructions for installing PHP earlier, it will be C:phpphp-cgi.exe.
  7. Type PHP with FastCGI in the Name field.
  8. Click OK, and then click Yes when asked whether you want to create a FastCGI application for this executable.
  9. Close the IIS Manager.

Tip

image

If you want to use impersonation in your site, change the value of fcgi.impersonate in the php.ini file to 1.


Creating PHP Pages

With IIS configured and PHP enabled, you can now create a PHP page in Expression Web to test the functionality of the FastCGI application. Follow these steps to create a sample PHP site for testing:

  1. In Expression Web, select Site, New Site.
  2. Under the General tab, select Empty Site.
  3. Enter a name for the site, such as PHPTestSite. Click OK.
  4. Now, create a PHP page. Select File, New, Page to open the New dialog box.
  5. Select PHP as the file type in the General section as shown in Figure 32.6; then click OK.

    Figure 32.6. You can create PHP pages as easily as any other type of page.

    image

  6. Select Code View. In the Body section, enter the following PHP code:

    <?php
    echo "Hello World! ";
    ?>

  7. Save the page as helloworld.php. Figure 32.7 shows the page in Code View.

Figure 32.7. Enter a simple PHP block in the body section of the sample page.

image

Previewing the Page

Even if you have IIS7 installed and configured to use PHP, Expression Web will not use it by default when you preview in the browser. Instead, it will use the Microsoft Expression Development Server. You need to either configure the site you just created to use IIS for the preview or tell the Microsoft Expression Development Server where to find your PHP CGI executables. Fortunately, both of these configuration options are done in the same place in the Site Settings dialog. Follow these steps to configure the preview of PHP pages using the Microsoft Expression Development Server:

  1. Select Site, Site Settings to open the dialog.
  2. Click the Preview tab.
  3. Make sure the Preview Using Website URL button and the Use Microsoft Expression Development Server check box are selected.
  4. If you have not configured the PHP CGI executable path in the Application Settings dialog, or if you want to use a different version for this site, select the Use a PHP Executable for Only this Web Site option.
  5. If necessary, enter the path to your PHP CGI executable or browse to it. It will be C:phpphp-info.exe if it was installed using the instructions in the previous section.
  6. Click the Preview in Browser button. The page should be parsed by the PHP program, as shown in Figure 32.8.

Figure 32.8. View the page in the browser. If all went well, you’ll see the PHP-generated text.

image


Tip

image

You can configure the location of the PHP executable in the Application Settings dialog as well. If you configure it in the Application Settings dialog, it will affect all sites you create with Expression Web.


If you’d rather configure the preview feature to use IIS running locally instead, follow these steps:

  1. Configure a virtual directory in the IIS Manager that points to your development site path. Right-click Default Web Site, and select Add Virtual Directory.
  2. In the Add Virtual Directory dialog, type PHPTestSite as the alias; then enter or browse to the path where your site project files are located.

    Tip

    image

    If the PHP.ini file is not correctly configured for displaying PHP, Expression Web displays a dialog asking whether you want the file to be configured. Make sure you answer Yes to this so that Expression Web can fix the PHP.ini file.


  3. Right-click the new PHPTestSite item in the tree, and select Edit Permissions. This opens the properties window for the folder. Click the Security tab.
  4. Click the Edit button, and then click Add in the Permissions dialog.
  5. In the Select Users or Groups dialog, type IIS_IUSRS. Then click OK.
  6. Click OK again.
  7. In Expression Web, select Site, Site Settings to open the Settings dialog.
  8. Click the Preview tab.
  9. Select the Preview Using Custom URL for the Web Site radio button.
  10. Type http://localhost/PHPTestSite/ for the custom URL.
  11. Click OK.
  12. Click the Preview in Browser button to view the page in the browser.

PHP in Design View

PHP script blocks cannot be processed in Design View in the same way they are in the browser. However, you can see where PHP code blocks are using the formatting marks available for script blocks.

Formatting marks are not enabled by default. Do the following to show them:

  1. Select Design View.
  2. Select View, Formatting Marks from the menu.
  3. Make sure the Show item is selected.
  4. Select View, Formatting Marks again.
  5. Be sure Script Blocks is selected.
  6. PHP blocks appear with the script block icon, as shown in Figure 32.9.

Figure 32.9. Script formatting marks can be used in Design View to identify PHP code blocks on a page.

image

As with other types of scripts, you can view the code within the block by double-clicking the script block icon (see Figure 32.10).

Figure 32.10. Double-clicking a script block icon lets you view or edit PHP code in Design View.

image

PHP in Code View

Although Design View is somewhat limited in its handling of PHP, Code View offers some additional features. You can customize the display of PHP code in the editor and use IntelliSense to help you write PHP code.

PHP Syntax Highlighting

Syntax highlighting makes editing in Code View easier because it makes code blocks and the elements contained in them stand out from the surrounding code. With syntax highlighting, you can customize each PHP item with the color of your choice. You can customize foreground and background colors and even set font styles such as bold, italic, or underline specifically for each PHP item.

Expression Web is configured with default values for each of the formatting options. (You can change them if you don’t like the defaults.) Follow these steps to configure syntax highlighting for PHP elements:

  1. Switch to Code View.
  2. Select Tools, Page Editor Options from the menu.
  3. Select the Color Coding tab, as shown in Figure 32.11.

    Figure 32.11. PHP syntax highlighting enables you to customize colors and font styles for various PHP code elements.

    image

  4. Make sure the Code View Settings radio button is selected.
  5. Scroll down the list of display items until you see the PHP items.
  6. Select each PHP item in turn and select the foreground color, background color, and any custom font styles you like. Use the Automatic option for the foreground and background colors so those items are determined automatically by the editor.

Tip

image

You can also show this tooltip by positioning the cursor at any point in a parameter list and pressing Ctrl+Shift+Space.


Using IntelliSense with PHP

IntelliSense is a feature of Microsoft’s code editors that helps you speed up coding by giving you options to select code from a list as you type. IntelliSense also provides you with tooltips to fill in parameters for function calls. IntelliSense works inside a PHP script block regardless of the type of PHP tags you use to identify the block (<?php ?>, <? ?>, or <script language="php"> </script>).

Press Ctrl+L inside a PHP script block to bring up a list of available PHP functions, as shown in Figure 32.12. You can quickly locate a function from the long list by typing one or more letters of the function name right before or after you activate the list. Alternatively, simply scroll down the list using the mouse or the arrow keys and choose a function manually.

Figure 32.12. IntelliSense for PHP lets you easily discover PHP techniques and makes entering PHP code faster.

image

When the function you want to add is highlighted in the list, you can enter it in the editor simply by pressing Tab.

If the selected code is a function, IntelliSense shows you a tooltip with the parameters required by the function when you enter the left parenthesis, as shown in Figure 32.13. As you enter parameters and type the comma separating them, the next parameter to enter appears bolded in the tooltip.

Figure 32.13. Tooltips guide you through the process of entering parameters for function calls.

image

Global variables in PHP are provided by the environment and include several collections, such as session variables, form elements, cookies, and environment variables. IntelliSense can simplify the addition of global variables in your code as well. In PHP, global variables are preceded by a $_. If you type those characters into the editor inside a PHP code block, IntelliSense presents you with a list of global variables (see Figure 32.14). As with the function list, you can type a partial name and then press Tab to complete the entry.

Figure 32.14. You can choose from a list of global variables when you enter the $_ prefix.

image

Setting PHP-Specific IntelliSense Options

If you prefer not to use IntelliSense, or want only some of the IntelliSense features, you can enable or disable them in the Page Editor Options dialog box.

The following are some PHP IntelliSense options you can enable or disable:

PHP Global Variable Completion—Controls whether to display a list of global variables when you type $_.

PHP Parameter Information—Choose whether to display information about parameters when entering a function call.

PHP Function Categories—You can reduce the size of the IntelliSense function list by deselecting categories of functions you might never need.

Follow these steps to set IntelliSense options:

  1. Select Tools, Page Editor Options.
  2. Select the IntelliSense tab.
  3. In the Auto Popup section, select or deselect the IntelliSense items as you see fit, as shown in Figure 32.15.

    Figure 32.15. Set PHP IntelliSense options in the Page Editor Options dialog box.

    image

  4. Click OK when you are finished.

PHP Script Options

To further simplify and assist you with your PHP coding, Expression Web lets you insert common PHP script blocks into your code from the Insert menu (see Figure 32.16). This can be helpful if you aren’t familiar with the exact syntax of a particular PHP statement or global variable.

Figure 32.16. Add segments of PHP script into a page from the Insert menu.

image

The following section describes the PHP script items you can insert using this method.

Form Variable

The Form variable holds information passed to the page from form elements on the requesting page. Form variables are passed using the HTTP POST method; therefore, the global variable name is $_POST.


Tip

image

It should be mentioned that Expression Web isn’t very smart when it comes to inserting script text. If your cursor is already positioned inside a PHP script block, it will still add the PHP script tags around the inserted script. You must remember to delete these extra tags manually.


The following code is inserted into a page when you select this option:

<?php $_POST[]; ?>

To reference a specific form variable, you must use the name of the form element as a key, as shown in this example:

<?php $_POST["LAST_NAME"]; ?>

URL Variable

The URL Variable item inserts a script to pull items passed to the page via the HTTP GET method as parameters passed in the calling URL. The following script is inserted:

<?php $_GET[]; ?>

As with other global variables, you must use the name of a URL variable as a key to reference a specific variable value.

Session Variable

As a user visits pages on your site, the browser passes a session value that the web server uses to identify the specific user session. Session variables can be used to maintain user state information on the server between page requests. Use the Session Variable script item to insert the following script:

<?php $_SESSION[]; ?>

Instead of having session values determined by the requesting page, you must store values in the session variable yourself. Store it using a key you create:

<?php $_SESSION["role"] = "administrator"; ?>

Then, on a subsequent page request, retrieve it using the same key:

<?php
if ($_SESSION["role"] == "administrator") {
    echo "administrator is logged in. ";
}
?>

Session variables last only as long as the user’s session is active.

Cookie Variable

Cookie variables are similar to session variables in that they store information that persists from page to page. Cookies, however, are sent to the browser and stored on the client computer instead of the server. This item inserts the following script:

<?php $_COOKIE[]; ?>

include

PHP code that will be used in many pages can be separated out and put in its own file, which then can be included in a PHP page using the include statement.

When you select the Include item from the Insert menu, you are prompted to select a PHP file to include, as shown in Figure 32.17. This item inserts the following script, with the chosen page as a parameter to the include statement:

<?php include('common.php'), ?>

Figure 32.17. Include files let you keep shared PHP code in one place.

image

Include Once

The Include Once script is similar to the Include script, except that the inserted script will be included in a page only once to avoid variable and function redefinitions, value reassignments, and other potential problems. When you select this item, the following script is inserted:

<?php include_once('common.php'), ?>

As with Include, you select the file to add to the statement.

require

The PHP require statement is similar to the include statement, except in the way in which errors are handled when it is used. If the file referenced by an include statement doesn’t exist, an error message will be displayed but script execution will continue. When the require statement is used, PHP script execution will stop if there is an error with the included file.

The following script is inserted when this statement is used:

<?php require('common.php'), ?>

require_once

The require_once statement is analogous to the include_once statement, but with the same difference in error handling as between include and require. This script segment is inserted:

<?php require_once('common.php'), ?>

Code Block

The Code Block item inserts a simple empty PHP script block tag, as follows:

<?php ?>

This can be useful as shorthand for entering the tag quickly, particularly if you memorize the keyboard shortcut used to enter it: Alt+I, H, B.

echo

As mentioned at the beginning of this chapter, the echo statement is a common way to have the PHP script insert dynamic text into a page. This item inserts the following script:

<?php echo ?>

The cursor is positioned after the echo statement to facilitate adding the string or variable values to be echoed.

Comment

The Comment item inserts a PHP C-style comment into the program flow, with the cursor positioned to type the comment text:

/* */

Note that this script doesn’t include the surrounding script block tags. PHP assumes that the comment will be inserted into an existing block.

if

The if statement is a commonly used conditional execution statement. This item inserts the following script:

<?php if ?>

An expression to evaluate is then inserted enclosed in parentheses. The following is an example:

<?php if ($user_role == "administrator") ?>

An if statement typically is followed by a block of code to be executed, contained in braces. The code between the braces is executed only if the expression evaluated by the if statement is true. Note that this script does not add the braces; they must be added by hand.

The if statement can also use the alternative style described earlier in this chapter, in which case you must manually enter a colon after the expression to be evaluated, as well as a corresponding endif; statement. This can be useful when you want to embed HTML code in the if block, as the example in the “PHP Program Flow” section of this chapter shows.

else

The else statement can be used to follow up an if statement as an alternative block of code to execute if the expression evaluated by the if statement is false. This item inserts the following script:

<?php else ?>

The else statement should be followed up with a block of code in curly braces. You can also use the alternative syntax, although you need to remember to add a colon after the else statement. An example shown earlier in the chapter in the use of the if..else..endif syntax is repeated here to demonstrate this:

image

Displaying PHP Information

Although you might know your server intimately, your site’s PHP pages could end up deployed to some other server that might not be configured quite the same way as the server on which you developed it. This can often be frustrating to debug, as you end up putting in debugging echo statements that loop over global variables and other such techniques to try to glean some information about the server.

The need to display server information for development and debugging purposes is so common that the phpinfo() function was created just to facilitate the display of this type of information. If you are deploying a PHP application to many server configurations, it is in your best interest to include a test page somewhere that calls phpinfo.

To use phpinfo, simply include it in a PHP page in a PHP script block:

<?php
phpinfo();
?>

Various bits of server configuration information are displayed in the resulting page, as shown in Figure 32.18.

Figure 32.18. The phpinfo() function displays useful information about your PHP and server environment.

image

If you call phpinfo with no parameters, as previously shown, you will get all the information that can be displayed—which can be a lot. Give it a try and scroll down the list just to see what is available. If you want to restrict the output to only certain portions of the information, pass in a value as a parameter to restrict the output. The values that can be passed are defined as constants for convenience and appear in Table 32.2.

Table 32.2. Options for phpinfo

image

Because the arguments for phpinfo are bitwise values, they can be combined using the or operator (|) to display more than one item at a time. For example, you can display INFO_ENVIRONMENT and INFO_VARIABLES information by calling phpinfo as follows:

<?php
phpinfo(INFO_ENVIRONMENT | INFO_VARIABLES);
?>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.78.136