PHP

GETTING STARTED WITH PHP

1

INTRODUCTION TO PHP
HP is a popular scripting language used to create powerful and dynamic Web sites. PHP is currently in use on over five million Web sites around the world. PHP is open source software, which means it is available

P

free of charge. There are also no costs or restrictions related to distributing the PHP scripts you create, whether the scripts are for development or commercial use.

Versions PHP is constantly evolving and a new version of the language is released every few years. Each new version of PHP offers more features than previous versions but is still compatible with the previous versions. This means that scripts you write using the current version of PHP will be compatible with future versions. PHP 4 is the current version of PHP and is used in the examples throughout this book. HTML HyperText Markup Language (HTML) is the markup language used to create Web pages. PHP can be used to dynamically generate the HTML code for a Web page. PHP code can also be embedded into the HTML code for a Web page. PHP is embedded into HTML code with the use of special tags, called delimiters. Using the delimiters, you can add as many sections of PHP code to an HTML document as you need. Embedding PHP code in HTML code makes it possible to enhance existing Web pages on a Web site. Dynamic Web Sites Dynamic Web sites contain Web pages that display constantly changing content. Using PHP, you can determine the content a Web page displays, depending on many different factors. For example, you can have a page automatically present different content to users depending on the current date or the user's location. Dynamic Web pages are more useful to each individual user than static Web pages.

Interactive Web Sites Interactive Web sites contain Web pages that exchange information between the Web site and the user. Using PHP allows Web developers to easily create Web pages that process information from a user and then generate content depending on the information submitted by the user. Interactive Web sites allow Web developers to tailor the content of Web pages to better appeal to the user. Database Manipulation One of the most important features of PHP is the ability to work with a number of different databases, including MySQL, Oracle and Sybase. PHP pages can be used to access a database and then make the information stored in the database available to users who visit the Web site. Using databases to store information and PHP code to access the information is an efficient method of displaying up-to-date information in a Web site. PHP can also allow users to manipulate the data in a database. For example, a PHP page can be used to add, delete or edit records in a database depending on a user's request.

Server-Side Processing A Web server processes all the PHP code in a Web page and translates the code into simple HTML code. This means that Web developers do not have to take into consideration the types of Web browsers used by clients. Any browser that can view Web pages can view pages containing PHP code processed by a Web server. Object-Oriented Although PHP is not a true object-oriented language, PHP does support object-oriented programming concepts that allow Web developers to write code in an object-oriented fashion. Object-oriented programming is a type of programming that treats packages of code as distinct modules, or objects. Using objects can make a large Web application easier to manage, especially if there are multiple developers working on the same application. Increased Security Because PHP code is processed by a Web server, a user cannot access the code used to create a PHP page. This makes it safer to work with sensitive data, such as login names and passwords. If a user views the source code of a Web page created using PHP within a Web browser, all the user will see is the HTML code that was generated by the Web server to create the page, not the PHP code itself.

Cross Platform PHP can be installed on computers using different Windows and Unix operating systems. While some specialized functions work only on specific platforms, the vast majority of PHP code will work equally as well on either platform. Many PHP developers write their code on Windows-based computers and then use the code on Web servers that run a Unix operating system. Web Servers You do not require a dedicated Web server to publish the Web pages you create using PHP. You can simply install Web server software on your own computer. A popular example of Web server software that includes support for PHP is Apache. Microsoft's Web server products, Internet Information Server (IIS) and Personal Web Server (PWS), can also be used to store and serve PHP pages. If you cannot install Web server software on your computer, you can transfer your PHP pages to a Web hosting service on the Internet. Development Tools You do not require any special development tools to create and view PHP pages. All you need is a text editor and a Web browser. Although there are some programming tools available that make creating PHP pages easier, these tools are typically used only by Webmasters who generate large amounts of PHP code on a continuous basis.

2

3

PHP

GETTING STARTED WITH PHP

1

INSTALL APACHE WEB SERVER ON WINDOWS
efore you can publish PHP pages, you must install a Web server that can interpret and process PHP code. Apache Web server is an extremely reliable and robust Web server that can be used for serving a small intranet or a large commercial Web site. Since Apache is the most popular Web server used on the Internet, PHP has been developed to work well with Apache to make PHP pages available on the Web.

B

Apache Web server is relatively easy to install and maintain. Although the Windows version of Apache was designed primarily for use on computers running the Windows NT or Windows 2000 operating system, it can also be used on computers using Windows 95, 98, Me or XP. On the Windows platform, Apache is installed using a standard Windows installation program. The Apache files must be installed in a folder on the computer. The default installation location is C:\Program Files\Apache Group\Apache. You can specify another destination folder, but it is recommended that you accept the default folder. Apache includes several parts, such as documentation, modules that increase Web server efficiency and the source code of the application program itself. You may not need to install all the available components in order to use Apache. The setup program allows you to choose the type of installation you want to perform.

A recent release of Apache Web server is included on the CD-ROM disc that accompanies this book, but you should make sure you install the latest release of the server. The latest version of Apache is available at the www.apache.org Web site. Before you can install Apache, you must install the TCP/IP protocol on your computer. For information about installing network protocols, refer to your operating system documentation.

When installing Apache Web server, you can choose one of three installation options. The Typical option installs the most commonly used files and is the recommended option. The Compact option installs only the files required to run Apache. This option is useful when installing Apache on a computer with limited hard drive space available. The Custom option allows advanced Web site developers to choose the Apache Web server files they want to install. If you are installing a more recent version of Apache Web server than the one included on the CD-ROM disc that accompanies this book, you should carefully read the Web server documentation, especially the areas that relate to PHP. Later versions of Apache may work differently with PHP than the version used in this book.

Unlike commercial programs, which often include a support department to handle any problems with the application, there is no official support included with the Apache program, so you must troubleshoot any problems yourself. There are, however, many Web sites, user groups, newsgroups and books available that can be a source of information for Apache users. The Apache FAQ located at http://httpd.apache.org/docs/misc/FAQ.html is a good starting point when looking for help information.

INSTALL APACHE WEB SERVER ON WINDOWS

C:\Program Files\Apache Group\Apache

⁄ Double-click the icon for the Apache Web server installation program to start installing the program.
I A welcome dialog box
appears.

I This area displays information about the Apache Web server program.

¤ Click Next to continue.

I This area displays the license agreement you must read and accept before continuing.

‹ Click Yes to accept the
agreement and continue.

I An information dialog box may appear, providing information about this version of the Web server software. Click Next to continue.

I This area displays the folder where Apache Web server files will be installed. I You can click Browse to specify a different folder in which to install the files.

› Click Next to continue.

ˇ Click the type of
installation you want to perform. Note: If you choose Custom, the following steps will be different for your installation.

Á Click Next to continue.

CONTINUED

4

5

PHP

GETTING STARTED WITH PHP

1

INSTALL APACHE WEB SERVER ON WINDOWS
hen installing Apache Web server on a computer running a Windows operating system, a folder containing shortcut commands for Apache Web server is added to the Programs folder on the Start menu. This folder allows you to quickly access commands that let you work with Apache from the Start menu. The installation program allows you to choose whether you want to view a README file that contains information about the release of Apache you installed. If you choose to display the file, it will open when the installation is complete. You should carefully review the README file for any new release of Apache you install. Once Apache Web server is installed, you should install the Web server as a service. A service is a term used on Windows computers to describe a program that is automatically executed and managed by the operating

W

system. When you install Apache as a service, the program will start automatically and run in the background each time the computer is started. Once the Web server has been installed as a service, you should restart the computer. To confirm that Apache Web server has been installed and started properly, you can have the server display a page in a Web browser. After starting the Web browser you want to use, you enter the name or IP number of your computer as the URL in the Web browser. The IP number indicates the computer that is running the Web server software. If you do not know the IP number of your computer, you can use 127.0.0.1, which is the IP number that computers running TCP/IP use to refer to themselves. If the Apache installation was successful, a default Web page will be displayed.

After installing Apache Web server as a service, you can stop or restart Apache manually using Start menu commands. To stop or restart Apache on most Windows systems, click Start, select Programs and choose Apache Web Server. Then click Apache as a service and select Stop Service or Restart Service. You can also start and stop Apache Web server from within a command prompt window. In the command prompt window, change to the directory that contains the Apache program files, usually C:\Program Files\Apache Group\Apache, and type apache at the prompt to start the Web server. You can use the same method to stop Apache, except type apache -k shutdown at the prompt.

If you are removing Apache Web server from your computer, you may want to first uninstall Apache as a service to ensure that the program is removed correctly. To uninstall Apache as a service, click Start, select Programs and choose Apache Web Server. Then click Apache as a service and select Uninstall service. The Apache Web server program is written by a group of dedicated and talented volunteers who do not receive any payment for their work with Apache. Apache Web server is completely free to download, install and use. Unlike many free programs that require a fee to be paid if the software is used for business purposes, there are no restrictions on the use of Apache.

INSTALL APACHE WEB SERVER ON WINDOWS (CONTINUED)

My Documents

Online Services

My Computer

Outlook Express

Apache Programs Apache Web Server Accessories Games Online Services StartUp Apache as a service Install service

Jack Smith...

I This area displays the folder where program icons for Apache will be installed.

‡ Click Next to install
Apache on your computer.

I A dialog box appears, indicating that the installation is complete.

· Click Finish to close
the dialog box.

INSTALL APACHE AS A SERVICE

° If you do not want to
display the README file after the dialog box closes, click the box beside this option ( changes to ).

⁄ Click Start. ¤ Click Programs. ‹ Click Apache Web Server. › Click Apache as a service.

ˇ Click Install service. Á Restart the computer.
Apache Web server will start automatically each time the computer is started.

TEST APACHE

⁄ Start the Web browser
you want to use to test Apache Web server.

‹ Type the IP number of your computer or 127.0.0.1 and then press Enter.
I The Web browser displays a Web page generated by Apache Web server.

¤ Click this area to
highlight the current Web page address and then type http://.

6

7

PHP

GETTING STARTED WITH PHP

1

INSTALL APACHE WEB SERVER ON UNIX
pache Web server was originally developed and configured to run optimally on computers using the UNIX operating system, which makes Apache an ideal server to use to interpret and process PHP code on a Unix computer.

A

A recent release of Apache is available on the CD-ROM disc that accompanies this book, but you can check the www.apache.org Web site for the latest release of the server. The steps for installing Apache will depend on the UNIX operating system and the version of Apache you are using. You should carefully read the installation instructions included with the software. The Apache program files are usually stored in a compressed file with the .Z extension. To access the Apache files, you must first uncompress the compressed file using the gunzip command. The files are then archived into a single file with the .tar extension. You must extract the files from the archive using the tar xvf command. The extracted files are automatically saved in a new directory, which you can access using the cd command.
INSTALL APACHE WEB SERVER ON UNIX

The configure command allows you to set up some Apache installation settings to suit your needs. You may need to precede the configure command with ./ to indicate the location of the command on the computer. To specify a directory where you want Apache program files to be installed, you use the --prefix parameter with the configure command, specifying the name and location of the directory as the value of the --prefix parameter. After you run the configure command, you must execute the make command to prepare Apache Web server for installation. You then use the make install command to install the Apache files on the computer. Once the Apache software has been installed, you can use the start command to start the Web server.

To confirm that Apache has been installed and started properly, you can have the server display a page in a Web browser. The Lynx Web browser is a text-based browser available on most Unix computers. To display a test page generated by Apache, type lynx http:// followed by the IP number or name of your computer at the prompt. You can also use 127.0.0.1, which is the IP number computers using TCP/IP commonly use to refer to themselves. You can restart or stop Apache using the same method you use to start the server. To restart Apache, type /user/local/apache/bin/apachectl restart at the prompt. To stop Apache, type /usr/local/apache/bin/apachectl stop.

On some Unix systems, such as Red Hat Linux, you can use the Red Hat Package Manager (RPM) to install Apache Web server. RPM is an easy-to-use application that allows you to quickly install, update and remove applications from your computer. More information about RPM is available at the www.rpm.org Web site. The tar command can be used to combine multiple files into a single, more manageable file. The letters xvf indicate settings you can specify for the tar command. To display information about the settings you can use with the tar command, type man tar at the prompt. When you finish reviewing the settings, press q to quit.

⁄ At the command prompt, type gunzip followed by the name of the file you want to unzip. Then press Enter.

¤ To retrieve the unzipped files from the archive, type tar xvf followed by the name of the tar file that contains the Apache files. Then press Enter.
Note: A directory with the same name as the tar file is automatically created to store the files retrieved from the archive.

‹ To work in the directory that contains the Apache files, type cd followed by the name of the directory. Then press Enter.

› To specify a directory where
you want to install the Apache files, type ./configure – –prefix=. Then type the name and location of the directory and press Enter.

Á To install the Apache
files on the computer, type make install and then press Enter.

I This message appears when Apache has been successfully installed.

START APACHE

‡ To start Apache, type
the name and location of the directory you specified in the --prefix parameter in step 4, immediately followed by /bin/apachectl start. Then press Enter.

ˇ To prepare Apache for
installation, type make and then press Enter.

8

9

PHP

GETTING STARTED WITH PHP

1

CONFIGURE APACHE WEB SERVER TO WORK WITH PHP
hen you configure Apache Web server to work with PHP, you can set up PHP as a CGI binary or as an Apache module. Setting up PHP as an Apache module allows you to access additional capabilities of the PHP program, but for most installations it is sufficient to set up PHP as a CGI binary. To set up PHP as a CGI binary, you need to specify certain settings, or directives, in the Apache configuration file. Initially, Apache Web server cannot access PHP program files because the files are stored in a location outside the server's directory structure. The ScriptAlias directive allows you to create a virtual path Apache can use to access the directory that stores PHP program files. For example, on Windows computers, you can create the virtual path /php/ to allow you to access files in the C:\PHP directory.

W

To ensure that Apache Web server processes PHP files correctly, you use the AddType directive to specify the Multimedia Internet Mail Extensions (MIME) type used for PHP files. MIME types are a set of accepted file types typically used by Internet applications. PHP files use application/x-httpd-php as the MIME type. When using the AddType directive, you also indicate the file extensions you want to associate with PHP. PHP files commonly use the .php extension, but may also use other extensions, such as .phtml and .php3. The Action directive allows you to specify that Apache should pass PHP files to the PHP program for processing before displaying the files in a Web browser. When using the Action directive, you specify the MIME type of the files you want to pass to PHP as well as the name and location of the program that will process the files.

The name and location of the Apache configuration file depends on the operating system the computer uses. The name of the configuration file is usually httpd.conf. On Windows operating systems, the file is typically located in the conf subdirectory of the main Apache program directory. On Unix-based computers, the file is usually found in the /etc directory. When you specify a file path in the Apache configuration file, you should use slashes (/) instead of backslashes (\) in the path name. For example, the filename c:\php\php.exe should be typed as c:/php/php.exe.

To set up PHP as an Apache module, you should first move the php4ts.dll file, which is located in the main PHP directory, to your system directory. The name of the system directory depends on your operating system. On computers running Windows NT or 2000, you can move the file to the WINNT directory. To indicate that you want to use PHP as an Apache module, you must then add the following code to the Apache configuration file:
LoadModule php4_module c:/php/sapi/php4apache.dll AddType application/x-httpd-php .php .phtml

CONFIGURE APACHE WEB SERVER TO WORK WITH PHP

Save

⁄ Open the Apache configuration file in a text editor. ¤ To create a virtual path
that will allow Apache to access PHP program files, type ScriptAlias.

‹ Type the virtual path
you want to use.

› Type the actual location
of the PHP files, enclosed in quotation marks.

ˇ To specify which file extensions Apache should process as PHP files, type AddType. Á Type application/x-httpd-php
to specify the MIME type used for PHP files.

‡ Type the extensions
you want to use for PHP files.

° To specify that Apache should
pass files to the PHP program before displaying the files in a Web browser, type Action.

· Type application/x-httpd-php
to specify the MIME type of the files you want to pass to PHP.

‚ Type the name and location of the PHP program file that will process the files, enclosed in quotation marks.

— Save the Apache
configuration file.

I You can now use Apache Web server to process and display PHP pages you create.

10

11

PHP

GETTING STARTED WITH PHP

1

INSTALL INTERNET INFORMATION SERVER

M

icrosoft Internet Information Server (IIS) 5.0 is Web server software that allows you to host multiple Web sites on the Internet or on a network, such as a corporate intranet. IIS 5.0 is designed for use with the Windows 2000 operating system and is available on the Windows 2000 Professional CD-ROM disc. IIS 5.0 offers many advanced features that allow you to effectively host and manage even the busiest Web sites. Although IIS 5.0 is powerful server software, it can still be used to learn about Web servers and PHP. IIS 5.0 can be used to perform all the examples in this book. To install IIS on a computer, you must add parts of the Internet Information Services component to the computer. The parts of the component that must be added are Common Files, which are the files required to run IIS;

Internet Information Services Snap-In, which provides an interface you can use to administer your Web sites; and World Wide Web Server, which allows users to access your Web sites. IIS may affect the performance of an existing or new service pack you install on the computer. If you need to install a service pack, you should check the support.microsoft.com Web site to determine whether the service pack should be installed before or after IIS is installed. After IIS has been installed, you may have to restart the computer. IIS starts automatically each time the computer is started. PHP can be installed either before or after installing IIS. You can have multiple installations of IIS on a computer, but you can have only one installation of PHP.

Before installing IIS, you should log on to the computer using the administrator account, since a user account may not have permission to install all the components that IIS requires. Logging on to the computer as administrator will ensure that you have all the necessary permissions to install IIS. The Internet Information Services component includes several optional parts you can install. Documentation provides help files regarding the use of IIS and should be installed. File Transfer Protocol (FTP) Server allows IIS to host FTP sites. Personal Web Manager provides a graphical interface you can use to administer your Web sites. SMTP Service allows IIS to send e-mail messages.

After IIS is installed, the Internet Information Services window provides tools that allow you to administer your Web sites. Display the Control Panel and double-click Administrative Tools. In the Administrative Tools window, double-click Internet Services Manager to display the Internet Information Services window. You can remove IIS from a computer. Perform steps 2 to 9 below, except select each part of the Internet Information Services component you want to remove in step 6 ( changes to ). Removing IIS from a computer does not remove the Inetpub\wwwroot directory and the files it stores from the computer.

INSTALL INTERNET INFORMATION SERVER

My Do

My Do

My Do

My Do

Change or Remove Programs
My C My C

Change or Remove Programs
My C

Change or Remove Programs
My C

Change or Remove Programs

Add New Programs
My N P My N P

Add New Programs Internet Information Services (IIS) Add/Remov Windows Component 18.3 MB
My N P

Add New Programs
My N P

Add New Programs

World Wide Web Server Add/Remov Windows Component

1.9 MB

Recy

Add/Remove Windows Components

Recy

Recy

Recy

Add/Remov Windows Component

5.6

Int Ex

Int Ex

Int Ex

Int Ex

⁄ Insert the Windows 2000 Professional CD-ROM disc into a drive.
Note: If the Microsoft Windows 2000 CD dialog box appears, click to close the dialog box.

¤ In the Control Panel, double-click Add/Remove Programs to display the Add/Remove Programs window. ‹ Click Add/Remove Windows Components to display the Windows Components Wizard.

› Click Internet Information Services (IIS).
I This area displays a description of the Internet Information Services component.

ˇ Click Details to display the Internet Information Services (IIS) dialog box.

Á Click the box (

) beside each part of the Internet Information Services component you want to install ( changes to ).

‡ Click OK to confirm
your selections.

° Click Next to install
the parts of the Internet Information Services component you selected.

I In this example, Common Files,
Internet Information Services Snap-In and World Wide Web Server are selected.

I When the installation is complete, a message indicates that you have successfully completed the Windows Components Wizard.

I You should restart the computer before using Internet Information Server.

· Click Finish to close the
wizard.

12

13

PHP

GETTING STARTED WITH PHP

1

ADD A VIRTUAL DIRECTORY TO INTERNET INFORMATION SERVER
hen Internet Information Server (IIS) is installed, a number of directories are created that can be used to store Web pages and PHP pages. By default, these directories are stored in the document root directory C:\Inetpub\wwwroot. Only pages stored in the document root directory or its subdirectories can be displayed by users. You can create a virtual directory to make pages that are not stored in the document root directory or its subdirectories available for viewing. In order for PHP pages stored in a virtual directory to be processed by the Web server, the virtual directory must be properly configured. The Virtual Directory Creation Wizard can help you add and configure a virtual directory. You must give the virtual directory an alias, which is a name users will use to access pages in the directory. An

W

alias is often used to shorten a long directory name. For example, a directory named '2001_marketing_information' could be assigned the alias 'marketing'. Short directory names can help make a Web site easier for users to navigate. Virtual directories allow IIS to make a directory accessible to users of a Web site regardless of the location of the directory. For example, the directory C:\datapages can be added to the abccorp.com Web site as a virtual directory with the alias 'data'. Users can then use the address www.abccorp.com/data/ to access pages in the virtual directory. Users accessing a virtual directory you have added to IIS will not be able to determine the actual location of the directory on the computer.

You can also use Windows Explorer to add a virtual directory to IIS. Start Windows Explorer and then select the directory you want to add as a virtual directory. Click the File menu and then choose Properties. In the Properties dialog box, click the Web Sharing tab and then select the Share this folder option. In the Edit Alias dialog box that appears, type an alias for the virtual directory and then select the access and application permissions you want to use for the directory. Then click OK. Click OK in the Properties dialog box to add the virtual directory to IIS.

You can easily remove a virtual directory you no longer need from IIS. Perform steps 1 and 2 below to display the Internet Information Services window and then select the virtual directory you want to remove. Click the Delete button ( ) and then click Yes in the dialog box that appears. Removing a virtual directory prevents users from accessing pages stored in the directory but does not remove the directory and its contents from the computer.

ADD A VIRTUAL DIRECTORY TO INTERNET INFORMATION SERVER

Default Web Site

Site

New

Virtual Directory

⁄ In the Control Panel, double-click Administrative Tools to display the Administrative Tools window. ¤ Double-click Internet Services Manager to display the Internet Information Services window. 14

‹ Click

to display a list of Web sites on the Web server ( changes to ). you want to add a virtual directory to.

ˇ Click Action. Á Click New.

‡ Click Virtual Directory.

I The Virtual Directory Creation Wizard appears.

° Click Next to continue.

· Type an alias for the
virtual directory.

‚ Click Next to continue.

› Click the Web site
CONTINUED

15

PHP

GETTING STARTED WITH PHP

1

ADD A VIRTUAL DIRECTORY TO INTERNET INFORMATION SERVER
ou must specify the location of the directory you want to add as a virtual directory to IIS. You must also specify the access permissions for the directory. Access permissions determine how the Web pages, PHP pages and other files in the directory can be utilized.

Y

The Browse permission allows users to view a list of all the subdirectories and pages the virtual directory contains. When a user specifies a directory but does not specify the name of the page they want to display, the user can select a page, including a PHP page, from the list. After a virtual directory is created, all the pages and files in the directory will be available to users accessing the Web site. You should be careful to store only files and Web or PHP pages you want users to be able to view in the virtual directory. A virtual directory you add to IIS may be affected by folder permissions set by the Windows operating system. Folder permissions restrict who can access the folder and how the files in the folder can be used. For more information about folder permissions, see page 132.

The Read permission allows users to access Web or PHP pages and must be turned on for a virtual directory containing content you want to be displayed. The Read permission is turned on by default. The Run scripts permission allows scripts to run in the directory and must be turned on for virtual directories that contain PHP pages. The Run scripts permission is turned on by default. The Execute permission allows applications to run in the virtual directory. For security reasons, the Execute permission is rarely enabled. The Write permission allows files to be created in the directory and must be turned on for virtual directories containing PHP pages that create files.

You can later change the execute permissions for a virtual directory you have added to IIS. Display the Internet Information Services window and then select the virtual directory you want to change. Click the Properties button ( ) to display the Properties dialog box and then click the Virtual Directory tab. Click in the Execute Permissions area and select the option you want to use. The Scripts and Executables option allows all file types to be accessed or executed in the directory. The Scripts only option allows only scripts, such as PHP files, to be run. The None option allows access to only static files, such as HTML or image files.

After adding a virtual directory to Internet Information Server, you can enable or disable the logging function for the directory. Display the Internet Information Services window and then select the virtual directory you want to change. Click the Properties button ( ) to display the Properties dialog box and then click the Virtual Directory tab. Click the Log visits option to enable ( ) or disable ( ) the recording of visits to the directory in a log file.

ADD A VIRTUAL DIRECTORY TO INTERNET INFORMATION SERVER (CONTINUED)

sales

— Type the path of the directory you want to add as a virtual directory.

I You can also click the Browse button to locate the directory on the computer.

± Click Next to continue. 16

¡ Click an access permission in this area to turn the permission on ( ) or off ( ).

™ Click Next to continue.

I A message appears, indicating that you have successfully completed the Virtual Directory Creation Wizard.

£ Click Finish.

I The virtual directory is added to Internet Information Server and appears in this area.

¢ Click

to close the Internet Information Services window.

17

PHP

GETTING STARTED WITH PHP

1

SET WINDOWS FILE AND FOLDER PERMISSIONS
ou can change permissions to grant users and groups of users different types of access to a file or folder on Internet Information Server (IIS). The types of permissions that can be set for a file or folder depend on the operating system and file system installed on the Web server. The steps below are for use on a server running the Windows 2000 operating system with the NTFS file system.

Y

as change permissions. Modify allows users to modify, add, move and delete files. Read & Execute allows users to run applications, such as PHP pages. List Folder Contents allows users to display a list of files and folders stored in a folder. Read allows users to display files and Write allows users to change files. Windows file and folder permissions work with the access permissions set in IIS. Access permissions set for a folder in IIS apply to all users who access the folder. Windows folder permissions apply only to the users and groups you specify. When Windows file and folder permissions and IIS access permissions are set differently, the Web server uses the most restrictive permissions. For more information about IIS access permissions, see page 14.

Great care must be taken when setting file and folder permissions on a Web server. To gain a full understanding of file and folder permissions and the consequences of changing these permissions, you should consult the operating system and Web server documentation. Incorrectly setting file and folder permissions on a Web server can leave the server vulnerable to a range of problems, from accidental data deletion to serious security breaches. Incorrect file and folder permissions can also prevent all users from accessing the Web server. If you develop your PHP pages on a different Web server than you publish the pages on, you must ensure that the appropriate file and folder permissions are set on the Web server on which the pages are published. The permissions will not be transferred to the Web server when you transfer the files for the PHP pages.

If you no longer wish a user or group to have permission to access a file or folder, you can remove the user or group. Perform steps 1 to 4 below to display the Security tab of the Properties dialog box. Click the user or group that you no longer want to be able to access the file or folder and then click Remove.

When IIS is installed, a user account is created called IUSR_ followed by the name of the computer, such as IUSR_WEBSRV. This user account is part of the Everyone group. If you deny the Everyone group access to a file or folder, you can use the IUSR account to allow users to access information in the file or folder. You can allow or deny permissions for a user or group to specify how a file or folder can be accessed. Full Control allows users to modify, add, move and delete files, as well

SET WINDOWS FILE AND FOLDER PERMISSIONS
My Documents My Documents My Documents My Documents

Administrator (PHP-WIN2000\Administrator) My Computer My Computer My Computer IUSR_PHP-WIN2000 PHP-WIN2000 My Computer Internet Guest Account (PHP-WIN2000\I... phone_extensi ons My Network Places Properties My Network Places My Network Places My Network Places

Recycle Bin

Recycle Bin

Recycle Bin

Recycle Bin

Internet Explorer

Internet Explorer

Internet Explorer

Internet Explorer

⁄ Click the file or folder you want to change the permissions for.

¤ Click File. ‹ Click Properties to
display the Properties dialog box.

› Click the Security tab.
I This area lists the users and groups that can access the file or folder.

ˇ Click Add to display the
Select Users, Computers, or Groups dialog box.

Á Click a user or group in
this area you want to have access to the file or folder.

‡ Click Add.
I The user or group you
selected appears in this area.

I You can repeat steps 6 and 7 for each user or group you want to be able to access the file or folder.

· Click a user or group
in this area to view their permissions.

‚ Click an option to allow or deny the permission. — Click OK to confirm your changes. 19

° Click OK to confirm
your selection.

I This area displays the
permissions granted to the user or group.

18

PHP

GETTING STARTED WITH PHP

1

INSTALL PERSONAL WEB SERVER
icrosoft Personal Web Server (PWS) allows you to host a single Web site on your own computer to make Web and PHP pages available for viewing. This allows you to test and troubleshoot any problems before transferring the pages to a Web hosting service on the Internet. Personal Web Server 4.0 is available on the Windows 98 CD-ROM installation disc. PWS is not suitable for making information available directly to users on the Internet, but can be used to share documents on small networks or intranets. When installing PWS, you can choose the installation option that best suits your needs. The Minimum option installs only the files required to run PWS and is useful when installing PWS on a computer with limited hard drive space available. The Typical option installs the most commonly used PWS files and is the recommended option. The Custom option allows advanced Web site developers to choose the PWS files they want to install.
INSTALL PERSONAL WEB SERVER

M

The C:\Inetpub\wwwroot directory is automatically set as the home directory for PWS. The home directory is where you will store all the Web and PHP pages you want to be able to display. If you do not want to use the C:\Inetpub\wwwroot directory as the home directory, you can set another directory as the home directory. This is useful if you already have a directory that stores the pages you want users to be able to display and you do not want to copy the pages to the default home directory. After PWS and PHP are installed, you can begin creating and accessing Web and PHP pages. You can access pages using a Web browser installed on the same computer that is running PWS or a Web browser installed on another computer on the same network. To install PHP on a Windows-based computer, see page 22.

In addition to Windows 98, PWS can be used on a computer running the Windows 95 or Windows NT Workstation operating system. If you do not have your Windows 98 CD-ROM installation disc or you are using Windows 95 or Windows NT Workstation, you can obtain Personal Web Server 4.0 at the www.microsoft.com Web site. PWS is part of the Windows NT 4.0 Option Pack. You do not have to start PWS manually each time you want to use the software. Once you have installed the Web server software, PWS will start automatically each time you start your computer.

You can double-click the Personal Web Server icon ( ) on the taskbar to display the Personal Web Manager window. The Personal Web Manager window allows you to administer your Web site. For example, to stop PWS and make your Web site unavailable to users, click the Stop button. To restart PWS, click the Start button. In addition to wwwroot, several other directories are created when PWS is installed. In the Personal Web Manager window, you can click C:\Inetpub\wwwroot to display these directories.

C:\Inetpub\wwwroot

⁄ Locate and double-click the setup.exe file for the Personal Web Server setup program.
Note: On the Windows 98 CD-ROM disc, the setup.exe file is located in the add-ons directory in the pws subdirectory.

I The Microsoft Personal Web Server Setup dialog box appears, displaying information about Personal Web Server.

‹ Click the type of installation you want to perform.

Note: If you choose Custom, the following steps will be different for your installation.

I This area displays the location of the Personal Web Server home directory.

I If you want to use a different directory as the home directory, click Browse to specify the directory you want to use.

I When the installation is complete, a message appears thanking you for choosing Microsoft software. I The Personal Web Server icon appears on the taskbar.

ˇ Click Finish to exit the setup program.
I A message will appear asking you to restart your computer. Click Yes to restart your computer.

¤ Click Next to continue.

› Click Next to continue.

20

21

PHP

GETTING STARTED WITH PHP

1

INSTALL PHP ON A WINDOWS-BASED COMPUTER

I

n order to create and process PHP pages, you need to install PHP on your computer. Recent Windows versions of PHP can be used with Microsoft Windows 95, 98, NT, 2000, ME and XP. A recent release of PHP is included on the CD-ROM disc that accompanies this book. You can install PHP directly from the CD-ROM disc. The PHP program is available in a standard package, which includes a Windows installation program that allows you to easily install the software. PHP is also available in an expanded package that includes additional capabilities, such as database support for different operating systems. The standard package consists of a single executable file, while the expanded package is compressed into a Zip file. For Windows installations, it is usually sufficient to install the standard package using the Windows installation program. The computer on which you install PHP does not need to be connected to the Internet. You can use a stand-alone
INSTALL PHP ON A WINDOWS-BASED COMPUTER

computer that has Web server software and the PHP program installed to develop PHP pages. The pages can then be transferred to a Web server connected to the Internet or an intranet. The Web server to which you transfer the PHP pages can use any type of operating system, such as UNIX. When you start installing PHP, you must first accept a license agreement before the installation will continue. The setup program then allows you to choose the type of installation you want to perform. The Standard option is recommended for most users. The Advanced option allows experienced Web site developers to specify additional options for installing PHP. You must also choose the directory where you want the main PHP files to be stored. The default installation location is C:\PHP. You can specify another destination folder, but it is recommended that you accept the default folder.

The most recent release of PHP is available at the www.php.net Web site. If you are installing a more recent version of PHP than the one included on the CD-ROM disc that accompanies this book, you should carefully review the documentation included with the software. Newer releases of PHP may work differently than the version used in this book. Older versions of PHP are still available following the release of a new version. This is useful for system administrators who have standardized a particular version of PHP for use on their Web servers. Many Web and network administrators will not immediately upgrade to the latest available version of PHP unless they wish to take advantage of a specific feature of the new version. Administrators often decide to wait until a recent version of PHP has been widely used so they are aware of any errors or compatibility problems before installing the new version.

If you wish to install the expanded version of PHP, you will need a program capable of unzipping files, such as WinZip. WinZip is available at www.winzip.com. You can find complete installation instructions for the expanded version in the install.txt and README.txt files, which are included with the PHP Zip file. You should carefully review each of these files before installing PHP.

My Documents

My Documents

My Documents

My Documents

⁄ Double-click the icon for the PHP installation program to start installing the program.
I A welcome dialog box
appears.

I This area displays information about the PHP program.

¤ Click Next to continue.

I This area displays a license agreement you must read and accept before continuing.

‹ Click I Agree to accept
the agreement and continue.

› Click the type of installation
you want to perform. Note: If you choose Advanced, the following steps will be different for your installation.

ˇ Click Next to continue.

I This area displays the folder where PHP files will be installed. I You can click Browse to specify a different folder in which to install the files.

Á Click Next to continue.

CONTINUED

22

23

PHP

GETTING STARTED WITH PHP

1

INSTALL PHP ON A WINDOWS-BASED COMPUTER
hen installing PHP, the setup program allows you to specify the name of the mail server the computer will use to send e-mail messages. Specifying e-mail information is important if you intend to create PHP scripts that will send e-mail messages. Mail servers used to send e-mail messages use the Simple Mail Transfer Protocol (SMTP) and are often referred to as SMTP servers. The network administrator or ISP should be able to tell you the name of the mail server used to send messages. If you do not have access to an SMTP server, you can type "localhost" as the mail server name. You should also specify the e-mail address you want to display on outgoing e-mail messages. You would usually specify the address of the Web server administrator, usually referred to as the Webmaster. PHP can automatically perform many of the configuration tasks necessary to allow the PHP program to be used
INSTALL PHP ON A WINDOWS-BASED COMPUTER (CONTINUED)

W

correctly with some types of Web servers, such as Internet Information Server (IIS). The setup program allows you to select the type of Web server you will use with PHP. Depending on the Web server you select, PHP may automatically configure the server to work with PHP. When you have specified all the installation options, you can install PHP on your computer. The program should take only a few minutes to install. After PHP has been installed, you can configure PHP to suit your needs using the php.ini file included with the program. For more information about configuring PHP, see page 26. You may also need to configure the Web server you want to use with PHP. To configure Apache Web server, see page 10. For information about configuring another type of Web server, refer to the server's documentation.

PHP should be installed only on the hard drive of the Web server. You should not install PHP on a network drive or on removable media, such as a Zip drive. While it is technically possible to install PHP on these types of media, the performance of the program will deteriorate as the Web site is accessed more often. When specifying the e-mail address you want to display on outgoing e-mail messages, you may want to use an e-mail address set up especially for the Webmaster, instead of the personal e-mail account of the person who holds the Webmaster position. This lets you avoid having to reconfigure the PHP settings if the Webmaster changes in the future.

If the computer stops responding before the PHP installation is complete, there may be a problem with the installation program or with the disk drive where PHP is being installed. You should close all open programs and restart the computer before attempting to re-install the program. If the installation program stops responding again, you can download another copy of the installation files from the main PHP Web site. You should also check the computer's hard drive for possible errors.

My Documents

My Documents

My Documents

My Documents

My Computer

My Network Places

Recycle Bin

Internet Explorer

Connect to the Internet

‡ Double-click this area and type the name of the outgoing mail server.
I If you do not know the name of the mail server, you can type localhost.

° Double-click this area
and type the e-mail address you want to display on outgoing mail.

‚ Select the type of Web server you want to be configured for use with PHP.
I If your Web server does not appear in the list, you can select None to configure the server manually.

Note: PHP may not be able to automatically configure the Web server you select.

I A dialog box appears, indicating that you are ready to install PHP. I You can click Back to return to a previous screen and change the information you entered.

± Click Next to install
PHP on the computer.

I A dialog box appears when the installation is complete.

¡ Click OK to close the dialog box and then restart the computer.

— Click Next to continue.

· Click Next to continue.

24

25

PHP

GETTING STARTED WITH PHP

1

CONFIGURE PHP
ou can use the php.ini file to configure PHP to suit your needs. The php.ini file is a text file that controls how PHP processes scripts and is read by the Web server when PHP is started.

Y

You can edit the php.ini file using a simple text editor, such as Notepad on a Windows computer, or vi, a text editor available on most Unix computers. The format of the php.ini file is very simple. The file contains new lines and whitespace, which make the file easy to read. The new lines and whitespace are ignored and so do not affect the speed at which PHP operates. The php.ini file also contains comments, denoted by a semicolon. All the information from a semicolon to the end of the line is ignored. The php.ini file is comprised of many directives that control the behavior of PHP. A directive consists of a

directive name followed by an equal sign (=) and a value. For example, the directive used to turn off error logging is log_errors = Off. You can change the value of a directive to change the way PHP operates. For example, you can change how long a script can execute or how much memory a script can use. Each directive appears on its own line in the file. A semicolon precedes some of the directives in the php.ini file, such as the directives that implement extensions. These directives are commonly used directives that can be enabled simply by deleting the semicolon. For example, you can remove the semicolon that precedes the extension=php_gd.dll directive to allow PHP to generate images on the fly. Enabling an extension allows you to add extra functionality to PHP.

On computers running the Windows operating system, the php.ini file should be stored in the main Windows directory, such as C:\WINNT or C:\WINDOWS. On Unix systems, the location of the php.ini file can vary, but the file can often be found in the /usr/local/lib/ directory. PHP is comprised of many modules that are used to perform different tasks, such as the MySQL module, which is used to work with MySQL databases. The php.ini file can be used to change and specify module settings. Typically, each module has its own section heading, such as [MySQL] or [Sybase]. Any text enclosed in brackets [] is ignored. You can view more detailed information about configuring PHP at the www.php.net/manual/en/configuration.php Web site.

When you enable extensions in the php.ini configuration file, you may have to specify where the files for the extensions are stored. All extension files are stored in a directory called extensions. By default, the extensions directory is a subdirectory of the main PHP directory. If the extensions directory is stored in another location, you can use the extension_dir directive in the php.ini file to specify the location of the directory. The extension_dir directive can be found under the Paths and Directories comment. In the following example, the extensions directory is a subdirectory of the C:\webfiles directory.
Example: extension_dir = c:\webfiles

CONFIGURE PHP

⁄ Locate and open the php.ini file in a text editor.

CHANGE RESOURCE LIMITS

¤ Locate the Resource Limits comment.

‹ To change the maximum amount of time a script can execute, locate the max_execution_time directive.

› Delete the current
value and then type the value you want to use.

ˇ To change the maximum
amount of memory a script can use, locate the memory_limit directive.

Á Delete the current
value and then type the value you want to use.

ENABLE AN EXTENSION

· Delete the semicolon
that precedes the extension directive.

‡ To enable an extension,
locate the Dynamic Extensions comment.

‚ Save the changes you
made to the php.ini file.

° Locate the extension
directive you want to enable.

26

27

PHP

GETTING STARTED WITH PHP

1

VERIFY THAT PHP IS INSTALLED CORRECTLY

O

nce the Web server software and PHP have been installed and the server has been configured to use PHP, you should verify that the Web server and PHP are working together properly. To do so, you can create a simple PHP test file and save the file on the Web server. You can then display the file in a Web browser. The test file contains the phpinfo function enclosed between the <?php opening delimiter and the ?> closing delimiter. The delimiters tell the Web server where the PHP code begins and ends. A semicolon must follow the phpinfo function. The phpinfo function is used to display information about the setup and configuration of the Web server and PHP. Using this function allows you to verify that the Web server and PHP are working together properly, as well as confirm installation and configuration choices. The test file should be saved in the main, or document root, directory of the Web server.
VERIFY THAT PHP IS INSTALLED CORRECTLY

To display the test file in a Web browser, you must specify the address of the file. The address must begin with http:// and include the name or IP number of the Web server. If the Web browser you will use to view the file is running on the same computer as the Web server, you can use the computer name 'localhost' or the IP number 127.0.0.1. This is the IP number that computers using the TCP/IP protocol use to refer to themselves. If the Web server and PHP are functioning properly, the Web browser displays information about the Web server and PHP when you display the test file. You can view general information about PHP, such as the version number, server information, such as the name of the document root directory, and detailed information about PHP extensions and variables.

If the Web server and PHP information does not appear when you view the test file, you should review the topics in this book concerning the installation and configuration of the Web server and PHP. You should also review the documentation that came with the Web server and your version of PHP. You can use any text editor to create the PHP test file. When saving the file, ensure that the file is saved in a text-only format. If you do not want the phpinfo function to display all of the available information about the Web server and PHP, you can specify the type of information you want to display. To display only specific information, you can include one of the following arguments in the phpinfo function: INFO_GENERAL, INFO_CREDITS, INFO_CONFIGURATION, INFO_MODULES, INFO_ENVIRONMENT, INFO_VARIABLES or INFO_LICENSE.
Example: phpinfo(INFO_VARIABLES)

The name and location of a Web server's document root directory depends on the operating system installed, the type of Web server and the installation choices made when the Web server software was installed. On Windows-based computers running Internet Information Server (IIS) or Personal Web Server (PWS), the document root directory is typically C:\Inetpub\wwwroot. On Windows-based computers running the Apache Web server, the document root directory is typically C:\Program Files\Apache Group\Apache\htdocs. On Unix computers running the Apache Web server, the document root directory is typically /usr/local/apache/htdocs or /home/httpd/html.

⁄ Start a text editor. ¤ Type the opening
delimiter <?php.

‹ To display information
about the Web server and PHP, type phpinfo();.

ˇ Save the test file in the document root directory of the Web server.

› Type the closing
delimiter ?>.

I The filename must end with the .php extension. You may have to enclose the filename in quotation marks.

Á Start a Web browser. ‡ Click this area to
highlight the current Web page address.

· Type the name or
IP number of the Web server followed by /.

‚ Type the name of
the test file and then press Enter.

° Type http://.

I If the Web server and PHP are functioning properly, the Web browser displays information about the Web server and the current state of PHP.

28

29

PHP

GETTING STARTED WITH PHP

1

CHANGE UNIX FILE PERMISSIONS
ach file on a Unix computer includes a set of permissions that determine who can access, change or execute the file. The permissions for a file can be changed to control access to the file.

E

been assigned read, write and execute permissions and the group and other users have been assigned only read permission. New file permissions are usually set using the chmod command. The chmod command takes two arguments. The first argument specifies a value that represents the file permissions, while the second argument specifies the name of the file to which the permissions are to be assigned. The value that represents file permissions is usually specified using octal notation. Octal notation uses a base-8 numbering system. The octal value consists of three digits, which represent the permissions for the owner, followed by the permissions for the owner's group and the permissions for other users. For example, the -rwxrw-r-- permissions will have an octal value of 764. You should precede the octal value with a zero (0).

You can use this chart to determine and change the permissions for a file on a Unix computer.
PERMISSIONS: OCTAL VALUE: DESCRIPTION:

Only the owner of a file or the system administrator can change the permissions for a file. To view the current permissions for a file, you can use the ls -l command to display a list of all the files in a directory. The permissions are usually displayed to the left of each filename. On Unix systems, files can be assigned read (r), write (w), and execute (x) permissions. The permissions for a file are typically represented by a dash followed by a series of nine characters. The first three characters represent the permissions for the file's owner. The next three characters represent the permissions for the owner's group and the last three characters represent the permissions for all other users. For example, -rwxr--r-- indicates that the owner has

----x -w-wx r-r-x rwrwx

0 1 2 3 4 5 6 7

None Execute only Write only Write and execute Read only Read and execute Read and write Read, write and execute

You can change the owner of a file using the chown command. When using the chown command, you must specify the username of the new owner followed by the name of the file you want to assign to a new owner. For example, you can type chown sandyr index.html to give ownership of the index.html file to the user sandyr. You can use the chgrp command to assign a file to a new group. To use the chgrp command, specify the name of the group to which you want to assign the file followed by the name of the file. For example, you can type chgrp webadmins index.html to assign the index.html file to the webadmins group.

CHANGE UNIX FILE PERMISSIONS

⁄ To view a list of files in the current directory and the permissions for each file, type ls –l at the prompt. Then press Enter.

I The list of files appears. This area displays the permissions for each file.

¤ To change the permissions for a file, type chmod. ‹ Type the octal value that represents the permissions you want to assign to the file. The octal value should be preceded by a 0.

› Type the name of the
file to which you want to assign the permissions. Then press Enter. Note: To assign the same permissions to more than one file, you can type the name of each file after the octal value.

ˇ Repeat steps 2 to 4
for each file for which you want to change permissions.

Á To view the new file permissions, type ls –l and then press Enter.

I An updated list of files appears, displaying the new file permissions.

30

31

PHP

GETTING STARTED WITH PHP

1

TRANSFER PAGES TO A WEB HOSTING SERVICE

I

f you do not have a Web server that can make your Web and PHP pages available on the Web, you must transfer the pages to a Web hosting service's Web server. You need a File Transfer Protocol (FTP) program to transfer your Web and PHP pages to a Web server. WS_FTP Pro for Windows is a popular FTP program. In the example below, we use WS_FTP Pro version 6.7. You can obtain the latest version of WS_FTP Pro at the www.ipswitch.com Web site. Before you can transfer Web and PHP pages to a Web hosting service's Web server, you must set up a connection to the server. FTP programs can connect and transfer files to different types of Web servers using different types of operating systems. For example, you can use an FTP program to transfer PHP pages developed on a Windows computer to a Unix computer.
SET UP A CONNECTION

To set up a connection to a Web server, you must know the address of the server, your user ID and your password. If you do not know this information, contact your Web hosting service. Many FTP programs allow you to save your password, which saves you from having to retype your password each time you transfer Web pages to the Web server. When you save your password, anyone who uses your computer will be able to connect to the Web server, so you should not save your password if other people have access to your computer. You need to set up a connection to a Web server only once. After you set up a connection, you can connect to the server at any time.

Web hosting services are companies that make Web pages available on the Web. When choosing a Web hosting service, you should consider several factors. For example, you may want to look for a Web hosting service with adequate technical support services to meet your needs. You should also ensure that your hosting service offers enough storage space for any multimedia files included in your pages. A good Web hosting service will also be able to supply you with statistics about your pages, such as where users are from and any error messages that may have been generated.

You can create a new directory to store and organize your Web server connections. In the Configured Sites area of the Connection dialog box, click the directory you want to store the new subdirectory. If you want to create a main directory, click the Sites directory. Then click to create the directory. In the New Folder dialog box, type the name of the new directory and then click Finish. FTP programs allow you to set up multiple connections. This is useful if you want to use one connection to transfer your Web and PHP pages to a Web server and another connection to download files from a different Web server. Perform steps 1 to 9 starting on page 32 for each connection you want to set up.

CONNECT TO A WEB SERVER

www.company.com jsmith

Country Kitchen Web

⁄ Start the FTP program you will use to transfer your Web pages to a Web server.
I The Connection dialog
box appears. to display the New Site dialog box and set up a new connection to the Web server.

‹ Type a name for the connection. › Click this area and type the address of the Web server you want to transfer your Web pages to. ˇ Click Finish to continue.

I The name of the connection appears in this area.

I The address of the Web server you specified appears in this area.

‡ Click this area and type
your password. A symbol (x) appears for each character you type to prevent others from seeing your password.

Á Click this area and
type your user ID.

· Click Save to have the program store the information you entered for the connection.

⁄ Click the connection for
the Web server you want to transfer your Web pages to.

¤ Click Connect to
connect to the Web server.

¤ Click

° To save your password so
you will not need to retype the password again later, click this option ( changes to ).

I If the connection you set up is not displayed, click the plus sign ( ) beside the Ipswitch directory ( changes to ).

CONTINUED

32

33

PHP

GETTING STARTED WITH PHP

1

TRANSFER PAGES TO A WEB HOSTING SERVICE

O

nce you have connected to a Web hosting service's Web server, you can transfer information to the server. You can transfer a single file, multiple files or an entire directory to the Web server in one operation. Before transferring your Web or PHP pages to a Web server, you should make sure the filenames all have the .html, .htm or .php extension and do not include spaces or special characters, such as * or &. You should also check with your Web hosting service to ensure that you have used the correct name for your home page. You must also locate the directory on the Web server you want to transfer your files and directories to. This directory is often named "public." If you do not know the name of the directory, contact your Web hosting service. Your Web hosting service may also stipulate where you can place PHP files on the Web server.

If your connection to the Web server is idle for an extended period of time, the server may automatically disconnect you. This helps ensure that the Web server's resources are available for other people who need to access the server. If you later make changes to the Web or PHP pages stored on your computer, you must transfer the updated pages to the Web server. The updated Web or PHP pages will replace the old pages on the server. When you transfer updated pages, a message may appear, indicating that the updated pages will replace the old pages. Many Web and PHP pages work together and require other pages in order to work correctly. When transferring files, you should ensure that you also transfer any needed support files.

If you have accidentally transferred a file to the Web server, you should delete the file from the server. This helps save storage space and prevents clutter on the Web server. To delete a file from the Web server, select the file in the right pane of the WS_FTP Pro window and then click the Delete button. To confirm the deletion, click Yes in the dialog box that appears. You can delete a connection you no longer need. Click the connection in the Configured Sites area of the Connection dialog box and then click to delete the connection. To confirm the deletion, click Yes in the dialog box that appears.

You should check all references to files on your Web and PHP pages before transferring the pages to a Web server. For example, if an image on a page is stored in the same directory as the page, make sure you specified only the name of the image (example: banner.gif). If the image is stored in a subdirectory, make sure you specified the location and name of the image (example: images/banner.gif). If you use a Macintosh computer to create your PHP pages, you can use the Fetch FTP program to transfer your pages to a Web hosting service. Fetch is available at the www.fetchsoftworks.com Web site.

TRANSFER PAGES TO A WEB HOSTING SERVICE
www.company.com www.company.com www.company.com www.company.com

public My Webs

recipes . htm

I The WS_FTP Pro window appears. I This area displays the directories and files stored on the Web server.

⁄ Locate the directory you want to transfer your Web pages to. In many cases, the directory is named "public." ¤ Double-click the
directory to display the contents of the directory.

I This area displays the directories and files stored on your computer.

Note: You can double-click to move up one level in the directory structure.

ˇ Click the file or directory
you want to transfer to the Web server.

Á Click to transfer the file or directory to the Web server.

I The file or directory appears on the Web server.

‹ Locate the directory
that contains the Web or PHP page(s) you want to transfer to the Web server.

› Double-click the
directory to display the contents of the directory.

‡ Repeat steps 3 to 6 for
each file and directory you want to transfer.

° Click Close to end the connection to the Web server. · Click Exit to exit the program. 35

34

PHP

LANGUAGE BASICS

2

INSERT PHP CODE INTO A WEB PAGE
dding PHP code to an HTML document allows you to create dynamic, interactive Web pages. You can add PHP code to an existing Web page or to a new HTML document you create. PHP code is inserted into HTML code using the <?php opening delimiter and the ?> closing delimiter. The delimiters tell the Web server where the PHP code begins and ends. You can add multiple sections of PHP code to an HTML document. You must use an opening and closing delimiter for each section of code. If the PHP code will generate output for display in a user's Web browser, you can use HTML tags to format the output. PHP code used to generate output must be inserted between the <body> and </body> tags. When a Web server receives a request for a Web page containing PHP code, the Web server processes all the code found between the <?php and ?> delimiters. The

A

information generated by the PHP code is inserted into the Web page before the page is sent to a user's Web browser. Users who visit the page will not be able to see the PHP code, even if they display the source code for the page. When saving a PHP page you have created, you must add the .php extension to the filename of the page. Some text editors do not recognize the .php extension, so you may have to enclose the filename in quotation marks, such as "index.php". The PHP page must be saved in the appropriate location on your Web server before the page can be displayed. If you do not want to use the .php extension for your PHP pages, you can configure your Web server to use another extension, such as .phtml, .htm or .html. For more information, see page 10.

In addition to the <?php and ?> delimiters, there are other delimiters you can use to insert PHP code into a Web page. If you have the short_open_tag setting enabled in your PHP configuration file, you can use the <? and ?> delimiters. You can also use the ASP-style delimiters <% and %>. To use ASP-style delimiters, you need to enable the asp_tags setting in the PHP configuration file. You can use the <script> tag to insert PHP code into a Web page. Using the <script> tag does not require any changes to the settings in the PHP configuration file.
Example: <script language="php"> print "Thank you. Please visit again."; </script>

Instead of the print function, you can use the echo command to generate output.
Example: echo "Thank you. Please visit again.";

You can use the <?= and ?> delimiters to insert a single print statement into an HTML document. Using the <?= and ?> delimiters reduces the amount of code you have to type and can make your script easier to read.
Example: <?php print $message; ?> Can be typed as: <?= $message ?>

INSERT PHP CODE INTO A WEB PAGE
Insert PHP Code - Microsoft Internet Explorer

⁄ Type <?php where
you want to insert PHP code into a Web page.

¤ Type ?> where you
want to end the PHP code.

‹ Between the opening and closing delimiters (<?php and ?>), type the PHP code you want to insert into the Web page.

I In this example, we use the print function to generate output.

SAVE AND DISPLAY A PHP PAGE

ˇ Save the page in the
appropriate location on your Web server.

› Repeat steps 1 to 3
for each section of PHP code you want to insert into the Web page.

I The filename must end with the .php extension. You may have to enclose the filename in quotation marks.

Á Display the PHP
page in a Web browser.

I The Web browser displays the result of inserting PHP code into a Web page.

36

37

PHP

LANGUAGE BASICS
Instead of //, you can use the hash symbol (#) to indicate the start of a single-line comment. Both styles of adding comments are acceptable, but you should choose one style and use it consistently throughout your code.

2

ADD A COMMENT TO A PHP PAGE
dding comments to your PHP code is a good programming practice and can help explain important or difficult sections of code. Web servers ignore comments in PHP code, so adding comments to a PHP page will not slow down the processing of the page. Even relatively simple code may be difficult to understand without comments. For example, you may use a variable named $totalCost in your code. You could use a comment to explain whether the variable stores the total cost of all the products or only some of the products. Besides describing the purpose of code, comments can contain information such as the name of the author and the author's contact information. A single-line comment is preceded by // and can be included at the end of a line of code. A single-line comment can also have its own line in a PHP page. All the information following // to the end of the line will be ignored by the Web server.

A

To add a comment that spans multiple lines, use /* before the first line and */ at the end of the last line. While comments can be any size, very lengthy comments may make your code difficult to read. The most effective comments are descriptive and concise. In addition to creating multi-line comments, you can use /* and */ to help troubleshoot a PHP page. For example, if your PHP code is generating an error, you can use /* and */ to comment out the suspect lines. If you confirm that the error lies somewhere else in the PHP code, you can simple remove /* and */ to restore the lines of code. Commenting out the lines saves you from having to erase the lines and type them again later. This technique is very effective for debugging large, complex sections of code. For more information about troubleshooting PHP code, see pages 208 to 219.

Example: <?php // Display a welcome message print "Welcome to my Web page.<br>"; # Display my name print "My name is Martine."; ?>

When creating multi-line comments, you should be careful not to place one comment inside another comment. Nested comments will generate an error when the PHP page is processed.
TYPE THIS: <?php /* Name: comments.php Purpose: To show how not to use delimiters Author: Martine Edwards <martine@abccorp.com> /* Display a welcome message */ print "Welcome to my Web page."; PHP will try to process these lines of comments and generate an error */ ?>

RESULT: Parse error: parse error in c:\web_apps\apache\htdocs\comments.php on line 16

ADD A COMMENT TO A PHP PAGE

⁄ To add a single-line comment, type //. 38

¤ Type the comment.

I Repeat steps 1 and 2 for each single-line comment you want to add.

I A single-line comment can be on its own line or at the end of a line of code.

‹ To add a multi-line
comment, type /*.

ˇ Type */ to complete the multi-line comment.

Á Display the PHP page
in a Web browser.

I The comments do not appear on the PHP page.

› Type the comment. 39

PHP

LANGUAGE BASICS

2

CREATE A NUMERIC VARIABLE
variable is a name that represents a value. For example, you could have the variable $myAge represent the value 29. A numeric variable is often used to store a value that may change, such as the result of a calculation or data retrieved from a database.

A

To create a numeric variable, you use the assignment operator (=) to assign an initial value to a variable name. A numeric variable can store an integer, such as 1 or 3452, or a floating-point number, such as 9.3 or 0.0054. A numeric variable can also store a negative value or no value at all. To specify a negative value, you simply place a minus sign (-) directly in front of a number. A numeric variable with no value has a null value, which is not the same as a value of zero (0). In PHP, a variable name must start with a dollar sign ($). The next character must be a letter or the underscore character (_) followed by any combination of letters and numbers.

A variable name can consist of multiple words. You can use a lowercase letter to begin the first word and then capitalize the first letter of each of the following words to make the name easy to read, such as $myDateOfBirth. The underscore character (_) can also be used to separate the words in a name, such as $my_age. You should choose one format and use it consistently to make your script easier for other people to understand. Variable names are case sensitive. For example, the variable $myAge is different than the variable $MYAGE. Several sections of PHP code can be inserted into one HTML document. The value of a variable created in one section of PHP code will be accessible in subsequent sections of the code.

Unlike other languages, such as C++ and Java, PHP is not a strongly typed language. In PHP, you do not need to explicitly declare the type of variable you want to create. For example, the same variable can be used to represent first an integer and then a floating-point number with no data type declarations.
Example: $a = 1; $a = $a + 1.5;

When working with numbers, PHP assumes you are working in base 10, or decimal notation. PHP also supports base 8, or octal notation, and base 16, or hexadecimal notation. To specify a value in octal notation, you place a zero (0) before an octal number. To specify a value in hexadecimal notation, you place a zero (0) and the letter x before a hexadecimal number. When you display an octal or hexadecimal number, the result is shown in decimal notation.
Example: $a = 020; print $a; print "<br>"; $b = 0x10; print $b; Result: 16 16

You can use exponential notation to specify a very large or very small number as the value of a variable. In this following example, $a is equal to 123000 and $b is equal to 0.0000123.
Example: $a = 1.23e5; $b = 1.23e-5;

CREATE A NUMERIC VARIABLE

⁄ To create a numeric variable, type $ followed by a name for the variable.

I The dollar sign ($) must be followed by a letter or an underscore character (_).

¤ Type = followed by
the value you want to assign to the variable.

I The value can be an integer or a floating-point number.

‹ Type the code that
uses the numeric variable you created.

I In this example, we use the print function to display the value of the variable.

› Display the PHP page
in a Web browser.

I The Web browser displays the value of the numeric variable.

40

41

PHP
The following is a list of several common escape sequences that can be enclosed in double-quoted strings.
ESCAPE SEQUENCE: DESCRIPTION:

LANGUAGE BASICS

2

CREATE A STRING VARIABLE
ou can create a variable that stores a string value. A string is a collection of characters that are enclosed in single or double quotation marks. The information in a string is treated as a scalar value, or a single piece of information. The quotation marks identify the beginning and end of a string and allow PHP to work with the string as one piece of information.

Y

the string. For example, a variable in a double-quoted string will be replaced with the value assigned to the variable when the string is processed. When including a character required by the PHP programming language in a double-quoted string, you must precede the character with a backslash if you do not want the character to be evaluated. For example, when a dollar sign ($) is placed in a string, PHP will evaluate the dollar sign as the beginning of a variable name unless you use a backslash to escape the symbol. When a string is enclosed in single quotation marks, PHP does not evaluate variables or escape sequences in the string, except for the \\ and \' escape sequences. You can use the \\ escape sequence to display a backslash and the \' escape sequence to display a single quotation mark in a single-quoted string.

\n \r \t \\ \" \$ \012 \x0A

Start a new line. Insert a carriage return. Insert a tab. Insert a backslash. Insert a double quotation mark. Insert a dollar sign. Use an octal ASCII value (example: 12). Use a hexadecimal ASCII value (example: 0A).

To create a string variable, you use the assignment operator (=) to assign a string value to a variable name. A variable name must begin with a dollar sign ($) followed by a letter or the underscore character (_). Variable names can consist of multiple words and are case sensitive. Escape sequences allow you to include special characters, such as tabs, newlines and carriage returns in a string and are often used to format text that will be displayed on a screen or stored in a file. When a string you assign to a variable is enclosed in double quotation marks, PHP will evaluate any escape sequences and variables included in
CREATE A STRING VARIABLE

Strings can be joined together using the concatenation operator (.). The concatenation operator can be used to join two strings, such as "Tom" . "Smith", or a combination of strings and variables, such as $myString = "I am " . $myAge . " years old". PHP is often used to output HTML code. When assigning an HTML tag, such as <IMG SRC="my_image.gif" WIDTH="100" HEIGHT="100"> to a string variable, you must use escape sequences to include any special characters, such as quotation marks, within the tag. The HTML code within the string will be processed by the Web server and applied to the output for a client's Web browser.
Example: $myImageTag = "<IMG SRC=\"my_image.gif\" WIDTH=\"100\" HEIGHT=\"100\">";

My Web Site

⁄ To create a string variable ‹ Between the quotation using double quotation marks, type the information marks, type $ followed by you want the string to contain. a name for the variable. I PHP will evaluate any variables and escape sequences ¤ Type = "". you include in the string. 42

› To create a string variable using single quotation marks, type $ followed by a name for the variable. ˇ Type = ''.

Á Between the quotation
marks, type the information you want the string to contain.

‡ Type the code that
uses the string variables you created.

I In this example, we use the print function to display the values of variables.

° Display the PHP
page in a Web browser.

I The Web browser displays the values of string variables.

I PHP will not evaluate information you include in the string.

43

PHP

LANGUAGE BASICS

2

CREATE A CONSTANT
constant is a name that represents a value you want to remain the same throughout a PHP script. Regardless of where a constant is created in a PHP script, the constant can be accessed anywhere in the script.

A

Once a constant has been created, it can be used within calculations in the same way you use a variable. Attempting to change the value of a constant when using the constant will generate an error. Unlike variables, constants do not start with a dollar symbol, so PHP cannot determine when a constant is being used in a string. For example, in the string "This page was created by AUTHOR", PHP will interpret the constant AUTHOR not as a value, but as the word AUTHOR. You must separate a constant you are using from the rest of the string to allow the constant to be evaluated correctly. PHP also allows you to access predefined constants from within PHP code. For information about predefined constants, see page 80.

It is good programming practice to define all your constants at the beginning of your PHP script. Keeping all your constants in the same location makes it easy to find and modify the constants. In addition to a string or number, you can use an expression as the value for a constant. This is useful when you want to display a different value for the constant depending on the value of a variable. For example, you can create a constant that stores a personalized greeting based on the user name of the person visiting your Web site.
Example: <?php $userName = Lindsay; define("GREETING", "Hello " . $userName); print GREETING; ?>

You use the define function to create a constant in your script. You must first specify the name of the constant you want to create. Constant names must start with a letter or an underscore (_) character. To help distinguish constants from variables, you should use all uppercase letters in a constant name. The name of the constant must be enclosed in quotation marks when specified in the define function. After naming a constant, you must specify the value you want to assign to the constant. A constant can store any string, integer or floating point value.

You can use the defined function to verify whether a constant exists in your script. If the constant exists, the defined function will return a value of 1. If the constant does not exist, the defined function will return a value of 0. Using the defined function is useful for quickly determining if a constant exists in a long script that uses a large number of constants.
Example: <?php if (defined("AUTHOR")) { print "Page created by: "; print AUTHOR; } else { print "Author unknown"; } ?>

CREATE A CONSTANT

⁄ Type define() where you want to create a constant.

¤ Between the parentheses, type the name of the constant you want to create, enclosed in quotation marks.

‹ Type a comma followed by the value you want to assign to the constant.
I If the value for the constant is a string, you must enclose the text in quotation marks.

› Type the code that
uses the value of the constant.

I If you are using the constant with a string, make sure the constant is not enclosed within the quotation marks for the string.

ˇ Display the PHP page
in a Web browser.

I The Web browser displays the result of using a constant.

44

45

PHP

LANGUAGE BASICS

2

TYPES OF OPERATORS

INTRODUCTION TO OPERATORS

ARITHMETIC OPERATORS

P

HP provides numerous operators that can be used to assign values to variables, perform calculations, make comparisons and much more. An operator takes one

or more arguments, called operands. A sequence of operands separated by one or more operators that produces a result in a PHP script is referred to as an expression.

You can use arithmetic operators to perform mathematical calculations. + (Addition) Finds the sum of two values.
print 3 + 3;

* (Multiplication) Multiplies two values.
print 2 * 3;

% (Modulus) Divides one value by another value and returns only the remainder in the result.
print 7 % 5;

Associativity When an expression contains multiple operators that have the same precedence, the associativity of the operators determines which part of the expression PHP evaluates first. Operators can have left associativity, right associativity or can be non-associative. If operators have left associativity, then the leftmost operator is processed first. For example, the result of the expression 5 - 3 + 2 is 4 rather than 0. The opposite holds true for operators that have right associativity. Some operators have neither left nor right associativity and are known as non-associative. When a non-associative operator is used beside others with the same precedence, you must surround the operator and its operands with parentheses to ensure that it will return the desired result.

Order of Precedence When an expression contains several operators, PHP processes the operators in a specific order, known as the order of precedence. The order of precedence ranks operators from highest to lowest precedence. Operators with higher precedence are evaluated before operators with lower precedence.

Displays 6 - (Subtraction) Finds the difference between two values.
print 6 - 3;

Displays 6 / (Division) Divides one value by another value.
print 9 / 3;

Displays 2

Displays 3

Displays 3

Parentheses Regardless of the precedence and associativity of operators, you can use parentheses to dictate the order in which PHP should process operators. In an expression, PHP processes operators and operands enclosed in parentheses first.

CONCATENATION OPERATOR

You can use the concatenation operator (.) to combine values into a string. This is useful when you want to combine text with a variable that has text value.

. (Concatenation)
$temp = "hot"; $myString = "It is " . $temp . " today."; print $myString;

Displays It is hot today. The following table shows the associativity of operators and the order of precedence from highest to lowest.
INCREMENT AND DECREMENT OPERATORS

Associativity Non-associative Right Right Left Left Left Non-associative Non-associative Left Left

Operators new [ ! ~ ++ -- (int) (double) (string) (array) (object) @ * / % + - . << >> < <= > >= == != === !== & ^

Associativity Left Left Left Left Left Right Left Left Left Left

Operators | && || ? : = += -= *= /= .= %= &= |= ^= ~= <<= >>= print and xor or ,

Increment and decrement operators are useful for creating counters in your script. These operators increase or decrease the value of an expression by one.

++value (Pre-increment) Adds 1 to a value before the expression that uses the value is processed.
$a = 5; print ++$a;

--value (Pre-decrement) Subtracts 1 from a value before the expression that uses the value is processed.
$a = 5; print --$a;

Displays 6 value++ (Post-increment) Adds 1 to a value after the expression that uses the value is processed.
$a = 5; print $a++; print "<br>"; print $a;

Displays 4 value-- (Post-decrement) Subtracts 1 from a value after the expression that uses the value is processed.
$a = 5; print $a--; print "<br>"; print $a;

Displays 5 6

Displays 5 4

46

47

PHP

LANGUAGE BASICS

2

INTRODUCTION TO OPERATORS
TYPES OF OPERATORS
ASSIGNMENT OPERATORS

(CONTINUED)

BITWISE OPERATORS

The assignment operator (=) can be used to set one value to another value. You can also combine the assignment operator with arithmetic operators to more easily perform calculations. For example, the expression $b = $b + 12 = (Assignment) Sets one value to another value.
$a = 3; print $a;

can be written as $b += 12. Combining operators reduces the amount of code you need to type and can make your scripts easier to read.

Bitwise operators, such as &(AND) and |(OR), are used to compare and manipulate values at the binary level. This can be very useful when dealing with binary files such as image and sound files. You can find more information about bitwise operators at the www.php.net/manual/en/language.operators.bitwise.php Web site.
COMPARISON OPERATORS

+= Adds one value to another value.
$a = 3; $a += 3; print $a;

-= Subtracts one value from another value.
$a = 3; $a -= 1; print $a;

*= Multiplies one value by another value.
$a = 3; $a *= 2; print $a;

/= Divides one value by another value.
$a = 6; $a /= 2; print $a;

.= Combines two values.
$a = "This is "; $a .= "a test."; print $a;

You can use comparison operators to compare values in your script. == (Equal to) Checks if one value is equal to another value.
$x = 7; $y = "7"; if ($x == $y) print $x . " is equal to " . $y;

Displays This is a test.

< (Less than) Checks if one value is less than another value.
$x = 5; $y = 9; if ($x < $y) print $x . " is less than " . $y;

Displays 3

Displays 6

Displays 2

Displays 6

Displays 3

LOGICAL OPERATORS

Displays 7 is equal to 7 === (Identical to) Checks if one value is equal to and of the same type as another value.
$x = 7; $y = 7; if ($x === $y) print $x . " is identical to " . $y;

Displays 5 is less than 9 > (Greater than) Checks if one value is greater than another value.
$x = 9; $y = 5; if ($x > $y) print $x . " is greater than " . $y;

You can use logical operators to check if a statement in your script is true. And Checks if two or more statements are true.
$x = 7; $y = 5; if (($x == 7) and ($y == 5)) print "True";

! Checks if a statement is not true.
$y = 5; if (! ($y == 10)) print "True";

Displays 9 is greater than 5 <= (Less than or equal to)

Displays 7 is identical to 7 != (Not equal to) Checks if one value is not equal to another value.
$x = 8; $y = 4; if ($x != $y) print $x . " is not equal to " . $y;

Displays True &&

Displays True Or Checks if at least one of two statements is true.
$x = 7; $y = 5; if (($x == 7) or ($y == 8)) print "True";

Checks if two or more statements are both true.
$x = 7; $y = 5; if (($x == 7) && ($y == 5)) print "True";

Checks if one value is less than or equal to another value.
$x = 5; $y = 5; if ($x <= $y) print $x;

Displays True ||

Displays 8 is not equal to 4 !== (Not Identical to) Checks if two values are not equal or not of the same type.
$x = 8; $y = 9; if ($x !== $y) print $x . " is not identical to " . $y;

Displays 5 >= (Greater than or equal to) Checks if one value is greater than or equal to another value.
$x = 7; $y = 5; if ($x >= $y) print $x;

Displays True Xor Checks if only one of two statements is true.
$x = 7; $y = 5; if (($x == 7) xor ($y == 8)) print "True";

Checks if at least one of two statements is true.
$x = 7; $y = 5; if (($x == 7) || ($y == 5)) print "True";

Displays True

Displays 8 is not identical to 9

Displays True

Displays 7

48

49

PHP

LANGUAGE BASICS
When a calculation contains several operators, such as 4 - 5 + 2 * 2, PHP processes the operators in a specific order, which is determined by operator precedence. For example, the * operator is processed before the - or + operators, since * has a higher precedence. If you want to override operator precedence, you can use parentheses to dictate the order in which PHP should process operators. PHP will process operators and operands enclosed in parentheses first.
Example: $fahrenheit = 100; $celsius = ((($fahrenheit - 32) / 9) * 5);

2

PERFORM A NUMERIC CALCULATION
ou can perform calculations to manipulate numeric data in a PHP page. Calculations can be performed using literal values, such as 3 or 56.23, as well as variables, such as $quantity or $cost.

Y

Calculations consist of operators and operands. Operators determine the type of calculation that will be performed. Operands are the values that are manipulated in a calculation. For example, the calculation 4 + 5 contains the operands 4 and 5 and the + (addition) operator. The + operator is an example of an arithmetic operator. Arithmetic operators are commonly used when performing numeric calculations and also include the - (subtraction), * (multiplication), / (division) and % (modulus) operators. Other types of operators that can be used when performing numeric calculations include comparison, logical, incrementing and decrementing operators. For more information about operators, see page 46.

You can use the assignment operator (=) to assign a calculation to a variable. When PHP processes a variable that contains a calculation, the calculation is performed and the result is stored in the variable. The stored result will only be available within the PHP page. Once the processing of the PHP page is complete, the variable ceases to exist. When a calculation contains an operand that is a variable, the calculation will use the value of the variable at the time the calculation is performed. If the value of the variable later changes, the change will not affect the result of the calculation.

Dividing a number by zero is a mistake commonly made when performing numeric calculations. If you divide a number by zero in PHP, a Division by zero error will result. The most common cause of this type of error is misspelling or mistyping a variable name in a calculation. When you misspell or mistype a variable name in a calculation, the variable will have a value of zero.
TYPE THIS: $myNumber = 10; print 1000 / $myNumbeR;

RESULT:

Warning: Division by zero in c:\web_apps\apache\htdocs\calculation.php on line 23

PERFORM A NUMERIC CALCULATION
Perform a Numberic Calculation - Microsoft Internet Explorer

⁄ Type an operand you want to use in a calculation.

¤ Type the operator for the type of calculation you want to perform.

‹ Type the second operand you want to use in the calculation.

› To assign the calculation
to a variable, type $ followed by a name for the variable. Then type =.

ˇ Type the code that
uses the result of the calculation.

I In this example, we use the print function to display the result of the calculation.

Á Display the PHP page
in a Web browser.

I The Web browser displays the result of performing a numeric calculation.

50

51

PHP
If you are going to execute only one line of code based on a condition, you can place the code to be executed on the same line as the if statement.
Example: if ($currentTemp > $hot) { print "It's hot."; } Can be typed as: if ($currentTemp > $hot) print "It's hot.";

LANGUAGE BASICS

2

USING THE IF STATEMENT
sing an if statement allows you to test a condition to determine whether the condition is true or false. When the condition is true, the section of code directly following the if statement is executed. For example, you can create a PHP page that displays a Good Morning message if a user views the page between 5:00 AM and 11:59 AM. If the condition is false, no code from the if statement is executed. A condition will be false if it evaluates to an empty string (" "), a string zero ("0"), an integer zero (0) or a null value.

U

A section of code you want to be executed must be enclosed in braces {} and is referred to as a statement block. To make your PHP code easier to read and understand, you should always indent the code in a statement block. If you want an if statement to execute a statement block when the condition is false, you must include an else statement. Using an if statement with an else statement allows you to execute one of two sections of code, depending on the outcome of testing the condition. If the condition is true, the statement block directly following the if statement is executed. If the condition is false, the statement block directly following the else statement is executed. Using an else statement ensures that a section of code is executed regardless of the outcome of testing the condition.

To test multiple conditions, you include elseif statements after the if statement. An elseif statement contains a condition that can be tested. If the condition specified in the if statement is false, PHP will test each elseif statement until a condition is true. PHP will then execute the block for the true elseif statement. If there are no true elseif statements, the else statement will be executed.
TYPE THIS: $myAge = 32; if ($myAge < 21) { print "Child: \$2.00"; } elseif ($myAge < 65) { print "Adult: \$5.00"; } else { print "Senior: \$3.00"; } RESULT:

The condition you want to test must be enclosed in parentheses (). Unlike most PHP statements, the if statement does not end with a semicolon. Ending an if statement with a semicolon is a common programming mistake and will generate an error when the PHP page is processed.

Adult: $5.00

USING THE IF STATEMENT

⁄ Type the code that creates the variables and assigns their values. 52

¤ Type if (). ‹ Between the parentheses,
type the condition you want to test.

› Type the code you want to execute if the condition you specified is true. Enclose the code in braces.

ˇ To use the else statement, type else.

Á Type the code you want
to execute if the condition you specified is false. Enclose the code in braces.

‡ Display the PHP page
in a Web browser.

I The Web browser displays the result of using the if statement.

53

PHP
The decrement operator (--) can be used in the re-initialization expression to decrease the value of the iterator by one each time the loop is processed. This allows you to create a for loop that counts backwards.
Example: for ($i = 5; $i >= 0; $i--) { print "$i<br>"; }

LANGUAGE BASICS
One or more expressions can be omitted from a for statement, though this may adversely affect the processing of the loop. For example, if a for statement does not include a conditional expression, PHP assumes the condition is always true and an infinite loop may be created. You should be careful not to create an infinite loop.
Example: for ($i = 1; ; $i++) { print "$i<br>"; }

2

USING THE FOR STATEMENT
rogrammers often need to execute the same block of code several times. The for statement allows you to create a loop that repeats the execution of code a specific number of times. For example, you may want to create five line breaks on a Web page. Instead of typing the code that creates a line break five times, you can create a loop that executes the code to create a line break and then repeats the loop until the value of a counter reaches 5.

P

beginning of each loop. If the condition is true, the loop is executed and a block of code you specify is processed. If the condition is false, the block of code is not executed and the loop is ended. The block of code is placed between braces {} and is known as the body of the loop. The third expression in a for statement is the re-initialization expression. This expression is used to modify the value of the iterator. Typically, the increment operator (++) is used in the re-initialization expression to increment the value of the iterator by one each time the loop is executed. The re-initialization expression should modify the iterator in a way that will eventually lead to the conditional expression being evaluated as false. Otherwise, the loop will be processed indefinitely.

A for statement consists of three expressions. The first expression is called the initialization expression and is used to specify the initial value of the variable that will be used to control the processing of the loop. This variable is referred to as the iterator and is often used as a counter in a loop. The second expression is known as the conditional expression. This expression allows you to specify a condition that evaluates the value of the iterator at the

When creating a re-initialization expression, you are not limited to using the increment and decrement operators to modify the value of the iterator by 1. An iterator can be modified by any increment, including floating point numbers. For example, an iterator can be initialized with a value of 0 and then increased in increments of 0.5 until a value of 5 is reached.
Example: for ($i = 0; $i < 5; $i = $i + 0.5) { print "$i<br>"; }

USING THE FOR STATEMENT

⁄ Type for (). ¤ Between the parentheses,
type the name of the variable you want to use as the iterator followed by =.

‹ Type the initial value
you want to assign to the iterator followed by a semicolon.

› Type the conditional expression you want to use to evaluate the value of the iterator followed by a semicolon.

ˇ Type the re-initialization
expression you want to use to modify the value of the iterator each time the loop is executed.

Á Type the code you
want to execute as long as the specified condition is true. Enclose the code in braces.

‡ Display the PHP page
in a Web browser.

I The Web browser displays the result of executing the loop.

54

55

PHP
A while loop may be used to count the number of characters in a string or the number of lines in a file.

LANGUAGE BASICS
You can place a loop within another loop to create a nested loop.
TYPE THIS: $loopCounter = 0; do { print "This is line number"; for ($x = 0; $x < 8; $x++) { print "."; } print "$loopCounter<br>"; $loopCounter++; } while ($loopCounter < 3);

2

USING THE WHILE STATEMENT

T

he while statement allows you to create a conditional loop that will execute a section of code as long as a specified condition is true. Conditions often test the value of a variable. For example, you may want to process a pay statement for each of the 100 employees in a company. Instead of typing the code that will process a pay statement 100 times, you can create a loop that will repeat the pay statement for each employee. The condition would check how many pay statements have been processed. After the 100th pay statement has been processed, the condition would be evaluated as false and the loop would end. The body of a while loop is enclosed in braces {} and contains the section of code to be executed, called the statement block. If the condition tests the value of a variable, the loop body will also contain code to alter the value of the variable. When the condition is true, the statement block is executed. When PHP reaches the end of the loop body, the condition is re-evaluated. If the condition is still true, the

code in the loop body is executed again. If the condition is false, the statement block is not executed and the loop ends. When creating a conditional loop, you must ensure that the condition being tested will be evaluated as false at some time. If the condition is always true, the code in the loop body will be executed indefinitely, creating an infinite loop. You should also keep in mind that there is typically a 30-second time limit for the processing of PHP code. You should thoroughly test your PHP code to prevent a PHP page from possibly timing out during processing, which could result in data loss. For information about the timeout settings for a PHP page, see page 219.

Example: $word = "dynamic"; $x = 0; while ($word[$x] != null) { $x++; } print "The word <b>$word</b> has $x characters.<br>";

A do..while statement can be used to test a condition after the body of a loop has been executed. This is useful if you have a section of code that you want to execute at least once, regardless of how the condition is evaluated.
TYPE THIS: $loopCounter = 0; do { print "This is line number "; print $loopCounter . "<br>"; $loopCounter++; } while ($loopCounter < 0);

RESULT:

This is line number........0 This is line number........1 This is line number........2

RESULT:

This is line number 0
USING THE WHILE STATEMENT
Using The WHILE Statement - Microsoft Internet Explorer

⁄ Type the code that creates a variable and assigns it a value. 56

¤ Type while ().

‹ Between the parentheses, type the condition you want to evaluate.

› Type the code you
want to execute as long as the condition you specified is true. Enclose the code in braces.

ˇ Within the braces, type the code that will alter the value of the variable each time the loop is executed.

Á Display the PHP page
in a Web browser.

I The Web browser displays the result of using the while statement.

57

PHP

LANGUAGE BASICS

2

USING THE SWITCH STATEMENT

T

he switch statement allows you to execute a section of code, depending on the value of an expression. When a switch statement is executed, the value of the expression is compared to a number of possible choices, which are specified using case statements. If the value of the expression matches a case statement, the section of code following the case statement is executed. For example, you can create a switch statement that displays a specific message, depending on information entered by a user. To use the switch statement, you must first specify the expression you want to use. For example, you can specify a variable whose value you want to check. After specifying the expression, you must create the case statements that contain the values the expression will be compared to. A case statement consists of the case keyword followed by a value and a colon (:). The value can be any scalar value, such as an integer or string, or an expression that evaluates to a scalar value.
USING THE SWITCH STATEMENT

The switch statement compares the value of the expression to each case statement in order, from top to bottom. To make your code more efficient, you should place the case statements that are most likely to match the expression first. You can use the break statement to prevent the code for the remaining case statements from being executed after a match has been made. The break statement should be the last statement in the section of code that follows each case statement. Although the last case statement does not require a break statement, some programmers include it to be consistent. This can help you avoid accidentally leaving out the break statement if you later add another case statement to the switch statement.

You do not need to include code for each case statement in a switch statement. You can execute the same code for several case statements by grouping the case statements together and including the code after the last statement in the group. This saves you from having to retype the same code for several case statements.
Example: switch ($item) { case "hat": case "shirt": case "pants": print "Clothing Category"; break; case "fruit": case "vegetables": print "Food Category"; break; }

You can include a default statement in a switch statement if you want to execute specific code when none of the case statements match the specified expression. The default statement is placed last in the switch statement structure.
Example: switch ($priority) { case 1: print "Urgent"; break; case 2: print "High Priority"; break; default: print "Low Priority"; break; }

Using the SWITCH Statement - Microsoft Internet Explorer

⁄ Type switch (). ¤ Between the
parentheses, type the expression you want the switch statement to use.

‹ Type a pair of braces to hold the case statements.

› Type case followed
by a value the expression may contain.

Á Type the code you
want to execute if the value in the case statement matches the expression you specified in step 2.

‡ Type break to prevent
the code for the remaining case statements from being executed once a match has been made.

° Repeat steps 4 to 7
for each value the expression may contain.

· Display the PHP page
in a Web browser.

I The Web browser displays the result of using the switch statement.

ˇ Type : to complete the case statement.

58

59

PHP

LANGUAGE BASICS
Creating a loop allows you to access all the elements in an array. You can use the count function to determine the total number of elements in the array and use the loop's counter variable as the index to access each element. the name of the array followed by the index number of the element you want to access enclosed in brackets, such as $days[1]. You can use an array element in a script as you would use a variable. The value of an element can be directly displayed to a Web browser using the print function or assigned to another variable that can then be processed further. An element can be changed or a new element can be added to an array without affecting the other elements in the array. For more information about changing or adding elements in an array, see page 62.
TYPE THIS: $vegetables = array ("broccoli", "carrot", "zucchini", "eggplant"); for ($x = 0; $x < count($vegetables); $x++) { print $vegetables[$x] . "<br>\n"; } RESULT:

2

CREATE AN ARRAY
n array is a variable that stores a set of related values. For example, an array could store the name of each day of the week. Using an array allows you to work with multiple values at the same time. Each value in an array is referred to as an element.

A

The first step in creating an array is to create a variable to store the array. You can then use the array keyword to assign a set of values, or elements, to the variable. The elements are enclosed in parentheses and separated by commas. String elements in an array must be enclosed in quotation marks. In PHP, it is possible to store values of different data types in a single array. You may even store other arrays in an array. PHP's array-handling capabilities make it more flexible and intuitive than most other programming languages. Each element in an array is uniquely identified by an index number, or key. PHP numbers the elements in array starting at zero (0). To access a specific element in an array, you enter

broccoli carrot zucchini eggplant

You can use the foreach statement to create a loop that allows you to work with each consecutive element in an array without having to specify each element's index. In the following example, each element in the $vegetables array is assigned to the $value variable.
TYPE THIS: $vegetables = array ("broccoli", "carrot", "zucchini", "eggplant"); foreach ($vegetables as $value) { print "The vegetable is: $value<br>\n"; } RESULT:

The The The The

vegetable vegetable vegetable vegetable

is: is: is: is:

broccoli carrot zucchini eggplant

CREATE AN ARRAY

⁄ Type a name for the array you want to create followed by = array ().

¤ Between the parentheses, type each element you want to add to the array separated by a comma.

I If the value for an element is a string, you must enclose the string in quotation marks.

‹ To access an array
element, type the name of the array followed by [].

ˇ Type the code that
uses the element in the array.

Á Display the PHP
page in a Web browser.

I The Web browser displays an element in the array.

› Between the brackets,
type the index of the element you want to access.

60

61

PHP
You can create an empty array and then later add elements to the array. This is useful when you want to filter array elements or dynamically add elements to an array using data obtained from a database or a file. To create an empty array, use the array keyword without placing any elements within the parentheses.
Example: $unfiltered = array ("apple", "orange", "not fruit", "grape", "banana", "not fruit", "not fruit", "cherry"); $filtered = array (); foreach ($unfiltered as $value) { if ($value != "not fruit") { $filtered[] = $value; } } foreach ($filtered as $value) { print "$value<br>"; }

LANGUAGE BASICS

2

WORK WITH ARRAYS

O

nce you have created an array, you can work with the elements in the array. For example, you can change or add elements in an array.

need to specify an index number. PHP will assign the new element an index number one greater than the current largest index number in the array. You may also explicitly specify the index number of a new element you add to an array. If you specify an index number that is more than one greater than the current largest index number, PHP will not create elements to fill the gap between the index numbers. Any new elements later added to the array will be placed after the new largest index number. If a new element is added to an array that does not yet exist, a new array will automatically be created. It is better programming practice, however, to first create an array before adding new elements to the array.

You can create an array with an index that starts with a number other than 0. The => operator is used to explicitly assign a starting index to the first element in the array. The next elements in the array will then be indexed accordingly in sequence.
TYPE THIS: $startWithTen = array (10 => "ten", "eleven", "twelve", "thirteen"); foreach ($startWithTen as $key => $value) { print "key: $key, value: $value<br>\n"; }

To change an element in an array, you must first specify the name of the array followed by a set of brackets. You must then specify the index number of the element you want to change. Keep in mind that PHP usually numbers the elements in an array starting at zero (0). PHP allows you to change the value of an element in an array by assigning the element a new value. When changing the value of an element, make sure you do not make unintended changes to the data, such as inserting text data into an array you want to contain only numbers. You use a similar method to add a new element to an existing array. When adding a new element, you do not

RESULT:

key: key: key: key:

10, 11, 12, 13,

value: value: value: value:

ten eleven twelve thirteen

WORK WITH ARRAYS

CHANGE AN ELEMENT

‹ Type = followed by
the value you want to assign to the element.

ADD AN ELEMENT

Á Type = followed by the
value you want to assign to the new element.

‡ To add an element with a
specific index number to an array, type the name of the array followed by [].

· Type = followed by the
value you want to assign to the element.

— Display the PHP page
in a Web browser.

⁄ To change an element in
an array, type the name of the array followed by [].

ˇ To add an element to
an array, type the name of the array followed by [].

I The Web browser displays the results of changing and adding elements in an array.

› Repeat steps 1 to 3
for each element you want to change.

¤ Between the brackets,
type the index number of the element you want to change.

° Between the brackets,
type the index number you want to assign to the new element.

‚ Type the code that
generates the results of your changes.

62

63

PHP

LANGUAGE BASICS
You can call a function from within another function. When calling other functions from within a function, you should be careful not to generate a loop that causes the functions to continuously call each other.
TYPE THIS: RESULT:

2

USING A FUNCTION
function, sometimes referred to as a subroutine, contains a block of code that performs a specific task, such as displaying a message. Using functions makes it easy to re-use sections of code in a PHP page. For example, you may have a function that displays a warning message when a client enters invalid data into a form. Instead of retyping the section of code that displays the message for each field in the form, you can simply re-use the function.

A

capitalize the first letter of each word to make the name easy to read, such as AddTotalCost. Function names are case-insensitive, but you should be consistent in naming functions to help make your scripts easier for other people to understand. The block of code used in a function is enclosed in braces {}. The block of code will not be executed until the function is called in the script. To call a function, you type the name of the function followed by a set of parentheses where you want to execute the code. PHP has many useful built-in functions, such as the print function. To avoid unnecessary work, you should check whether there is an existing function that suits your needs before defining your own function.

function WelcomeMessage() { print "Welcome to my Web page!<br>"; } function DisplayIntroduction() { WelcomeMessage(); print "My name is Martine.<br>"; } DisplayIntroduction();

Welcome to my Web page! My name is Martine.

Functions also allow you to group lines of code into smaller, more manageable sections. This makes it easier to understand and troubleshoot the code. A function is created using the function keyword followed by the name of the function and a set of parentheses. A function name must start with a letter or an underscore (_) character. The name should identify the purpose of the function or describe the action the function performs. It is common to have a function name begin with a capital letter. If the name consists of multiple words, you can

When creating a function, you should keep in mind that any variables created within the function can be accessed only within that function. The function's variables will not be accessible to other functions or other sections of code in the PHP page.
TYPE THIS: function SetPageTitle() { $pageTitle = "Martine's Home Page"; } function DisplayWelcome() { print "Welcome to $pageTitle<br>"; } DisplayWelcome(); RESULT:

Welcome to

USING A FUNCTION

CREATE A FUNCTION

⁄ To create a function,
type function.

¤ Type a name for the function followed by ().

‹ Type the code you want to execute when the function is called. Enclose the code in braces.

CALL A FUNCTION

ˇ Display the PHP
page in a Web browser.

› To call a function,
type the function name followed by ().

I The Web browser displays the result of the function.

64

65

PHP
A function can have more than one return statement. This is commonly found in functions that use conditional statements. Although a function can have more than one return statement, only one return statement will be executed. When a return statement is processed, the execution of the function is terminated.
TYPE THIS: function CheckAge() { $age = 19; if ($age >= 18) { return "You may vote.<br>"; } else { return "You may not vote.<br>"; } } print CheckAge();

LANGUAGE BASICS

2

RETURN A VALUE FROM A FUNCTION
lthough a function may simply display a value using the print function, it may be more useful to have the function return a value to the code that calls the function. A value returned from a function may be the result of a calculation or procedure or may indicate whether a process was successfully completed. For a function to return a value, you must include a return statement. A return statement consists of the return keyword followed by the value you want the function to return and is usually placed at the end of a function, after the code that performs an operation and generates or calculates the value to be returned. The execution of a function will terminate once the return statement is processed. A function can return a value of any single data type, such as strings, integers, floating-point numbers and boolean values. A function typically returns only one value. If you

A

need to have a function return multiple values, you should first place the values in an array and then return the array using the return keyword. When a function that returns a value is called, the value can be directly displayed to a Web browser using the print function. It may be more useful, however, to assign the value returned from a function to a variable that can then be processed further by the PHP script. The return keyword may also be used to simply denote the end of a function. This is useful for functions that will not return a value. In such cases, the return keyword is used alone and is not followed by any value or variable.

In PHP, most built-in functions return a boolean value. This is useful for helping to prevent your PHP scripts from crashing or generating errors. For example, the is_numeric function will return a value of true if the argument passed to the function is a number or a numeric string. Otherwise, the function returns a value of false.
Example: $x = 8; $y = "Hello"; if (is_numeric($y) == TRUE) { print "Answer: " . $x / $y . ".<br>"; } else { print "Cannot perform division.<br>"; }

RESULT:

You may vote.
RETURN A VALUE FROM A FUNCTION

⁄ Create the function you want to return a value from.

¤ In the body of the function, type return followed by the information you want the function to return.

I In this example, we return a variable that contains the result of a calculation.

‹ Type the code that
calls the function and uses the value returned from the function.

› Display the PHP
page in a Web browser.

I The Web browser displays the result of returning a value from a function.

66

67

PHP

LANGUAGE BASICS
You can specify a default value for an argument that will be passed to a function. When creating the variables that will store arguments you pass, you can assign a value you want to use as a default argument to a variable. A variable that has a default value assigned must be last in the list of variables in the function statement. When you pass arguments to the function, you do not need to specify an argument for the variable that has a default value assigned. The variable will automatically use the default argument. You will need to pass an argument to the variable only if you want to use a different argument.
TYPE THIS: function MyMessage ($message, $size = 3) { print "<font size=\"$size\">$message</font><br>"; } MyMessage ("Welcome to My Web Site"); MyMessage ("Welcome to My Web Site", 5);

2

PASS ARGUMENTS TO A FUNCTION
assing arguments to a function you have created can make the function more powerful by allowing you to use one function throughout a script to process different data.

P

and then send the result back to the code used to call the function. The result can be used in many ways in a PHP page. For example, you can assign the result to another variable or display the result on the screen. You can pass one or more arguments to a function, but the number of arguments you pass must match the number of variables you created to store the arguments. An argument you pass can be a variable or any alphanumeric value, but the argument must be appropriate for the purpose of the function. For example, you cannot pass a text value to a function if the value will be used in a mathematical calculation. Text values passed to a function must be enclosed in quotation marks.

In the function statement, you define one or more variables between the parentheses that follow the function name. Each variable represents a value, or argument, you will pass to the function. Each time you call the function in the PHP page, you will specify the arguments you want to pass to the function. You can use the variables you create in the function statement within the body of the function. The variables will exist only within the function and will not be available once the function has finished processing. This means that you will not be able to retrieve the value of a variable in a function from outside the function. The function can use the values that are passed to it to perform a calculation

RESULT:

Welcome to My Web Site

Welcome to My Web Site

PASS ARGUMENTS TO A FUNCTION

⁄ Create and call the function you want to pass arguments to.

¤ Between the parentheses in the code that creates the function, type the names of the variables you want to store the arguments that will be passed to the function. Separate each variable name with a comma.

‹ Between the parentheses
in the code that calls the function, type the arguments you want to pass to the function. Separate each argument with a comma.

I The number of arguments you pass must match the number of variables you created in step 2.

› Display the PHP page
in a Web browser.

I The Web browser displays the result of passing arguments to the function.

68

69

PHP

LANGUAGE BASICS

2

PASS ARGUMENTS TO A FUNCTION BY REFERENCE
y default, when an argument you pass to a function is a variable created outside the function, only the value of the variable is passed to the function. Any changes the function makes to the value do not affect the variable in the PHP page. If you want to use a function to change the value of a variable in the PHP page, you must pass the variable to the function by reference. Passing an argument by reference passes an entire variable to the function, rather than simply passing the value of the variable.

B

To pass an argument to a function by reference, you preface the argument with an ampersand (&) in the code that calls the function. An argument you pass by reference must be a variable. You can pass one or more arguments to a function by reference, but the number of arguments you pass must match the number of variables you created to store the arguments. When the function is called, the arguments you pass by reference are assigned to the variables you created in the function statement. When the variables are modified within the function, the values of the arguments they contain are also modified. The results of the function are then sent back to the code used to call the function.

If you want an argument passed to a function to always be passed by reference, you can type an ampersand (&) in front of the variable you create to store the argument in the function statement. This saves you from having to type an ampersand each time you pass an argument to the function.
TYPE THIS: function TimesThree(&$number) { $number *= 3; } $myNumber = 5; print "The original number is: $myNumber<br>"; TimesThree($myNumber); print "The new number is: $myNumber<br>";

Unlike variables, whose scope does not automatically extend to functions, constants you create in a PHP page are automatically accessible to the functions you create. This means that you do not need to pass a constant to a function before the constant can be used in the function. Constants are normally created at the beginning of a script. It is considered good programming practice to create all of your functions near the beginning of a script. This can make your code easier to understand and maintain. You can then call the functions wherever you want to execute the code in the PHP page.

Before you can pass arguments to a function, you must create one or more variables between the parentheses that follow the function name in the function statement. Each variable represents an argument you will pass to the function. The variables can then be used in the body of the function, allowing the function to work with the arguments that are passed to it. The variables you create in the function statement exist only within the function and are not available outside the function.
PASS ARGUMENTS TO A FUNCTION BY REFERENCE

RESULT:

The original number is: 5 The new number is: 15

⁄ Create and call the function you want to pass arguments to by reference.

¤ Between the parentheses in the code that creates the function, type the name of the variable you want to store the argument that will be passed to the function.

I If multiple arguments will be passed to the function, type the names of all the variables you want to store the arguments. Separate each variable name with a comma.

‹ Between the parentheses
in the code that calls the function, type an ampersand followed by the name of a variable you want to pass to the function.

70

I You can repeat step 3 for each argument you want to pass by reference, separating each argument with a comma. The number of arguments you pass must match the number of variables you created in step 2.

› Display the PHP page
in a Web browser.

I The Web browser displays the result of passing an argument to the function by reference.

71

PHP

LANGUAGE BASICS
You can have PHP retain the value of a local variable after a function has finished executing and use the value the next time the function is called. To retain the value of a local variable, you use the static keyword when creating the variable. The initial value you assign to the variable is used the first time the function is called. The next time the function is called, PHP will use the value assigned to the variable the last time the function was executed. The value of a static local variable is retained only for the duration of the script. Once the script is finished processing, the value ceases to exist.
TYPE THIS: function Multiply($number) { static $container = 1; $container *= $number; return $container; } $myNumber = Multiply(2); print "1 times 2 is: $myNumber<br>\n"; $myNumber = Multiply(4); print "...times 4 is: $myNumber<br>\n"; $myNumber = Multiply(3); print "...times 3 is: $myNumber<br>\n"; RESULT:

2

UNDERSTANDING VARIABLE SCOPE

T

he scope of a variable determines which parts of a script can access the variable and use its value.

If you create a variable in the body of a function, the value of the variable will only be available in the function. Variables created in a function are referred to as local variables. By default, a function can access only local variables. This is an important safety feature in PHP because it prevents variables created outside a function from interfering with variables of the same name created within the function. To allow a function to use a variable that was created outside of the function, you must declare the variable as global within the function. To declare a variable as global, you use the keyword global followed by the name of the variable. The global declaration must be made before

the variable can be used. Declaring a variable as global within a function does not create a new variable, but simply allows the function to access and use the value of the variable. Any changes made to a global variable inside a function also affect the value of the variable outside of the function. Variables have a limited lifetime in PHP. The lifetime of a variable refers to the length of time the value of the variable exists in memory. A variable created in a PHP script exists only for the duration of the script. When the script is finished processing, the value of the variable ceases to exist. A variable created in a function exists only while the function is being executed. The value of a local variable ceases to exist when the function terminates.

1 times 2 is: 2 ...times 4 is: 8 ...times 3 is: 24

UNDERSTANDING VARIABLE SCOPE

⁄ Type the code that creates a variable and assigns it a value. 72

¤ Type the code that creates a function.

‹ To create a local variable, type the code that creates a variable and assigns it a value in the body of the function.

› To declare a variable
as global in the body of the function, type global followed by the name of the variable.

ˇ Type the code that
uses the local variable and the global variable.

Á Type the code that calls the function.

‡ Display the PHP
page in a Web browser.

I The Web browser displays the result of using a local variable and a global variable.

73

PHP
You can access functions dynamically, just as you would access dynamic variables. To call a function dynamically, you first assign the function name to a string variable. When you want to call the function, you can use the variable name followed by parentheses instead of the function name.
TYPE THIS: function FontFour($message) { print "<font size=\"4\">$message</font>"; } function FontFive($message) { print "<font size=\"5\">$message</font>"; } function FontSix($message) { print "<font size=\"6\">$message</font>"; } $size = "Four"; if ($size != "") { $functionName = "Font" . $size; } else { $functionName = "FontSix"; } $functionName("Hello there! How are you?");

LANGUAGE BASICS

2

USING DYNAMIC VARIABLES
HP allows you to use dynamic variables, which are also referred to as variable variables, in your scripts. A dynamic variable is a variable whose name is stored in another variable. A variable consists of two parts––the variable operator ($) and the name of the variable. A regular variable uses a literal string as the name of the variable. However, you can create a dynamic variable by using the name of an existing string variable as the name of the dynamic variable. Dynamic variables are especially useful for accessing the values of a series of variables that you have previously created dynamically in your script, such as field names in a form. If you do not know the exact number of variables in the form, but you know that the names of the variables all begin with "Field_", you can create a dynamic variable that will access all the variables named "Field_" in the form.

P

You first create a string variable that has the same name as the dynamic variable you want to use. The string variable should contain the name of the variable you want to access. To create the dynamic variable, you type the variable operator ($), followed by the string variable you created. The result is a variable that has two variable operators ($), such as $$varName. A dynamic variable acts as the equivalent of the original variable that stores the name of the variable you want to access. You can work with the dynamic variable in the same way you would work with a regular variable.

RESULT:

Hello there! How are you?

USING DYNAMIC VARIABLES

⁄ To create a string variable that will contain the name of the variable you want to access, type $ followed by a name for the variable. Then type =. 74

¤ Type the value or
expression the variable will store, including the name of the variable you want to access.

‹ To create a dynamic variable, type $ followed by the string variable you created in step 1.

› Type the code that
uses the dynamic variable.

I In this example, the dynamic variable is used in a loop that accesses a series of string variables and displays their values.

ˇ Display the PHP page
in a Web browser.

I The Web browser displays the result of using a dynamic variable.

I String values must be enclosed in quotation marks.

75

PHP
Type casting is another way to explicitly set the data type of a variable. You can cast a variable to the integer, double, string, boolean, array or object data type. You must first
TYPE THIS: $uncasted = 1.2345; $casted = (integer)$uncasted; print "Data type of the uncasted variable is: " . gettype($uncasted); print "<br>"; print "Data type of the casted variable is: " . gettype($casted);

LANGUAGE BASICS
create the variable you want to cast. You then create a second variable to store the data type you want to use, enclosed in parentheses, and the first variable.

2

WORK WITH DATA TYPES OF VARIABLES
hen creating variables in PHP, you do not have to explicitly declare the type of variable you want to create. The data type of a variable is determined by the value assigned to the variable. For example, if you assign an integer value to the $number variable, then $number will use the integer data type. This distinguishes PHP from other languages, such as C++ and Java, which require variables to have assigned data types. If you are working with different types of data, PHP will automatically perform the required data type conversions. For example, if you add the string "3" to the integer 2, PHP will convert the string to an integer and return the integer 5 as the result. When PHP automatically converts a value to a new data type, it affects only how the value is evaluated. The value of the variable is not changed. The gettype function allows you to determine the current data type of a variable. The gettype function takes the name of the variable whose data type you want to determine as its argument.

W

You can use the settype function to force PHP to always evaluate a variable using a specific data type. The settype function takes two arguments––the name of the variable whose data type you want to set and the data type you want the variable to use. The data types you can specify include integer, double, string, boolean, array and object. The double data type refers to doubleprecision floating-point numbers. When you use the settype function, PHP will attempt to convert the value of the variable to the specified type. If the conversion is successful, the settype function will return a value of true. A value of false will be returned if the conversion was not successful. When a value is converted to a new data type, data may be lost. For example, if you convert a floating-point number to an integer, the fractional part of the number will be lost.

RESULT:

Data type of the uncasted variable is: double Data type of the casted variable is: integer When you use a string in a numeric calculation, PHP examines the beginning of the string. If the string begins with valid numeric data, PHP will use the numeric data and truncate the rest
TYPE THIS: $a = "100 US Dollars"; print "\$a = " . ($a + 0) . "<br>"; $b = "US Dollars: 100"; print "\$b = " . ($b + 0);

of the string. If the string begins with anything other than numeric data, the value of the string will be zero (0).
RESULT:

$a = 100 $b = 0

WORK WITH DATA TYPES OF VARIABLES

⁄ Type the code that creates a variable and assigns it a value. ¤ To determine the data type of a variable, type gettype(). 76

‹ Between the
parentheses, type the name of the variable whose data type you want to determine.

ˇ To set the data type of a variable, type settype(). Á Between the parentheses, type the name of the variable whose data type you want to set followed by a comma.

‡ Type the data type
you want to set for the variable, enclosed in quotation marks.

° Type the code that uses
the settype function.

· Display the PHP page
in a Web browser.

I The Web browser displays the results of working with the data types of variables.

› Type the code that uses
the gettype function.

77

PHP

LANGUAGE BASICS

2

GET INFORMATION ABOUT A VARIABLE
here are a number of functions you may use to test whether a variable stores data of a certain type. Testing the value of data stored in a variable is useful before using a variable in a calculation. If you attempt a calculation with the wrong type of variable, an error may occur. The is_int, is_integer, and is_long functions are used to verify if a variable stores an integer. You use the is_float, is_real and is_double functions to check whether a variable stores a floating-point number. The is_numeric function is used to test if a variable stores a number or a numeric string. The is_bool function is used to determine if a variable is a boolean. To check if a variable stores a string, you use the is_string function. The is_array function is used to test if a variable stores an array, and the is_object
GET INFORMATION ABOUT A VARIABLE

T

function is used to test whether a variable is an object. You use the is_resource function to check if a variable is an integer that represents a system resource, such as an open file or an open database connection. The functions that test the type of a variable return a value of true if the value stored in the variable is of the indicated type, otherwise, the functions return a value of false. There are other useful functions you may use to get information about a variable, such as whether a variable has been assigned a value or whether a variable holds a zero (0) value. The isset function returns a value of true if a value has been assigned to a variable. The empty function returns a value of false if a variable contains a non-zero or non-empty value.

You may use the print_r function to view information about a variable you specify in a form that can be easily read. This function is especially useful for viewing the contents of arrays and objects. When using the print_r function, you may want to use the <pre> tag to format the result.
TYPE THIS: $info = array ("Tom", 24, 65.5); print "<pre>"; print_r($info); print "</pre>";

The var_dump function is used to display information about a variable in an easy-to-read format and shows the data types of all the values being displayed. You may want to use the <pre> tag to format the result of the var_dump function.
TYPE THIS: $info = array ("Tom", 24, 65.5); print "<pre>"; var_dump($info); print "</pre>";

RESULT: Array ( [0] => Tom [1] => 24 [2] => 65.5 )

RESULT: array(3) { [0]=> string(3) "Tom" [1]=> int(24) [2]=> float(65.5) }

⁄ Type the code that creates variables and assigns their values. ¤ To check if a variable stores a value of a specific type, type the function you want to use followed by (). 78

‹ Between the parentheses, type the name of the variable you want to check. › Type the code that uses the function.

ˇ To check if a value has been assigned to a variable, type isset(). Á Between the parentheses, type the name of the variable you want to check.

‡ Type the code that
uses the isset function.

° To check if a variable
stores an empty or 0 value, type empty().

‚ Type the code that uses the empty function.

— Display the PHP page
in a Web browser.

· Between the parentheses,
type the name of the variable you want to check.

I The Web browser displays the results of retrieving information about the variables.

79

PHP

LANGUAGE BASICS

2

ACCESS SYSTEM CONSTANTS
HP comes with several built-in system constants that you can use in your scripts. A constant is a name that represents a value that does not change. Because PHP sets the value of a system constant, these constants do not have to be declared and can be used in every script you create. You can also create your own constants. This allows you to set the value of the constant. For information about defining and using constants, see page 44. System constants are usually used to store information about the environment in which a PHP script is running. For example, the PHP_VERSION constant stores the version of PHP being used on the computer and the _ _FILE_ _ constant stores the filename of the script being processed. To access the value of a system constant in a PHP page, you specify the name of the constant in the PHP code. Unlike variables, constants do not start with a dollar symbol,
ACCESS SYSTEM CONSTANTS

Common PHP System Constants
CONSTANT: DESCRIPTION:

P

so PHP cannot determine when a constant is being used in a string. To ensure that a constant is evaluated correctly in a string, you must separate the constant from the rest of the string. You should use all uppercase letters when specifying the name of a system constant. The constants TRUE and FALSE, however, are also commonly referenced using all lowercase letters. TRUE and FALSE are the most frequently used system constants. You can test the values of the TRUE or FALSE system constant by assigning the constant to a variable and using the variable in an if statement. You cannot modify the value of a PHP system constant. You also cannot use the name of a system constant as the name or value of a constant you create. If you attempt to do either of these tasks in your script, the script will generate an error.

_ _FILE_ _ _ _LINE_ _ PHP_VERSION PHP_OS TRUE FALSE E_ERROR E_WARNING E_PARSE E_NOTICE E_ALL NULL

Returns the filename of the script being processed. Returns the number of the line being processed in the script. Returns the version number of PHP being used. Returns the name of the operating system running PHP. Stores a value of true. Stores a value of false. Indicates a fatal error that is not related to parsing. Indicates that an error has occurred, but PHP will continue processing the script. Indicates a fatal parsing error caused by invalid syntax in the script. Indicates that an error may have occurred, but PHP will continue processing the script. Represents all the E_* constants. If used with the error_reporting function, all problems noticed by PHP will be reported. Represents no value.

⁄ To access the value of a system constant, type the name of the constant.

¤ Type the code that
uses the value of the constant.

‹ Repeat steps 1 and 2 for each system constant you want to access.

› To test the value of a
system constant, type the code that assigns the value of the constant to a variable.

ˇ Type the code that
uses the value of the constant.

Á Display the PHP page
in a Web browser.

I The Web browser displays the result of accessing the values of system constants.

80

81

PHP

LANGUAGE BASICS

2

INCLUDE A FILE
he require and include statements allow you to use one file in several different PHP pages. This can save you time when you need to include the same information in multiple pages. For example, if you have a copyright notice you want to display on all your PHP pages, you can create a file that contains the copyright notice and then use a require or include statement to include the information on all your pages. If you change the code in the file, all the PHP pages that include the file will be updated. You must first create the file you want to include. The file can contain plain text or HTML code, such as a table, header or footer. The file can also contain PHP code enclosed within the PHP delimiters (<?php and ?>), such as variables or functions. You can save the file with the .inc extension on the Web server. To include the file in a PHP page, you must add a require or include statement in the PHP page. The filename specified in the require or include statement must be

T

enclosed in quotation marks. The contents of the required or included file can then be used in your script. The require and include statements differ mainly in the way PHP processes each statement. When a script is processed, PHP replaces instances of the require statement with the contents of the file to be included, even if the line containing the require statement is never executed. Unlike the require statement, the include statement is processed only when the statement is executed and returns a boolean value of true or false, depending on whether the statement is executed correctly. If you want to include a file based on a condition being true, you should use an include statement instead of a require statement.

Using the require and include statements allows you to break code into manageable sections and then include the code in PHP pages as needed. For example, you can organize constants and functions you create into include files that you can then insert into your PHP pages. You can also nest include files within other include files. This is especially useful for complex PHP pages that contain long sections of code.

Some files should be included only once when a script is processed. For example, if a file with a function declaration has been included multiple times, an error will occur after the require or include statement is processed the first time, because a function can be declared only once in a script. To ensure that a file is included only once, you can use the require_once or include_once statement when you include the file in a PHP page. After the file has been included once, PHP will ignore any new statements that include the file.
Example: <?php require_once("hello.inc"); ?>

INCLUDE A FILE

CREATE A FILE TO INCLUDE

¤ Save the file on the
Web server.

INCLUDE A FILE

¤ Type include() or
require() where you

‹ Between the parentheses,
type the name of the file you want to include, enclosed in quotation marks.

› Display the PHP page
in a Web browser.

⁄ In a text editor, create a file you want to include in several PHP pages.

⁄ Display the code for the PHP page in which you want to include a file.

want to include a file.

I The Web browser displays the result of including a file.

82

83

PHP

WORK WITH ARRAYS

3

CREATE AN ASSOCIATIVE ARRAY
ou can create an associative array, which allows you to use string values instead of index numbers to identify the elements in the array. These string values are often referred to as keys.

Y

meaningful keys. Arrays containing many elements with very long keys require more memory, which makes the script less efficient. To access an element in an associative array, you specify the name of the array followed by the key enclosed in brackets, such as $user[name]. If the key contains spaces, it must be enclosed in quotation marks, such as $user["last name"]. You should not access an element with a key that is enclosed in quotation marks within another string, such as print "Welcome $user["first name"]", since an error will be generated. In such cases, it is better to access the element outside the string and use the concatenation operator (.) to combine the strings, such as print "Welcome " . $user["first name"].

You can use the foreach statement to work with each key-value pair in an associative array. You specify another variable to hold the value of each key after the as keyword in the foreach statement. This variable is followed by the => operator and the variable that will hold the value of each element.
TYPE THIS: $user = array ("name" => "Tom", "age" => 24, "gender" => "male"); foreach ($user as $key => $value) { print "$key: $value<br>"; }

To change the value of an element in an associative array, you specify the name of the array followed by the key of the element you want to change. You can then use the assignment operator (=) to assign a new value.
Example: $user = array ("name" => "Tom", "age" => 24, "gender" => "male"); $user[age] = 29;

Creating an associative array is similar to creating a simple array. You create a variable to store the array and then use the array keyword to assign the elements. When assigning an element to an associative array, however, you must first type the key. The key is enclosed in quotation marks and should describe its associated value in the array. The key is followed by the => operator and the value of the element. Each key-value pair in an associative array is separated by a comma. It is good programming practice to avoid using spaces and non-alphanumeric characters, such as ? and &, in the keys of an associative array. You should also try to use short but

RESULT:

You can later add an element to an associative array. To do so, you specify the name of the array followed by the key of the new element. You can then assign the new value.
Example: $user[status] = "single";

name: Tom age: 24 gender: male

CREATE AN ASSOCIATIVE ARRAY

⁄ Type a name for the associative array you want to create followed by = array ().

¤ To add an element to the
array, type a key followed by => and the value you want to assign to the element.

‹ Repeat step 2 for each element you want to add to the associative array. Separate each key-value pair with a comma. › To access an element in the associative array, type the name of the array followed by [].

ˇ Between the brackets, type the key of the element you want to access.

Á Type the code that
uses the element in the associative array.

‡ Repeat steps 4 to 6 for each element you want to access.

° Display the PHP page
in a Web browser.

I The Web browser displays the result of accessing elements in an associative array.

84

I The key and any string values must be enclosed in quotation marks.

85

PHP

WORK WITH ARRAYS
You can neatly display the elements of a multidimensional array in a table created using HTML. To access all the elements in the multidimensional array, you may use nested foreach loops. The first foreach loop will iterate through each array in the multidimensional array, while the other foreach loop will iterate through the elements in each array.
TYPE THIS: $users = array ( array ("name" => "Tom", "age" => 24, "gender" => "male"), array ("name" => "Martine", "age" => 19, "gender" => "female"), array ("name" => "Jason", "age" => 40, "gender" => "male") ); print "<table border=\"1\">\n"; print "<tr>\n"; print "<th>#</th>\n"; print "<th>Name</th>\n"; print "<th>Age</th>\n"; print "<th>Gender</th>\n"; print "</tr>\n"; foreach ($users as $number => $user) { print "<tr><td>$number</td>"; foreach ($user as $value) { print "<td>$value</td>"; } print "</tr>"; } print "</table>"; RESULT:

3

CREATE A MULTIDIMENSIONAL ARRAY
multidimensional array is useful for organizing data in a grid or a table format. For example, you may use a multidimensional array to store data about different users. You create a multidimensional array by adding one or more arrays as elements of another array.

A

When creating a multidimensional array, you should make the array symmetrical by ensuring that each array in the multidimensional array has the same number of elements. You can use simple arrays, associative arrays or both types as elements of a multidimensional array. To access an element in a multidimensional array, you need to specify the name of the array followed by a set of brackets for each dimension of the array. For example, accessing an element in a two-dimensional array will require two sets of brackets. You then specify the indexes of the element you want to access in the multidimensional array within the brackets. The index of the array you want to access is specified in
CREATE A MULTIDIMENSIONAL ARRAY

the first set of brackets. The index of the element within the array is specified in the second set of brackets, and so on. Keep in mind that PHP begins numbering arrays and elements at zero (0). For example, to access the third element in the second array of a two-dimensional array, you would type $values[1][2]. Accessing an element of a multidimensional array within a string, such as print "Name: $values[2][0]", may not give the correct result. To avoid problems, you should use braces {} when accessing an element of a multidimensional array within a string, such as print "Name: {$values[2][0]}". You may want to access the element outside the string and use the concatenation operator (.) to combine the strings instead, such as print "Name: " . $values[2][0].

⁄ Type a name for the multidimensional array followed by = array (). ¤ To assign an array as an element of a multidimensional array, type array followed by the values or key-value pairs for the array enclosed in parentheses. 86

‹ Repeat step 2 for each
array you want to assign to the multidimensional array. Separate each array with a comma. Note: In this example, a two-dimensional array is created.

› To access an element in the multidimensional array, type the name of the array followed by a set of brackets for each dimension in the array. ˇ Between the first set of brackets, type the index of the array you want to access.

Á Between the second set of brackets, type the index or key of the element you want to access.
I If necessary, specify additional indexes or keys within brackets.

‡ Type the code that
uses the element in the multidimensional array.

° Repeat steps 4 to 7
for each element you want to access.

· Display the PHP page
in a Web browser.

I The Web browser displays the results of accessing elements in a multidimensional array.

87

PHP

WORK WITH ARRAYS
You can create a function that advances the array pointer a specified number of times. The array and the number of advancements are passed to the function as arguments, with the array being passed by reference. In the function, a loop is used with the next function to advance the pointer. You can also create a function that uses the prev function to set the pointer back a specified number of times.
Example: function AdvancePointer(&$array, $number) { for ($counter = 0; $counter < $number; $counter++) { next($array); } } function MoveBackPointer(&$array, $number) { for ($counter = 0; $counter < $number; $counter++) { prev($array); } } $fruits = array ("apple", "avocado", "banana", "grapefruit", "melon"); AdvancePointer($fruits, 3); print "Key: " . key($fruits) . ", Value: " . current($fruits) . "<br>"; MoveBackPointer($fruits, 2); print "Key: " . key($fruits) . ", Value: " . current($fruits) . "<br>";

3

MOVE THROUGH ARRAY ELEMENTS
ou may access the elements in an array by navigating through the array using an internal array pointer, which is used to indicate which element in the array is currently selected. This is useful when accessing array elements that have non-sequential indexes or keys. When an array is created, the pointer is set to the first element of the array. You can then move the pointer forward or back to an element you want to access.

Y

Once you have set the pointer to the element you want to work with, you can use the key and current functions to access the element. These functions also take the name of the array as an argument. The key function returns the key, or index, of the current element, while the current function returns the value of the current element. If the internal array pointer is advanced beyond the last element in the array or is moved back beyond the first element, the position of the pointer will be lost. You will not be able to recover the pointer using the next or prev functions. To restore the pointer, you must use the reset or end function.

The internal array pointer is moved using the next, prev, end and reset functions. The next function is used to advance the pointer to the next element in an array. The prev function sets the pointer back to the previous element. The end function sets the pointer to the last element in an array, while the reset function sets the pointer back to the first element in the array. The next, prev, end and reset functions take the array you want to move through as an argument and return the value of the element to which the pointer is set.
MOVE THROUGH ARRAY ELEMENTS

⁄ Type the code that creates an array.

¤ To move through the
elements in the array, type the name of the function you want to use (next, prev, end or reset) followed by the name of the array enclosed in parentheses.

‹ To access the index of the current element, type key followed by the name of the array enclosed in parentheses. › To access the value of the current element, type current followed by the name of the array enclosed in parentheses.

ˇ Type the code that
uses the index and value of the current element.

Á Repeat steps 2 to 5
for each element you want to move to and access in the array.

‡ Display the PHP page
in a Web browser.

I The Web browser displays the result of moving through the array elements.

88

89

PHP

WORK WITH ARRAYS

3

ADD AND REMOVE ELEMENTS IN AN ARRAY

P

HP provides several functions that allow you to modify an array by adding and removing elements in the array.

To add an element to the beginning of an array, use the array_unshift function. Use the array_push function to add an element to the end of an array. When using the array_unshift and array_push functions, you must specify the name of the array you want to modify followed by the value for the element you want to add. In addition to individual elements, the array_unshift and array_push functions also accept lists of values. This allows you to add multiple elements to the beginning or end of an array. To add more than one element, you type the value for each element, separating each value with a comma. The array_unshift and array_push functions will return the number of elements in the modified array.

To remove an element from the beginning of an array, use the array_shift function. The array_pop function allows you to remove an element from the end of an array. You can remove only one element from an array at a time using the array_shift or array_pop function. These functions will return the value of the removed element. When you use the array_unshift or array_shift function to add or remove an element from the beginning of an array, the other elements will shift to accommodate the new element. The keys of numerically indexed elements in the array will be re-indexed starting from zero (0). Using the array_push or array_pop functions to add or remove an element from the end of an array will not affect the indexing of the other elements.

When working with arrays in PHP, it is important to remember that the position of an element in an array does not necessarily correspond to the index number of the element. The positions of array elements are determined by the order in which the elements are assigned to the array, especially in cases where the indexes of the elements are set explicitly. For example, using the array_pop function will remove the element that was set last in the array, not the element with the highest index number.
Example: $fruits = array(); $fruits[3] = "apple"; $fruits[2] = "grape"; $fruits[1] = "melon"; $fruits[0] = "orange"; array_pop($fruits); foreach($fruits as $value) { print "$value "; } Result:

You can use the assignment operator (=) to add elements to the end of an array instead of using the array_push function. This is useful when you want to add only a single element to the end of an array.
Example: $fruits = array("apple", "grape", "melon"); $fruits[] = "orange"; foreach($fruits as $value) { print "$value "; } Result:

apple grape melon orange

apple grape melon
ADD AND REMOVE ELEMENTS IN AN ARRAY

ADD AN ELEMENT

¤ To add an element to
the beginning of the array, type array_unshift().

⁄ Type the code that creates an array.

I To add an element to
the end of the array, type array_push().

‹ Between the parentheses, type the name of the array to which you want to add an element followed by a comma. › Type the value for the element you want to add to the array.

I String values must be enclosed in quotation marks.

REMOVE AN ELEMENT

‡ Between the parentheses,
type the name of the array from which you want to remove an element.

· Display the PHP page
in a Web browser.

Á To remove the last
element in the array, type array_pop().

ˇ Type the code that
uses the array.

I The Web browser displays the results of adding and removing elements in an array.

90

I To remove the first element in the array, type array_shift().

° Type the code that uses
the array.

91

PHP
You can use a negative offset number to specify the position of the first element you want to replace. When a negative number is used, the array_splice function finds the position of the elements from the end of the array, starting at 1.
TYPE THIS:

WORK WITH ARRAYS

3

REPLACE ELEMENTS IN AN ARRAY

T

he array_splice function allows you to replace existing elements in an array with new elements.

To use the array_splice function, you must specify the name of the array you want to change and the offset number of the first element you want to replace. The offset number corresponds to the position of the element in the array, but is not necessarily the index number of the element. The offset number will be the same as the index number of the element only if the array is indexed in consecutive order starting from zero (0). You should also specify a length parameter to indicate the number of elements you want to replace in the array. You can replace one or more elements. If you do not specify a length parameter, PHP will replace the element represented by the offset number, followed by each element to the end of the array.
REPLACE ELEMENTS IN AN ARRAY

You can then indicate the new elements you want to assign to the array. The array_splice function allows you to replace elements in an array with an array of elements or a single element. If new elements are not specified, the elements selected for replacement in the array will simply be removed. The array_splice function can also be used to add new elements to the end of an array. To add elements to the end of an array, specify an offset number that is greater than the highest index number in the array and use a length parameter of zero (0). When you use the array_splice function to replace or add elements in an array, the keys of numerically indexed elements in the array will be re-indexed starting from zero (0). When the array_splice function is executed, an array containing the replaced array elements is returned.

RESULT:

$fruits = array("apple", "avocado", "banana", "grapefruit", "melon"); array_splice($fruits, -2, 2, "peach"); foreach($fruits as $value) { print "$value "; }

apple avocado banana peach

If you want to work with only some of the elements in an array, you can extract the elements you want without modifying the array. To extract elements from an array, use the array_slice function instead of the array_splice function.
TYPE THIS: $fruits = array("apple", "avocado", "banana", "grapefruit", "melon"); $extracted = array_slice($fruits, 1, 3); foreach($extracted as $value) { print "$value"."s "; } RESULT:

avocados bananas grapefruits

⁄ Type the code that creates an array. ¤ To replace elements in the array with more than one new element, type the code that creates an array that contains the new elements. 92

‹ To replace elements in an array, type array_splice().

› Between the parentheses, type the name of the array that contains elements you want to replace followed by a comma. ˇ Type the offset number of the first element you want to replace followed by a comma.

Á Type the number of
elements you want to replace followed by a comma.

‡ To specify the
elements you want to assign to the array, type the name of the array that contains the new elements.

I To replace the array elements with just one element, you can type the value for the new element. A string value must be enclosed in quotation marks.

· Display the PHP page
in a Web browser.

I The Web browser displays the result of replacing elements in an array.

° Type the code that uses
the array.

93

PHP
When PHP sorts strings, values beginning with uppercase characters are grouped together first, followed by values beginning with lowercase characters. Using the same case for all the array elements will ensure that they are sorted in the correct order. You can use the strtolower function to convert the values in an array to all lowercase characters before performing a sort.
TYPE THIS: $fruits = array("Orange", "apple", "Banana", "mango", "Grape"); foreach($fruits as $key => $value) { $fruits[$key] = strtolower($value); } sort($fruits); foreach($fruits as $value) { print "$value "; }

WORK WITH ARRAYS

3

SORT A SIMPLE ARRAY

T

he sort function allows you to sort a simple array and place the elements in order from lowest to highest. For example, you could sort an array of numbers into ascending order or sort an array of strings into alphabetical order. The sort function takes the name of the array you want to sort as its argument. When you sort an array using the sort function, the keys for numerically indexed elements will be re-indexed starting from zero (0). This makes the sort function unsuitable for sorting an associative array. For information about sorting associative arrays, see page 96. PHP allows you to use an optional second argument with the sort function to specify how the data values should be treated. The SORT_REGULAR value specifies that PHP should evaluate the array elements based on their ASCII values. By default, PHP will use the SORT_REGULAR value when sorting an array, unless another sort type is specified. To specify that you want the array elements to be evaluated

You can arrange the elements in an array in random order. To arrange array elements in random order, you use the shuffle function. Before using the shuffle function, you must call the srand function to initialize PHP's random number generator.
TYPE THIS: srand((double) microtime() * 1000000); $numbers = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); shuffle($numbers); foreach($numbers as $value) { print "$value "; }

as numbers, you can use the SORT_NUMERIC value. If you specify the SORT_STRING value, the elements will be evaluated as strings. Specifying a sort type argument is useful when you want to force PHP to evaluate array elements in a specific way. For example, PHP would normally sort an array containing the numbers 1, 2 and 10 as 1 10 2. To ensure that the numbers are sorted in correct ascending order, you should use the SORT_NUMERIC value. The sort function will return a value of true or false depending on whether the sort was executed successfully. To sort an array in reverse order, from the highest to the lowest value, you use the rsort function. The rsort function has the same properties and takes the same arguments as the sort function.

RESULT:

1 2 3 7 0 4 5 6 8 10 9

RESULT:

apple banana grape mango orange
SORT A SIMPLE ARRAY

⁄ Type the code that creates an array. ¤ To sort the array, type sort(). ‹ Between the parentheses,
type the name of the array you want to sort.

› To specify the way
you want PHP to evaluate the elements, type a comma followed by a sort value.

Á Display the PHP page in a Web browser.

I The Web browser displays the results of sorting the values in an array.

SORT AN ARRAY IN REVERSE ORDER

⁄ Type the code that creates an
array.

› To specify the way you want PHP to evaluate the elements, type a comma followed by a sort value. ˇ Type the code that uses the array.

Á Display the PHP
page in a Web browser.

I The Web browser displays the results of sorting the values in an array in reverse order.

¤ To sort the array in reverse
order, type rsort().

ˇ Type the code that
uses the array.

‹ Between the parentheses,
type the name of the array you want to sort in reverse order.

94

95

PHP
The natsort function sorts alphanumeric values using a method called natural ordering, which is based on how a person would naturally order items. The natsort function is based on Martin Pool's Natural Order String Comparison algorithm. You can find more information about natural ordering at the www.linuxcare.com.au/projects/natsort Web site. The natsort function can be used to sort both simple and associative arrays.
TYPE THIS: $images = array ("img100.gif", "img12.gif", "img10.gif", "img2.gif", "img1.gif", "img20.gif"); natsort($images); foreach ($images as $value) { print "$value &nbsp"; }

WORK WITH ARRAYS

3

SORT AN ASSOCIATIVE ARRAY

T

he asort function is used to sort an associative array so that the relationship between the key and value of the array elements are preserved during the sorting process. When the asort function is used, the values of an associative array are sorted from lowest to highest. Using the asort function to sort the values in an associative array ensures that the array elements will not be re-indexed starting from 0, which would cause the original keys to be lost. You may also sort an associative array based on the keys of the array elements rather than the values using the ksort function. When the ksort function is used, the keys will be sorted from lowest to highest while maintaining the relationship between the key and value of the array elements.

The asort and ksort functions take the associative array you want to sort as an argument and will return a value of true or false depending on whether the sort was executed successfully. PHP allows you to use an optional second argument with the asort and ksort functions to specify how the data values should be treated. The SORT_REGULAR value specifies that PHP should evaluate the array elements based on their ASCII values. By default, PHP will use the SORT_REGULAR value when sorting an array, unless another sort type is specified. To specify that you want the array elements to be evaluated as numbers, you can use the SORT_NUMERIC value. If you specify the SORT_STRING value, the elements will be evaluated as strings.

The natcasesort function also uses the natural ordering method to sort values, but it sorts values in a case-insensitive manner. Similar to the other functions used to sort associative arrays, the natcasesort function maintains the relationship between the key and value of the array elements. The arsort function is used to sort the values of an associative array from highest to lowest. To sort an associative array based on keys from highest to lowest, the krsort function is used. The arsort and krsort functions take the associative array you want to sort as an argument. You can also specify the sort type you wish to use to evaluate the values or keys.

RESULT:

img1.gif img2.gif img10.gif img12.gif img20.gif img100.gif

SORT AN ASSOCIATIVE ARRAY

SORT BY VALUE

‹ Between the parentheses,
type the name of the array you want to sort.

⁄ Type the code that creates an associative array. ¤ To sort the array
according to the value of each element, type asort().

Á Display the PHP page in a Web browser.

› To specify the way you
want PHP to evaluate the values, type a comma followed by a sort value.

I The Web browser displays the result of sorting an associative array by the value of each element.

SORT BY KEY

‹ Between the parentheses,
type the name of the array you want to sort.

Á Display the PHP page
in a Web browser.

⁄ Type the code that
creates an associative array.

¤ To sort the array
according to the value of each element, type ksort().

› To specify the way you
want PHP to evaluate the keys, type a comma followed by a sort value.

I The Web browser displays the result of sorting an associative array by the key of each element.

ˇ Type the code that 96
uses the array.

ˇ Type the code that uses
the array.

97

PHP

WORK WITH ARRAYS
The code in the comparison function may contain more than one conditional structure, depending on how the two values are being compared. For example, in a comparison function used to compare two numbers, the code may initially compare the two values so that the odd number is first. If the two values are both odd numbers or both even numbers, the code may then compare the two values so that the smaller number is first.
TYPE THIS: function OddEven($firstValue, $secondValue) { $firstRem = $firstValue % 2; $secondRem = $secondValue % 2; if (($firstRem == 1) && ($secondRem == 0)) return -1; else if (($firstRem == 0) && ($secondRem == 1)) return 1; else { if ($firstValue < $secondValue) return -1; else if ($firstValue > $secondValue) return 1; else return 0; } } $numbers = array(18, 5, 9, 3, 69, 101, 58, 93, 14, 80, 28); usort($numbers, "OddEven"); foreach ($numbers as $value) { print "$value "; } RESULT:

3

SORT AN ARRAY USING COMPARISON FUNCTIONS
ou can create a function that compares values in an array to determine in which order the values should be sorted. To avoid unnecessary work, you should check whether there is an existing sorting function that suits your needs before defining your own function.

Y

A comparison function takes two arguments representing two adjacent values in an array. The function compares the two values and returns a value of -1, 1 or 0. A value of -1 indicates that the first value will appear first in the sorted array. A value of 1 indicates that the second value will appear first in the sorted array. If the function returns a value of 0, the two values are treated equally in the sort order. The code in the body of a comparison function typically contains a conditional structure, which is used to compare the two values and determine the value to be returned. Once the comparison function has been defined, you can use the usort function to sort the values in an array. When
SORT AN ARRAY USING COMPARISON FUNCTIONS

using the usort function, the array you want to sort is passed as the first argument. The name of the comparison function is passed as the second argument and must be enclosed in quotation marks. The array will then be sorted based on the order determined by the comparison function. When an array is sorted using the usort function, the array elements are re-indexed starting from zero (0). To maintain the association between the key and value of the array elements, such as when sorting an associative array, you should use the uasort or uksort function instead of the usort function. The uasort function sorts an array based on the value of the array elements. The uksort function sorts an array based on the key of the array elements. The uasort and uksort functions take the same arguments as the usort function.

3 5 9 69 93 101 14 18 28 58 80

⁄ To create a comparison function, type function followed by a name for the comparison function and (). 98

¤ Between the parentheses,
type the name of two variables that represent two adjacent values in an array, separated by a comma.

‹ In the body of the function, type the code that compares the two values and returns a value of -1, 1 or 0, depending on the result of the comparison.

I In this example, the comparison function compares the length of two string values and places the string with the shorter length first.

ˇ Type the name of the
function you want to use to sort the array (usort, uasort or uksort) followed by ().

Á Between the parentheses, type the name of the array followed by a comma. Then type name of the comparison function enclosed in quotation marks. ‡ Type the code that uses the sorted array.

° Display the PHP page
in a Web browser.

I The Web browser displays the result of using a user-defined comparison function to sort an array.

› Type the code that creates an array.

99

PHP

WORK WITH ARRAYS

3

GET INFORMATION ABOUT AN ARRAY

T

here are several functions available that you can use to find information about an array.

array_reverse function, the elements in the resulting array are re-indexed starting from 0. The array_flip function is used to switch the keys and values in an array. The array_flip function returns an array in which the keys are the values from the initial array and the values are the corresponding keys from the initial array. These functions all take the array you want to work with as an argument. The result of each function is typically assigned to a variable that can then be displayed on a Web browser or further processed. The in_array function is also used to find information about an array. This function allows you to find a specific value in an array. The in_array function takes two arguments––the value you are looking for and the array to be searched. The in_array function will return a value of true if the specified value is found.

The array_count_values function is used to count the number of times a value occurs in an array. This function returns an array in which each key represents a unique value in the initial array. The value associated with a key indicates the number of times the value occurred in the initial array. This is useful for calculating subtotals in an array. The array_sum function is used to calculate the sum of all the values in an array and is typically used on an array of numeric values. The array_sum function returns the sum as an integer or a floating-point number. You can use the array_keys function to obtain all the keys in an array. The array_keys function returns an array containing all the keys. The array_reverse function is used to reverse the order of the elements in an array. When using the
GET INFORMATION ABOUT AN ARRAY

You can use the array_rand function to retrieve random entries from an array. Before using the array_rand function, you need to use the srand function to initialize PHP's random number generator. When using the array_rand function, you must specify the array that contains the elements you want to select from. You may also specify the number of elements you want to choose.
TYPE THIS: srand((double)microtime() * 10000000); $numbers = array ("one", "two", "three", "four", "five", "six", "seven", "eight", "nine"); $pickThree = array_rand($numbers, 3); foreach ($pickThree as $value) { print "$numbers[$value] "; }

The array_unique function can be used to remove duplicate values from an array by returning an array containing only the unique values. This function is useful for removing redundant values that have been inadvertently added to an array.
TYPE THIS: $fruits = array ("apple", "banana", "apple", "banana", "orange"); $unique = array_unique($fruits); foreach ($unique as $value) { print "$value "; }

RESULT: RESULT:

apple banana orange

four nine seven

⁄ Type the code that creates an array. ¤ Type the function you want to use to find information about the array followed by (). 100

I You can use the array_count_values, array_sum, array_keys, array_reverse or array_flip function.

‹ Between the parentheses, type the name of the array you want to use.

› Type the code that
uses the result of the function.

USING THE in_array FUNCTION

‡ Type a comma followed
by the name of the array you want to search.

· Display the PHP page
in a Web browser.

ˇ To determine if a value
is found in an array, type
in_array().

° Type the code that uses
the result of in_array function.

I The Web browser displays the results of obtaining information about an array.

Á Between the parentheses,
type the value you want to find, enclosed in quotation marks.

101

PHP

WORK WITH ARRAYS
The each function is commonly used with the list statement to retrieve the key and value of an element in an array. The each function returns an array that has an index of 0 for the key and an index of 1 for the value of the element at which the internal array pointer is currently positioned. The pointer is then advanced to the next element. Code that creates a loop, such as a while statement, is required to access the key and value of each element in an array.
TYPE THIS: $user = array("Name" => "Frank", "Age" => "33", "Gender" => "male"); while (list($key, $value) = each($user)) { print "$key: $value<br>\n"; } RESULT:

3

USING THE LIST STATEMENT

P

HP allows you to use the list statement to assign the values in an array to a list of variables. Using the list statement can make your arrays easier to work with and is especially useful when working with functions that return an array. Instead of referencing an array element by its numeric key, you can assign the element to a variable with a meaningful name. When you want to use the element, you can use the variable name to access the element. This can also make your code easier to read and understand. The list statement takes as its arguments the names of the variables to which you want to assign the values in an array, separated by commas. You can assign all, some or just one of the values in an array to a variable. For example, if you want to retrieve only the third element in an array,

you do not need to assign all the elements to variables. Instead, you can leave the spaces for the first two elements empty and specify a variable name for only the third element, such as list(, , $day). When using the list statement, you should use only arrays with numerically indexed elements starting from zero (0). The order of the variables you specify in the list statement should correspond to the index numbers of the values, not the positions of the values in the array. The list statement cannot access values in an array with an associative index. You also cannot use the list statement to assign a value that is not part of an array to a variable.

Name: Frank Age: 33 Gender: male

You can use the next, prev, end and reset functions to move through the elements in an array. This allows you to move the internal array pointer to a specific element you want to access in an array. You can then use the each function with the list statement to assign the value of the element to a variable.
TYPE THIS: $user = array("Name" => "Frank", "Age" => "33", "Gender" => "male"); next($user); next($user); list(, $gender) = each($user); print "$gender"; RESULT:

male

USING THE LIST STATEMENT

⁄ Type the code that creates a function that returns an array.

¤ To assign the values in the
array to a list of variables, type list(). Then type = followed by the name of the function that returns the array.

‹ Between the parentheses for the list function, type the name of each variable to which you want to assign a value in the array. Separate each variable name with a comma.

I If you do not want to assign a value to a variable, leave a blank space for the value.

› Type the code that
uses the variables.

ˇ Display the PHP page
in a Web browser.

I The Web browser displays the result of using the list statement to assign array elements to variables.

102

103

PHP

WORK WITH STRINGS

4

CHANGE CASE OF A CHARACTER OR STRING
HP provides functions that allow you to change the case of text in a string. For example, you can use the strtolower function to change all the text in a string to lowercase. To change all the text in a string to uppercase, use the strtoupper function. Changing all the text in a string to the same case can make the text easier to search and manage. The ucfirst function allows you to change the first character in a string to uppercase. PHP will apply the ucfirst function to the first character in a string, even if the first character is not a letter. For example, if the first character in a string is a number, the string will not display any changes. Use the ucwords function to change the first character of each word in a string to uppercase. PHP will consider any character or group of characters that directly follows a whitespace character, such as a space or carriage return, to be a word. For more information about whitespace characters, see page 112.
CHANGE CASE OF A CHARACTER OR STRING

USING ASCII VALUES
SCII (American Standard Code for Information Interchange) is a numbering system that assigns numerical values to letters, numbers and other characters. Many programs save, read and exchange data using the ASCII numbering system. Using the ord and chr functions allows you to convert between ASCII values and characters. The ord function converts a specified character to an ASCII value. If multiple characters are specified, the ord function will return the ASCII value of only the first character. You may find that you need to convert characters to their ASCII values in order to format and manipulate data. For example, if you use a PHP page to write data to a file, you may need to convert formatting characters such as horizontal tabs to their ASCII values before you can write the characters to the file. The chr function converts a specified ASCII value to a character. PHP allows you to manipulate the results of the chr function as you would manipulate strings. For example,
USING ASCII VALUES

P

Each function takes the name of the variable that stores the string you want to change as its argument. If the string has not been assigned to a variable, you can use the string, enclosed in quotation marks, as the argument. The strtolower, strtoupper, ucfirst and ucwords functions can be used together to apply the results of one case function to another case function. This lets you change the case of a string in more than one way. For example, using the ucwords function will have no apparent effect if the string contains all uppercase characters. To ensure that only the first letter of every word is uppercase in the string, you can first apply the strtolower function and then apply the ucwords function to the string, such as ucwords(strtolower($changeCase)).

A

you can join characters returned by the chr function together using the concatenation operator (.). Converting ASCII values to characters in a PHP page is useful for including characters in your PHP page that do not appear on your keyboard, such as mathematical symbols. The standard ASCII characters are numbered from 0 to 127. When using the extended ASCII character set, the characters are numbered up to 255. You can visit the www.asciitable.com Web site to view a complete chart of the extended ASCII character set. All characters on a computer, including non-displayable characters and whitespace characters, such as the tab and newline characters, have an ASCII value. To convert a non-displayable or whitespace character to an ASCII value, you must provide the escape sequence for the character. For a list of commonly used escape sequences, see the top of page 42.

⁄ Type the code that creates a variable containing the string you want to change. ¤ Type the name of the function
you want to use to change the case of characters in the string (strtolower, strtoupper, ucfirst or ucwords) followed by ().

‹ Between the
parentheses, type the name of the variable that stores the string.

ˇ Display the PHP page in a Web browser.

I The Web browser displays the result of changing the case of characters in a string.

⁄ To convert a character to
an ASCII value, type ord().

‹ To convert an ASCII value to a character, type chr(). › Between the parentheses, type the ASCII value you want to convert. ˇ Type the code that uses the ord and chr functions.

Á Display the PHP
page in a Web browser.

¤ Between the parentheses,
type the character you want to convert enclosed in quotation marks.

I The Web browser displays the results of using the ord and chr functions.

› Type the code that
uses the result of the function.

104

105

PHP

WORK WITH STRINGS
The sprintf function uses the same formatting rules as the printf function. However, the sprintf function returns the formatted string as a result that can be assigned to a variable instead of automatically outputting the formatted string.
TYPE THIS: RESULT:

4

FORMAT A STRING
he printf function allows you to format strings for output. The printf function requires two arguments––a format string and a list of values you want to format. A format string contains the formatting rules that will be applied to the values. Each formatting rule in the format string must have a corresponding value in the list. Formatting rules are specified using a percentage symbol (%) and a type specifier that indicates the type of formatting to be applied. Before including the type specifier, you may also indicate padding, alignment, width and precision specifiers, in that order, to further format the string. These specifiers are useful for lining up text and numbers, improving the appearance of data in text-based Web browsers. The padding specifier indicates the character you want to use to pad the result. The padding specifier consists of a single quotation mark (') followed by the character you want to use. By default, spaces are used for padding.

T

The result of the printf function is normally right-justified, but you can include the alignment specifier (-) to signify that the result should be left-justified. You can also include a width specifier to indicate a minimum width. For example, the formatting rule %8s formats a string so it will have a minimum width of eight characters. A precision specifier indicates how many decimal digits should be displayed. The precision specifier is represented by a dot (.) followed by the number of decimal digits. For example, the formatting rule %.2f formats a floating-point number with a precision of two decimal places. A format string can also contain characters you do not want to format. For example, to include text in a string with formatted numbers, type the text in the format string. PHP will replace the formatting rules in the format string with the formatted numbers and then output the text and formatted numbers.

$name $rate $info print

= "David"; = 10.2369; = sprintf("%s's hourly rate is $%.2f.", $name, $rate); "$info<br>";

David's hourly rate is $10.24.

You can use the following type specifiers to indicate the type of formatting you want to apply.
TYPE SPECIFIER: MEANING:

b c d e f o s x X

Format as a binary number. Format as a character specified by the ASCII value. Format Format Format Format Format Format Format as as as as as as as a decimal number. a floating-point number, using exponential notation. a floating-point number. an octal number. a string. a hexadecimal number with lowercase letters. a hexadecimal number with uppercase letters.

FORMAT A STRING

⁄ To format a string for output, type printf().

¤ Between the parentheses, type
the formatting rules you want to use enclosed in quotation marks. Note: You may also include text you do not want to format within the quotation marks.

‹ Type a comma followed by the name of the variable you want to use for the first formatting rule you specified.

I You may specify a value instead of a variable. String values must be enclosed in quotation marks.

› Repeat step 3 for
each formatting rule you specified.

ˇ Type the code that
uses the printf function.

Á Display the PHP page
in a Web browser.

I The Web browser displays the result of formatting a string.

106

107

PHP

WORK WITH STRINGS

4

FIND THE LENGTH OF A STRING
HP's strlen function allows you to determine the number of characters in a string. The strlen function is often used to find the length of a string stored in a variable. The strlen function is especially useful for finding the length of a string before it is processed. For example, you can use the strlen function to check whether a password provided by a user has the required minimum number of characters or whether the data entered by a user is within a specific character limit before allowing the user to continue using your Web site. Determining the length of a string is also useful if you want to iterate through each character in a string using a loop. You would determine the length of the string and use the length as the condition for ending the loop.

P

The strspn function allows you to determine the length of a portion of a string. To use the strspn function, you must specify the characters you want to count in the string, called a mask. The strspn function returns the length of the portion of the string that contains the characters specified in the mask. The strspn function will stop executing when it encounters the first character that is not specified in the mask.
TYPE THIS: $amount = "\$259 dollars for hotel expenses."; $mask = "1234567890\$"; print strspn($amount, $mask); RESULT:

If the string for which you want to determine the length contains spaces or punctuation marks, the strlen function will count the spaces and punctuation marks as characters. PHP evaluates any escape sequences in a string, such as tabs (\t) or newlines (\n), before counting the number of characters, so each escape sequence is counted as one character. For example, the strlen function would count six characters in the string "hello\n". If you use the strlen function with a numeric value, PHP will evaluate the number as if it were a string. If the number includes a decimal point, the decimal point will also be counted as a character. For example, the strlen function would count nine characters in the number 123456.78.

4

The strcspn function is similar to the strspn function, except the strcspn function works in reverse by returning the length of the portion of a string which does not contain the characters specified in a mask. When the strcspn function encounters a character specified in the mask, the function will stop executing.
TYPE THIS: $filename = "\n\n \r \t\t ##my_webpage.html"; $mask = "abcdefghijklmnopqrstuvwxyz_."; print strcspn($filename, $mask); RESULT:

10

FIND THE LENGTH OF A STRING

⁄ Type the code that creates a string variable and assigns it a value.

¤ To determine the length of the string, type strlen().

‹ Between the parentheses, type the name of the variable that stores the string for which you want to determine the length.

I You can also type a string between the parentheses. Strings must be enclosed in quotation marks.

› Type the code that uses
the strlen function.

ˇ Display the PHP page
in a Web browser.

I The Web browser displays the result of finding the length of a string.

108

109

PHP
When using a while loop to execute the strtok function, if two tokens are adjacent in the string, the function will return an empty string and the while loop may end before the rest of the string is processed. To avoid this type of problem, you should use a strict comparison for FALSE. The remaining string will then be processed and the strtok function will return a segment of the string from the last token found to the next token in the string. If you want to access every segment of a string, you may want to call the strtok function once and then use a while loop to execute subsequent calls to the strtok function. The while loop should be set to terminate when the strtok function returns an empty string. The strtok function works well for processing strings with simple structures. For example, the strtok function is useful for counting the number of words in a sentence or for processing a database file in which the data is separated by tab characters.
Example: while (($word = strtok(" .")) !== FALSE) { print $word . "<br>"; }

WORK WITH STRINGS

4

DIVIDE A STRING

The implode function may be used to join the elements in an array into one string. When calling this function, you need to specify a string, which will be used to join the array elements, and the array containing the elements to be joined.
TYPE THIS: $fruitsArray = array ("apple", "orange", "peach", "grape", "melon"); $fruitsString = implode(" and ", $fruitsArray); print $fruitsString;

Y

ou can use the strtok function to divide a string based on one or more characters, called tokens, you specify. This process is also referred to as tokenizing a string. When the strtok function is first called, it requires two arguments––the string you want to divide and the tokens you want to use to divide the string. The strtok function then returns a segment of the string from the beginning of the string to the position of the first token. You may specify one or more characters to be used as tokens. If you specify an empty string as a token, the strtok function will simply return the entire string. The strtok function will also return the entire string if the string does not contain any of the tokens you specified.

The explode function may be used to divide a string and return an array of strings. This function typically requires two arguments––a string to be used as a separator and the string to be divided. You may also specify an optional third argument that indicates the maximum number of elements you want returned.
TYPE THIS: $fruitsString = "apple orange peach grape melon"; $fruitsArray = explode(" ", $fruitsString, 5); foreach ($fruitsArray as $value) { print "$value : "; }

RESULT:

apple and orange and peach and grape and melon

After the first time the strtok function is called in a PHP page, PHP will keep track of the remaining string that has not yet been divided. When the strtok function is called again in the page, you need to indicate only the tokens. You do not need to specify the string you want to divide again.

RESULT:

apple : orange : peach : grape : melon :

DIVIDE A STRING

⁄ Create a variable that contains a string you want to divide. ¤ To divide the string, type strtok(). 110

‹ Between the parentheses, type the name of the variable that contains the string, followed by a comma. › Type the characters you
want to use to divide the string, enclosed in quotation marks.

ˇ Type the code that assigns the result of the strtok function to a variable.

Á Type the code that
uses the result of the strtok function.

‡ To access the
subsequent segments of the string, type the code that creates a while loop and uses the results of the strtok function.

I The strtok function returns a segment of the string up to the first token.

I After the first call to the strtok function, you do not need to specify the variable that contains the string you want to divide.

° Display the PHP page
in a Web browser.

I The Web browser displays the result of using the strtok function to divide a sentence.

111

PHP
If you want to verify that the whitespace characters have been removed from a string, you may use the strlen function to count the number of characters in the original string and the number of characters in the resulting string. These functions are useful for cleaning up user input from a form, since the data received from forms can sometimes be unpredictable. For example, when a user is asked to enter data into a form, a user may inadvertently type extra spaces. Trimming the extra spaces from the beginning and end of the string may help ensure that the data is processed properly. You may also use these functions to remove formatting from text that is read from a file or will be written to a file. For example, text files that come from different operating systems, such as UNIX or Windows, may be formatted differently. Removing whitespace characters from a line of text before it is processed or written to a file can help avoid potential errors.
TYPE THIS: $original = "Welcome to my Web page!\0\t \r\n"; $trimmed = rtrim($original); print "Length of original string: " . strlen($original); print "<br>Length of trimmed string: " . strlen($trimmed);

WORK WITH STRINGS

4

TRIM A STRING
here are several functions used for trimming whitespace characters from strings before the strings are used or processed. Whitespace characters, which include spaces, carriage returns (\r), newlines (\n), tabs (\t), vertical tabs (\013) and null characters (\0), are normally invisible when displayed on a Web page, but may cause problems when included in data to be processed. To remove whitespace characters from the end of a string, you can use the rtrim function. The ltrim function is used to remove whitespace characters from the beginning of a string. To remove whitespace characters from the beginning and the end of a string, you can use the trim function. The rtrim, ltrim and trim functions all take the string to be trimmed as an argument and return the string with the appropriate whitespace characters removed. The returned string can be directly displayed to a Web browser or assigned to a variable, which can then be further processed in the script.

T

RESULT:

Length of original string: 28 Length of trimmed string: 23

PHP does not have a function that removes whitespace characters from the middle of a string, but you can use the eregi_replace function to replace adjacent whitespace characters in a string with a specified character or string. The eregi_replace function
TYPE THIS:

requires three arguments––a pattern containing the characters to be matched and replaced, a replacement character or string and a string that contains characters to be replaced. The eregi_replace function cannot be used to replace null characters (\0) in a string.
RESULT: Before: This a string After: This is a string . . . is . . .

$original = " This \t is\n\n a string . . ."; $replaced = eregi_replace("[\n\t\013\r ]+", " ", $original); print "<b>Before:</b><pre>$original</pre>"; print "<b>After:</b><pre>$replaced</pre>";

TRIM A STRING

⁄ Type the code that creates variables that contain strings you want to trim. ¤ To remove whitespace characters from the end of a string, type rtrim(). 112

‹ Between the parentheses,
type the name of the variable that contains the string you want to trim.

ˇ To remove whitespace characters from the beginning of a string, type ltrim(). Á Between the parentheses, type the name of the variable that contains the string you want to trim.

‡ Type the code that
uses the result of the ltrim function.

° To remove whitespace
characters from the beginning and end of a string, type trim().

‚ Type the code that
uses the result of the trim function.

— Display the PHP page
in a Web browser.

I The Web browser displays the results of trimming strings.

› Type the code that uses
the result of the rtrim function.

· Between the parentheses,
type the name of the variable that contains the string you want to trim.

113

PHP
The strncmp function can be used to compare a specific number of characters at the beginning of two strings. This function takes three arguments––the names of the two variables storing the strings you want to compare and the number of characters to be compared. The strncmp function, similar to the strcmp function, performs a case-sensitive comparison and returns an integer indicating which of the strings has a greater value or indicating that the strings have the same value.
TYPE THIS: $word1 = "banana"; $word2 = "bandit"; $result = strncmp($word1, $word2, 3); if ($result == 0) { print "The beginning of the word <b>$word1</b> is the same"; print " as the beginning of the word <b>$word2</b>."; } else { print "The words are different."; }

WORK WITH STRINGS

4

COMPARE STRINGS

Y

ou can use the strcmp function to compare two strings based on the ASCII (American Standard Code for Information Interchange) values of the characters in each string. For more information about ASCII values, see page 105. Comparing the values of strings can be useful if you want to sort the strings into a specific order. For example, you can compare the strings "cap" and "cat" and then put the strings in order. Based on a comparison of the ASCII values of each character in the strings, the string "cap" would come before the string "cat". It is important to remember that uppercase characters have different ASCII values than lowercase characters.

function returns a value greater than zero, typically 1. If the second string has a greater value than the first string, the function returns a value less than zero, typically -1. If the two strings have an equal value, the function returns zero. If one entire string exactly matches the beginning of the other string, the strcmp function returns the number of additional characters found in the longer string. If you compare an empty string to a non-empty string, the number of characters in the non-empty string is returned. Whether the number is positive or negative depends on which of the two strings is longer. If the first string is longer, a positive number is returned. If the second string is longer, a negative number is returned. The strcmp function is often used with an if statement to test which string has the greater value and then perform an action.

The strcasecmp and strncasecmp functions can be used to perform case-insensitive string comparisons. When these functions are used, the case of characters in the strings being compared is ignored. To use the strncasecmp function, you must indicate the number of characters you want to compare at the beginning of the strings.
TYPE THIS: $firstWord = "hello"; $secondWord = "HELLO"; $result = strcasecmp($firstWord, $secondWord); if ($result == 0) { print "The words are the same."; } else { print "The words are different."; }

The strcmp function takes the strings you want to compare or the names of the variables storing the strings as its arguments. After performing a case-sensitive comparison, the strcmp function returns an integer value indicating which of the strings has a greater value. If the first string has a greater value than the second string, the

RESULT:

RESULT:

The beginning of the word banana is the same as the beginning of the word bandit.

The words are the same.

COMPARE STRINGS

⁄ Type the code that creates the first string variable you want to use in a comparison. 114

¤ Type the code that creates the second string variable you want to use in a comparison. ‹ To compare the strings, type strcmp().

› Between the parentheses, type the name of the first string variable followed by a comma.

ˇ Type the name of the
second string variable.

Á Type the code that
uses the strcmp function.

‡ Display the PHP page
in a Web browser.

I The Web browser displays the result of comparing strings.

115

PHP
If you do not want to extract a substring from the offset to the end of the string, you can include an argument in the substr function to specify the number of characters you want to extract. If a negative number is specified, PHP removes that number of characters from the end of the substring.
TYPE THIS: $file = "my_webpage.htm"; print "Filename: " . substr($file, 0, 10);

WORK WITH STRINGS

4

EXTRACT OR REPLACE A SUBSTRING

T

he substr function allows you to access a specific part of a string, called a substring.

the string. When counting characters from the end of a string, PHP starts the count at 1, not zero (0). The substr_replace function allows you to specify replacement text for a substring and return the modified string. You must specify the name of the string variable in which you want to replace text. The new text you want to use and a positive or negative offset of the substring must also be specified. You can also specify the length of the substring you want to replace. If a positive number is used to specify the length, PHP replaces that number of characters with the replacement text. If a negative number is used, PHP stops replacing text that number of characters from the end of the string. The replacement text does not have to be the same length as the substring.

The strrchr function can be used to extract a substring from the last occurrence of a specified character to the end of a string. To use this function, you must specify the name of the string variable from which you want to extract a substring and the character to be matched.
TYPE THIS: $url = "http://www.abccorp.com/Sales2000"; $directory = strrchr($url, "/"); print $directory;

You must specify the name of the variable containing the string from which you want to extract a substring. The offset, or position, of the substring within the string must also be specified. If the offset value is a positive number, PHP finds the starting position of the substring by counting the number of characters from the beginning of the string. Characters in a string are numbered starting at zero (0). The substr function will return a substring that begins at the position you specified and ends at the end of the string. If the offset value you specify is a negative number, PHP finds the starting position of the substring by counting the number of characters from the end of
EXTRACT OR REPLACE A SUBSTRING

RESULT:

Filename: my_webpage
RESULT:

The strstr function can be used to extract a substring from the first occurrence of a specified character to the end of a string. To use this function, you must specify the name of the string variable from which you want to extract a substring and the character to be matched.
TYPE THIS: $email = "martine@maran.com"; $domain = strstr($email, "@"); print $domain; RESULT:

/Sales2000

@maran.com

⁄ Type the code that creates a string variable and assigns it a value. ¤ To extract a substring, type substr().

‹ Between the parentheses,
type the name of the string variable from which you want to extract a substring.

REPLACE A SUBSTRING

° Type a comma followed
by the replacement text enclosed in quotation marks.

· Type a comma followed
by the offset of the substring you want to replace.

Á To replace a substring in a string, type substr_replace(). ‡ Between the parentheses,
type the name of the string variable in which you want to replace text.

— Type the code that uses the substr_replace function.

± Display the PHP page
in a Web browser.

I The Web browser displays the results of extracting and replacing substrings.

› Type a comma followed
by the offset of the substring you want to extract.

‚ Type a comma followed
by the length of the substring you want to replace.

116

ˇ Type the code that uses
the substr function.

117

PHP
You may want to use the substr function to extract a substring that is a specific number of characters from a substring or character you find using the strpos or strrpos function. In the example below, the extension is extracted from a filename.
TYPE THIS: $file = "my_webpage.php"; $offset = strrpos($file, ".") + 1; print "The file type is: " . substr($file, $offset);

WORK WITH STRINGS
The strrpos function is used to find the last occurrence of a dot (.) in the string. The return value is then increased by 1 and the new value is used as the offset where the substr function will extract the extension.
RESULT:

4

SEARCH FOR A SUBSTRING OR CHARACTER
The strpos function allows you to search a string for the first occurrence of a substring and return the offset, or position, of the substring. If the substring cannot be found in the string, a value of false is returned. To use the strpos function, you must specify the name of the variable containing the string you want to search and the substring you want to search for. The substring must be enclosed in quotation marks. Although not required, PHP allows you to specify a starting offset when searching for a substring. When determining the starting offset, keep in mind that the characters in a string are numbered starting at zero (0). It is important to note that even if you specify a starting offset, the position of the substring returned by the function will still be relative to the beginning of the string.

T

he strpos and strrpos functions allow you to search a string to find a substring or character you specify.

The strrpos function allows you to search a string for the last occurrence of a character and return the offset of the character. If the character cannot be found in the string, a value of false is returned. The strrpos function takes two arguments––the name of the variable containing the string you want to search and the character you want to search for, enclosed in quotation marks. If you specify more than one character, only the first character will be used in the search. The strpos and strrpos functions are often used with an if statement to test whether the specified substring or character was found and then perform an action. When using an if statement, PHP could confuse the zero (0) position in a string with a value of false. To prevent this type of problem in your code, you should use the Identical to comparison operator (===) in the if statement.

The file type is: php

You can use the strpos function in a while statement to find all the instances of a substring in a string. In the example below, the offset is advanced by one position every time the while loop is iterated.
TYPE THIS: $users = "Barry Pruett, Mary Corder, Ted Cains, Mary Bednarek, Mary Hicks"; $offset = 0; while ($position !== false) { $position = strpos($users, "Mary", $offset); if ($position === false) break; print "Mary found at position: $position<br>"; $offset = $position + 1; } RESULT:

Mary found at position: 14 Mary found at position: 38 Mary found at position: 53

SEARCH FOR A SUBSTRING OR CHARACTER

⁄ Type the code that creates a variable that stores the string you want to search. ¤ To search for the first occurrence of a substring in a string, type strpos(). 118

‹ Between the parentheses, type the name of the string variable you want to search followed by a comma. › Type the substring you want to search for, enclosed in quotation marks.

ˇ To specify a starting position for the search, type a comma followed by the offset in the string where you want to start the search.

Á Type the code that
uses the strpos function.

SEARCH FOR A CHARACTER

‡ To search for the last occurrence
of a character in a string, type
strrpos().

· Type the character you want to search for, enclosed in quotation marks. ‚ Type the code that uses the strrpos function.

— Display the PHP page
in a Web browser.

I The Web browser displays the results of searching for a substring and a character in a string.

° Between the parentheses, type
the name of the string variable you want to search followed by a comma.

119

PHP
The str_replace function is case-sensitive and will only replace portions of the string that perfectly match the data to be replaced. To perform a case-insensitive replacement of data, you can use the eregi_replace function, which takes the same arguments as the str_replace function.
TYPE THIS: $text = "Mary had a little Lamb, little lamB, little LaMb."; print eregi_replace("lamb", "sheep", $text);

WORK WITH STRINGS

4

REPLACE DATA IN A STRING

Y

ou can use the str_replace function to replace all the occurrences of data in a string with another string. The str_replace function requires three arguments––the data to be replaced, the replacement string and the string that contains the data to be replaced. The result of the str_replace function can be directly displayed to a Web browser or assigned to a variable that can be further processed. The str_replace function is useful for editing data that is read from a text file or will be written to a file. For example, you may want to correct the spelling of a name or update an e-mail address before processing the information. You may want to replace specific characters in a string with another set of characters. This can be accomplished using the strtr function. To use the strtr function, you must first specify the string to be modified. You then specify the set of characters that you want to replace and the replacement characters. The last two parameters should

have the same number of characters. If the two parameters do not match in length, the longer parameter will be truncated to match the number of characters in the shorter parameter. The strtr function is useful for correcting data received from a form or a text file. For example, if a user enters data containing accented letters into a form, you may want to replace the accented letters with regular letters before processing the data. When the strtr function is used, each character in the string is examined in sequence and replaced accordingly. After the string has been completely processed, no further replacements are performed. You may also use the substr_replace function to replace data in a string. For information about the substr_replace function, see page 116.

RESULT:

Mary had a little sheep, little sheep, little sheep.

The strtr function may also be used to replace multiple words in a string. Instead of specifying the sets of characters to be searched and replaced, you can specify an associative array as the second argument of the strtr function. The instances of the array keys found in the string are replaced by the corresponding array values.
TYPE THIS: $oldList = "apple, banana, melon, grape"; $replacement = array("apple" => "melon", "melon" => "mango"); $newList = strtr($oldList, $replacement); print "Old list: $oldList<br>"; print "New list: $newList<br>"; RESULT:

Old list: apple, banana, melon, grape New list: melon, banana, mango, grape

REPLACE DATA IN A STRING

USING THE str_replace FUNCTION

¤ To replace data in a
string, type str_replace().

⁄ Type the code that creates variables that contain strings in which you want to replace data.

‹ Between the parentheses, type the data you want to replace, enclosed in quotation marks. › Type a comma followed
by the replacement string, enclosed in quotation marks.

ˇ Type a comma
followed the name of the string variable in which you want to replace data.

USING THE strtr FUNCTION

· Type a comma followed by
the characters you want to replace, enclosed in quotation marks.

± Display the PHP page
in a Web browser.

‡ To replace characters in
a string, type strtr().

I The Web browser displays the results of replacing data and characters in a string.

Á Type the code that
uses the result of the str_replace function.

° Between the parentheses,
type the name of the string variable in which you want to replace characters.

‚ Type a comma followed by
the replacement characters, enclosed in quotation marks.

120

— Type the code that uses the
result of the strtr function.

121

PHP

WORK WITH STRINGS
You can use the strip_tags function to remove all HTML formatting from a file or to prevent code a user inputs from being processed. The strip_tags function removes all the HTML and PHP tags from a string and then returns the result as plain text that can be easily processed or manipulated.
TYPE THIS: $htmlSource = "<html><head><title>ABC Corporation</title></head><body> <h1>Welcome to Our Web Site.</h1></body></html>"; $rawText = strip_tags($htmlSource); print $rawText; RESULT:

4

WORK WITH HTML TEXT
he htmlspecialchars and htmlentities functions allow you to convert special characters in a string to their character entity reference. The character entity reference consists of an ampersand, the name of the character and a semicolon. You can convert characters in order to force a Web browser to display HTML code as plain text on a PHP page instead of processing the code. This is useful when you want to block HTML code a user enters in a form that might interfere with the processing of a Web page. The htmlspecialchars function converts only the most common HTML characters to their character entity reference values. The htmlentities function is similar to the htmlspecialchars function, except the htmlentities function converts all the characters that have an equivalent character entity reference in HTML. To use the htmlspecialchars and htmlentities functions, you specify the string to be converted or a variable that stores the string. Each function will return a string with the corresponding character entity references for the HTML characters.
WORK WITH HTML TEXT

T

You can use the get_html_translation_table function to display a list of the characters that the htmlspecialchars or htmlentities function will convert. As an argument, you specify either HTML_SPECIALCHARS or HTML_ENTITIES. The function returns an associative array that has the actual character to be converted as the key and the character entity reference as the value for each element. PHP allows you to use an optional second argument with the htmlspecialchars, htmlentities and get_html_translation_table functions to specify how quotation marks should be handled. By default, PHP will use the ENT_COMPAT value, which converts only double quotation marks to their HTML entity reference. To convert both double and single quotation marks, use the ENT_QUOTES value. If you specify the ENT_NOQUOTES value, neither double nor single quotation marks will be converted.

ABC Corporation Welcome to Our Web Site.

The nl2br function allows you to convert newline characters (\n) in a string to HTML <br> tags. For example, you can use the nl2br function to convert a newline character a user types in a text area on a form to a <br> tag that a Web browser can process and display as a line break on a Web page. The nl2br function takes as its argument the string that contains the newline character to be converted or a variable that stores the string.
TYPE THIS: $userInput = "Hello!\nMy name is Tom!"; $formattedText = nl2br($userInput); print $formattedText; RESULT: Hello! My name is Tom!

CONVERT HTML CHARACTERS

¤ To convert HTML
characters to their character entity reference, type htmlspecialchars() or htmlentities().

⁄ Type the code that creates a variable that contains HTML code.

‹ Between the parentheses,
type the name of the variable that contains HTML code.

› To specify how you want the function to convert quotes, type a comma followed by the value you want to use (ENT_NOQUOTES, ENT_COMPAT or ENT_QUOTES).
results of the conversions.

DISPLAY THE TRANSLATION TABLE

° To display the character
entity reference values in a translation table, type a variable name followed by = htmlspecialchars().

Á To view the characters
that will be converted, type
get_html_translation_table().

‚ Type the code that formats the result of the get_html_ translation_table function in a table.

— Display the PHP page
in a Web browser.

I The Web browser displays the result of converting HTML characters and displays a translation table for the function you specified.

‡ Between the parentheses,
type the value for the display (HTML_SPECIALCHARS or HTML_ENTITIES).

ˇ Type the code that uses the translation table you want to

· Between the parentheses,
type the name of the variable that stores the characters that will be converted.

122

123

PHP

WORK WITH FILES

5

WRITE TO A FILE

I

t is often necessary to access text files stored on the Web server from within a PHP page. Writing data to text files allows you to store data, such as configuration settings and application information. Before you can write to a file, you must establish a connection to the file by using the fopen function to open a file and create a file pointer. A file pointer indicates the file you want to work with. The fopen function takes two arguments––the name of the file to be opened and the access mode you want to use. To open a file for writing, the w access mode can be specified. This access mode creates a new file if the file does not already exist. Using the w access mode will also overwrite any information already in an existing file. When a file is opened for writing, the file position indicator is placed at the start of a file. The file position indicator indicates where the next operation will be performed in the file.

You can use the fputs function to write a line of information to the file. The fputs function usually takes two arguments––a file pointer and the information to be written to the file. You may also specify the maximum length of the line to be written, in bytes. After the maximum length has been reached, any extra information at the end of a line will not be written to the file. Once all the information has been written to a file, the fclose function should be used to close the connection to the file. As with other operations involving accessing a file, the proper permissions that allow the file to be written to must be in place. For information about permissions, you should consult your operating system's documentation.

There are several different access modes you can use when opening a file. Each access mode places the file position indicator in a specific location.
ACCESS MODE: DESCRIPTION:

r r+ w w+

Open a file for reading only. Place the file position indicator at the start of the file. Open a file for reading and writing. Place the file position indicator at the start of the file. Open a file for writing only. Place the file position indicator at the start of the file. Create the file if it does not exist. Open a file for reading and writing. Place the file position indicator at the start of the file. Create the file if it does not exist. Open a file for writing only. Place the file position indicator at the end of the file. Create the file if it does not exist. Open a file for reading and writing. Place the file position indicator at the end of the file. Create the file if it does not exist.

a a+

WRITE TO A FILE
data - Notepad

⁄ To open a file and create a file pointer, type a variable name for the file pointer followed by = fopen(). 124

¤ Between the parentheses,
type the name of the file you want to open followed by a comma.

› To write a line of information to the file, type fputs(). ˇ Between the parentheses,
type the name of the file pointer followed by a comma.

Á Type a line of
information you want to write to the file.

‡ Repeat steps 4 to 6
until you have specified all the information you want to write to the file.

° To close the file,
type fclose().

‹ To specify the access
mode that allows you to write to the file, type "w".

I You may also specify
the maximum length of the line of information, in bytes.

· Between the
parentheses, type the name of the file pointer.

I When the PHP page is displayed in a Web browser, the information will be written to the file.

‚ You can use your text
editor to open the file and view its contents or use a PHP page to read the file. For information about reading a file using a PHP page, see page 126.

125

PHP

WORK WITH FILES

5

READ A FILE
fter creating a file pointer and opening a file for reading, you can access the contents of the file. This allows you to display the data in a Web browser or compare the data in the file to other data. When opening the file, you must specify an access mode that allows reading from the file. The r access mode is typically used. When a file is initially opened for reading, the file position indicator is placed at the beginning of the file. The fgets function is used to read the line of text indicated by the file position indicator and must have two arguments––the file pointer and the maximum length of the line to be read, in bytes. After a line of text is read from the file, the file position indicator automatically moves to the next line of text in the file. A while loop is often used to process each line in a file. With each iteration of the loop, the information retrieved from the file using the fgets function can be assigned to a variable and displayed to the client using the print function.

A

The fgets function will read a line of text up to the maximum length specified or until it reaches a newline character. A line will be truncated if it is longer than the maximum length specified. When the fgets function is used again, it will read the next line in the file and not the remainder of the previous line that was truncated. The feof function can be used to determine if the end of a file has been reached. The feof function takes the file pointer as an argument and is usually used with the Not operator (!) as the condition tested in a while loop. Once all the lines from a file have been read, the fclose function should be used to close the connection to the file.

Most computers that use Web server software and PHP have sophisticated username and password-based security features. When using PHP to read a file, the correct permissions that allow the PHP script to read the file must be enabled on the Web server that stores the file. Web servers are typically configured to use a special user account, such as web or http, to allow access to files. This user account must have read permissions for the files to be opened because when PHP attempts to read a file, the operating system interprets it as an attempt to read the file by the username assigned to the Web server. The special user account on the Web server must be set up before files can be accessed using PHP.

The file function may be used to automatically open, read and close a file. The file function takes the name of a file as an argument and returns the entire contents of the file as an array. Each element in the array will correspond to a line of information in the file. You do not need to create a file pointer when using the file function.
Example: $lines = file("data.txt"); foreach ($lines as $value) { print $value . "<br>"; }

READ A FILE

⁄ Perform steps 1 and 2 on page 124 to enter the code that opens a file and creates a file pointer.

¤ To specify the access
mode that allows you to read information from the file, type "r".

‹ To read a line of information from the file, type fgets(). › Between the
parentheses, type the name of the file pointer followed by a comma.

ˇ Type the maximum
length of the line of information to be read, in bytes.

Á Create a while loop
that will read and display each line of information from the file.

‡ To close the file, type
fclose().

· Display the PHP page
in a Web browser.

° Between the
parentheses, type the name of the file pointer.

I The Web browser displays the result of reading a file.

126

127

PHP

WORK WITH FILES

5

COPY OR DELETE A FILE
HP provides functions that allow you to manage files from within a PHP page. For example, the copy function creates a copy of a file, while the unlink function deletes a file. Copying a file is useful for creating a backup copy of a file. Deleting a file lets you remove a file that is no longer needed by the PHP page. It is good programming practice to verify whether a file exists before attempting to copy or delete the file. You can use the file_exists function to determine whether a file exists. The file_exists function returns a value of true if a file you specify exists and a value of false if the file does not exist. The copy function takes two arguments––the filename or path of the file to be copied and the filename or path of the copy you want to create. When the file is copied, the copy function duplicates the file without removing the original file.

P

The unlink function derives its name from the command used to delete files on Unix computers. The unlink function takes the filename or path of the file you want to delete as its argument. When specifying arguments for the copy and unlink functions, if the file you want to copy or delete is located in the current directory, you can specify just the name of the file. If the file is located in a different directory, you must specify the full path to the file. You may want to store the name or path of a file in a variable and then use the variable with the copy or unlink function. When the copy and unlink functions are successful, they return an integer value other than 0. If the functions are not successful, they return a value of 0.

In order to successfully copy and delete files, you must have the appropriate file and operating system permissions on the computer where the files are stored. For example, you cannot delete a file that has read-only permissions set. For information about the permissions for an operating system, refer to the operating system's documentation. The copy function is also useful for moving a file from one directory to another. To move a file, you use the copy function to create a copy of the file in the directory you want to move the file to. You can then use the unlink function to remove the original file from the directory you no longer want to store the file.
Example: copy("formdata.txt", "backup/webfile/formdata.txt"); unlink("formdata.txt");

You can use the filesize function to determine the size of a file in bytes. Determining the size of a file is useful when you want to delete large files in order to free up storage space.
TYPE THIS: print "The size of the file is: "; print filesize("formdata.txt") . " bytes";

RESULT:

The size of the file is: 1867 bytes

COPY A FILE

DELETE A FILE

⁄ To copy the file, type copy(). ¤ Between the parentheses,
type the name or path of the file you want to copy enclosed in quotation marks.

‹ Type a comma and
then type the name or path of the copy you want to create enclosed in quotation marks.

› Display the PHP page in a Web browser.

I The file has been copied.

⁄ To delete a file, type
unlink().

¤ Between the parentheses, type the name or path of the file you want to remove enclosed in quotation marks.

‹ Display the PHP page
in a Web browser.

I The file has been deleted.

128

129

PHP

WORK WITH FILES

5

DETERMINE THE STATUS OF A FILE
hen working with files, it is often necessary to determine information about a file before performing an action. For example, you should verify that a file can be written to by a PHP page before opening the file for writing. The is_file function allows you to determine if a file you specify is a file. This is useful when you want to ensure that an item is a file rather than a directory or a link to another file. The is_file function is commonly used to verify that an item is a file before attempting to open the file. The function returns a value of true if the item you specify is a file. Before opening a file you want to read, it is common practice to use the is_readable function to verify that the file can be read from a PHP page. If a file exists and is readable, the is_readable function returns a value of true.
DETERMINE THE STATUS OF A FILE

W

To determine whether a file can be written to by a PHP page, you use the is_writable function. If the file exists and can be written to, the function returns a value of true. The is_writable function is commonly used to check the status of files that can be written to by multiple users, since such files are frequently temporarily unavailable for writing while in use by another user. The is_file, is_readable and is_writable functions all take a single argument that indicates the file you want to check. The argument can be the file name or path of the file, such as c:\webfiles\form.dat, or a variable that stores the filename or path, such as $filename. If the file you want to check is in the current directory, you can specify just the name of the file. If the file is located in a different directory, you must specify the full path of the file.

Determining the status of a file can improve the efficiency of a PHP script. For example, before performing a complex process, such as retrieving information from a database and appending the information to a file, a check can be made to ensure the data can be written to the file. The is_file, is_readable and is_writable functions may be affected by the operating system you are running and the file system used by the computer that stores the files. While the is_file, is_readable and is_writable functions should perform as expected on Unix systems, there may be incompatibilities that interfere with the operation of these functions on other systems.

You can use the is_dir function to determine whether an item is a directory. The is_dir function returns a value of true if the directory you specify exists and is a directory.
TYPE THIS: if (is_dir("c:\data\webinfo")) { print "c:\data\webinfo is a directory."; } else { print "This is not a directory."; }

RESULT:

c:\data\webinfo is a directory.

⁄ To store the path of a file you want to check in a variable, type the code that assigns the path to the variable. ¤ To determine whether
the file is a file, type is_file().

‹ Between the parentheses,
type the name of the variable that stores the path of the file.

ˇ To determine whether the file can be read from the PHP page, type is_readable(). Á Between the parentheses, type the name of the variable that stores the path of the file.

‡ Type the code that
uses the result of determining whether the file is readable.

° To determine whether
you can write to the file, type is_writable().

‚ Type the code that uses
the result of determining whether the file is writable.

— Display the PHP page
in a Web browser.

› Type the code that uses the
result of determining whether the file is a file.

· Between the parentheses,
type the name of the variable that stores the path of the file.

I The Web browser displays the results of determining the status of a file.

130

131

PHP
Only the owner of a file or the system administrator can change the group or permissions for a file. When using the chgrp function, the owner of a file can assign the file only to a group to which the owner belongs. The system administrator can assign a file to any group.

WORK WITH FILES

5

SET FILE GROUP AND PERMISSIONS ON UNIX
ou can use a PHP page to change the group a file belongs to and set the permissions for the file. Changing the group and permissions for a file allows you to restrict access to the file.

Y

The system function allows you to execute UNIX commands from within a PHP page. To view the group and permissions for each file in the current directory, you can use the ls -l command. The chgrp function is used to assign a file to a new group. To use the chgrp function, you specify the location and name of the file you want to assign to a new group followed by the name of the group. Unix systems allow you to assign any combination of read (r), write (w), and execute (x) permissions to a file's owner, the group the file belongs to and all other users. The permissions for a file are typically represented by a
SET FILE GROUP AND PERMISSIONS ON UNIX

dash followed by a series of nine characters. The first three characters represent the permissions for the file's owner. The next three characters represent the permissions for the owner's group and the last three characters represent the permissions for all other users. To change the permissions for a file, you use the chmod function. The chmod function takes two arguments––the location and name of the file and the octal value representing the file permissions you want to use. The octal value consists of three digits, which represent the permissions for the owner, followed by the permissions for the owner's group and the permissions for other users. For example, the -rwxr-xr-x permissions will have an octal value of 755. You should precede the octal value with a zero (0). The chgrp and chmod functions return a value of true when the functions are executed successfully.

The chown function can be used to change the owner of a file. When using the chown function, you must specify the location and name of the file and the user name of the new owner. Only the system administrator can use the chown function.
Example: chown("/var/www/html/file1", "maryc")

The fileowner function allows you to determine the owner of a file. You can use the filegroup function to determine the group a file belongs to, which is usually the group to which the owner belongs. These functions retrieve an ID number that represents the user name of the owner or the name of the group. You can use the password file or group file available in Unix to match an ID number with the corresponding user name or group name.
TYPE THIS: print ("The UID is: " . fileowner("/var/www/html/file1")) . "br"; print ("The GID is: " . filegroup("/var/www/html/file1")); RESULT:

The UID is: 48 The GID is: 501

⁄ To execute a Unix command from the PHP page, type system().

¤ To display a list of files
in the current directory and the permissions for each file, type "ls –l" between the parentheses.

CHANGE FILE GROUP

ˇ Type a comma,
followed by the name of the group to which you want to assign the file, enclosed in quotation marks.

SET FILE PERMISSIONS

‹ To assign a file to a new group, type chgrp(). › Between the parentheses, type the location and name of the file, enclosed in quotation marks.

Á To change the
permissions for a file, type chmod().

° Type a comma, followed by the octal value that represents the permissions you want to assign to the file. The octal value should be preceded by 0. · To display an updated list of the files in the current directory, repeat steps 1 and 2.

‚ Display the PHP page
in a Web browser.

I The Web browser displays the results of changing the group and permissions for a file.

‡ Between the
parentheses, type the location and name of the file, enclosed in quotation marks.

132

133

PHP
PHP allows you to specify permissions for a directory in octal notation. When creating a directory on a computer You can make a variable name easier to read running the UNIX operating system, you can convert by using the underscore character ( _ ) to UNIX permissions to octal notation using the following separate the words in the name. When you chart. The UNIX permissions include read (r), write (w) separate the words in a variable name, you and execute (x). The octal value will consist of three should capitalize each word. digits, representing the permissions for the owner, followed by the permissions for the owner's group Example: and the permissions for other users. For example, Dim My_Date_Of_Birth a directory with permissions -rwxrw-r-- will have the octal value 764. When entering the permissions in a PHP script, precede the octal value with a zero (0).
UNIX PERMISSIONS: OCTAL VALUE:

WORK WITH FILES

5

CREATE AND DELETE DIRECTORIES
HP provides functions that allow you to manage directories from within a PHP page. The mkdir function creates a new directory, while the rmdir function removes an existing directory. You may want to create a directory to store temporary files and then remove the directory when the files are no longer needed by the PHP page. When working with directories in the current directory, you specify the name of the directory you want to create or remove. If you want to work with directories in a different directory, you must specify the full path of the directory you want to create or remove. You may want to store the name or path of a directory in a variable and then use the variable with the mkdir or rmdir function. When creating a new directory on a computer running the UNIX operating system, you must also specify permissions for the directory. Permissions control access to the directory and determine the operations, such as reading and writing, that can be performed.
CREATE A DIRECTORY

P

A directory you want to remove must not contain any files or subdirectories. You must delete any existing files and subdirectories from a directory before you can delete the directory. For information about deleting files, see page 128. When the mkdir and rmdir functions successfully create or remove a directory, they return an integer value other than 0. If the functions are not successful, they return a value of 0. It is good programming practice to verify whether a directory exists before attempting to create or remove the directory. You can use the file_exists function to determine whether a file exists.

In order to successfully create and remove directories, you must have the appropriate file and operating system permissions on the computer where the directories are to be created or removed. For information about the permissions for an operating system, refer to the operating system's documentation. The chdir function allows you to change which directory you are working in. This is useful when you want to work with files stored in another directory. To change the current directory, specify the name of the directory you want to work in, enclosed in quotation marks.
Example: chdir("temp");

----x -w-wx r-r-x rwrwx
DELETE A DIRECTORY

0 1 2 3 4 5 6 7

⁄ To store the name or path of the directory you want to create in a variable, type the code that assigns the information to the variable. ¤ To create a directory, type mkdir(). 134

‹ Between the parentheses, type the name of the variable you created in step 1. › If necessary, type a
comma and then type the octal value for the permissions you want the directory to use.

ˇ Display the PHP page in a Web browser.

I The directory has been created.

⁄ To store the name or path
of the directory you want to remove in a variable, type the code that assigns the information to the variable.

¤ To remove a directory,
type rmdir().

› Display the PHP page
in a Web browser.

I The directory has been removed.

‹ Between the parentheses,
type the name of the variable you created in step 1.

135

PHP

CREATING AND PROCESSING FORMS

6

CREATE A FORM
dding a form to a Web page allows you to gather data from users who visit the page. A form can be placed anywhere between the <body> and </body> tags in an HTML document. The body of your Web page can include as many forms as you need. You use the <form> tag to create a form and the action attribute to specify the location and name of the PHP page that will process the data entered into the form. If the PHP page is stored in the same directory as the Web page containing the form, you have to specify only the name of the PHP page. If the PHP page is not stored on the same Web server as the Web page containing the form, you must specify the full URL of the PHP page. You must also specify which method the form will use to pass data to the PHP page. There are two methods the form can use––get and post. The method you should

ADD ELEMENTS TO A FORM
use depends on the amount of data that will be passed. The get method sends data to the PHP page by appending the data to the URL of the page. The post method sends the data and the URL separately. The get method is faster than the post method and is suitable for small forms. The post method is suitable for large forms that will send more than 2000 characters to a PHP page. Unlike many other technologies used to process form information, PHP can automatically determine whether a form is submitting data using the get or post method and then retrieve the information accordingly. For information about creating a PHP page that processes data from a form, see page 140.

A

E

lements are areas in a form where users can enter data and select options. The most commonly used element is a text box, which allows users to enter a single line of data into a form. Text boxes are often used for entering names, addresses and other short responses.

Elements you add to a form must be placed between the <form> and </form> tags. A form can contain as many elements as you need. There are many different types of elements you can add to a form, such as text areas and check boxes. Text areas allow users to enter several lines or paragraphs of text, while check boxes let users select options on a form. For information about commonly used elements, see page 138. Each form element has attributes, such as name, type and size, which offer options for the element. The name attribute allows you to provide a name for an element.
ADD ELEMENTS TO A FORM

The name you specify is used by the PHP page that processes the form to identify the element and access the information in the element. A name can contain letters and numbers, but should not contain spaces or punctuation. If you want to include spaces in a name, use an underscore character (_) instead. You must add a submit button to every form you create. The submit button allows users to send the data they entered into the form to the Web server. When the Web server receives data from a form, the server transfers the data to the PHP page that will process the data. The PHP page can then perform an action with the data, such as storing the data in a database or displaying the information in a Web browser.

CREATE A FORM

Add Elements To A Form - Microsoft Internet Explorer

⁄ Type <form action=""
where you want to add a form to a Web page.

¤ Between the quotation
marks, type the location and name of the PHP page that will process the data entered into the form.

‹ Type method="">. › Between the quotation
marks, type the method the form will use to pass data to the PHP page.

ˇ Type </form> where
you want to end the form.

⁄ To add a text box to a
form, type <input type="text" name=""> between the <form> and </form> tags.

‹ To add a submit button to the form, type <input type="submit" name="">. › Between the quotation marks, type a word that describes the button.

ˇ Display the Web
page in a Web browser.

I The Web browser displays the text box and submit button.

I You can now add elements to the form.

¤ Between the quotation
marks, type a word that describes the text box.

136

137

PHP

CREATING AND PROCESSING FORMS

6

FORM ELEMENTS

COMMONLY USED ELEMENTS (CONTINUED)

A

n element is an area in a form where users can enter data or select options. There are several different types of elements you can add to a form.

Most elements require you to specify attributes that determine how the element will appear on a Web page.
COMMONLY USED ATTRIBUTES

You can find more information about form elements and attributes at the www.w3.org/TR/1999/REC-html401-19991224/interact/forms Web site.

Text Box A text box allows users to enter a single line of text, such as a name or telephone number. You must set the type attribute to text and use the name attribute to create a text box. You may also want to use the maxlength and size attributes.
First Name <input type="text" name="firstName" maxlength="20">

Text Area The textarea element displays a large text area that allows users to enter several lines or paragraphs of text. A large text area is ideal for gathering comments or questions from users. You must use the name attribute to create a text area.
Questions? <textarea name="userQuestions"></textarea>

Type The type attribute allows you to specify the kind of element you want to use.

Name The name attribute allows you to specify a name for an element. The PHP page that will process data from the element uses the name attribute to identify the data. Element names can contain more than one word, but should not contain spaces or special characters. Size The size attribute allows you to specify the width of an element.

Value The value attribute allows you to specify a value for an element. If an element displays a button, you can use the value attribute to specify the text that will appear on the button. Checked The checked attribute allows an element to display a selected option by default.

First Name
Check Box Check boxes allow users to select one or more options. For example, check boxes can be used to allow users to specify which states they have visited. You must set the type attribute to checkbox and use the name and value attributes to create a check box. You may also want to use the checked attribute.

Questions?

Maxlength The maxlength attribute allows you to restrict the number of characters a user can enter into an element.

Which states have you visited in the past year?<br> New York <input type="checkbox" name="states" value="New York" checked> California <input type="checkbox" name="states" value="California"> Texas <input type="checkbox" name="states" value="Texas">

Which states have you visited in the past year? Texas New York California

Radio Button
COMMONLY USED ELEMENTS

Password Box A password box allows users to enter private data. When a user types data into a password box, an asterisk (*) appears for each character, which prevents others from viewing the data on the screen. A password box does not protect the data from being accessed as it is transferred over the Internet. You must set the type attribute to password and use the name attribute to create a password box. You may also want to use the value, maxlength and size attributes.
Password Please <input type="password" name="secretWord" value="password" maxlength="20">

Drop-Down List The select element displays a drop-down list that allows users to select an option from a list of several options. For example, a drop-down list can be used to allow users to select one of three shipping methods. You must use the name attribute to create a drop-down list. You use the <option> tag with the value attribute to add options to the list.
How would you like your products shipped? <select name="shipMethod"> <option value="air">Air</option> <option value="land">Land</option> <option value="sea">Sea</option> </select>

Radio buttons allow users to select only one of several options. For example, radio buttons can be used to allow users to specify if they are male or female. You must set the type attribute to radio and use the name and value attributes to create a radio button. You may also want to use the checked attribute.
What is your gender?<br> Female <input type="radio" name="gender" value="female" checked> Male <input type="radio" name="gender" value="male">

What is your gender? Male Female

Submit Button A submit button allows users to send data in the form to the PHP page that will process the data. You must add a submit button to each form you create. You must set the type attribute to submit to create a submit button. You may also want to use the name and value attributes.
<input type="submit" name="submit" value="Submit Now">

Reset Button A reset button allows users to clear the data they entered into a form. A user cannot redisplay data that has been cleared. Reset buttons are commonly used in forms that have many text boxes. You must set the type attribute to reset to create a reset button. You may also want to use the value attribute.
<input type="reset" value="Click to Reset">

Password Please ********

How would you like your products shipped? Air
Air Land Sea Submit Now

Click to Reset

138

139

PHP

CREATING AND PROCESSING FORMS

6

PROCESS DATA FROM A FORM
fter creating a form on a Web page, you can create a PHP page that will process data submitted in the form. A PHP page can use information it accesses from a form to perform tasks such as displaying the data or storing the data in session variables or a database. PHP makes it easy to process data from a form. When a PHP page receives form information, the page automatically converts the names of form elements to PHP variables and assigns the data entered in the elements to the variables. To process data entered in a form element, you simply access the variable for the element by prefixing the name of the element with a dollar sign ($). The name of a form element is specified when the element is created on the Web page containing the form. For information about creating elements on a form, see page 137.

A

The PHP page that processes a form also automatically identifies the method the form is using to transfer information. This allows you to create a PHP page that processes form data without having to specify whether the form uses the get or post method. For more information about the methods a form can use to transfer information, see page 136. After creating and saving a PHP page that processes data submitted in a form, you should review the code for the Web page that contains the form to verify that the action attribute displays the correct filename and location for the PHP page. You should also verify that each form element has a unique name to ensure that the PHP page will create a unique variable for each form element. As with all variable names in PHP, the names of variables that store form data are case sensitive.

In addition to using forms, data can also be passed to a PHP page by a query string. A query string is one or more name-value pairs appended to the URL of a PHP page. To create a query string, you enter the URL of the PHP page in a Web browser, followed by a question mark. You then enter a name followed by an equal sign and a value for the name. To enter multiple name-value pairs, separate each pair with an ampersand (&). A query string should not exceed 2000 characters. The PHP page that receives the data will create variables using the names you specify and will assign the specified values to the variables.
Example: http://www.abccorp.com/processform.php?userName=Ernest&region=USA

As a security precaution, a PHP page that processes form data should not be used to display secure information based on the data submitted in the form. For example, you should not display troubleshooting or administrative information when a user name such as admin is entered in a text box. Form data can be easily manipulated, allowing unauthorized users to access the secure information.

The empty function can be used to verify whether a user entered data in a form element. If a user leaves the form element blank, the empty function will return a value of true.
TYPE THIS: if(empty($userName)) { print "You did not enter a user name."; } RESULT:

You did not enter a user name.

PROCESS DATA FROM A FORM

SET UP THE PHP PAGE

¤ Type the code that
uses the data from the form element.

⁄ Type $ followed by the
name of a form element you want to access.

‹ Repeat steps 1 and 2 for each form element you want to access.

PROCESS FORM DATA

⁄ In a Web browser,
display the Web page containing the form you want to process.

¤ Enter data into the form. ‹ Click the submit button
to pass the data in the form to the PHP page that will process the data.

I The Web browser displays the result of processing data from a form.

140

141

PHP

CREATING AND PROCESSING FORMS

6

PROCESS MULTIPLE FORM SELECTIONS

M

ost elements in a form are used to submit a single item of information, such as a name or telephone number, to a page that processes the information. Some form elements, however, allow users to choose more than one option at once. For example, you can create a form that allows a user to select one or more items from a list. The elements most often used to pass multiple selections in a form are the drop-down list and the check box element. For more information about form elements, see page 138. When creating a form that can pass multiple selections for one element to a PHP page, you must indicate that the PHP page should process the data as an array of values, rather than as a single variable. To specify that the data should be passed as an array, you include a pair of brackets [] after the name of the element in the form, such as <select name="products[]">.

In the PHP page that processes the form data, you can access all the values selected for an element by using a for loop. For information about creating a for loop, see page 54. To access the values in the for loop, you prefix the name of the element with a dollar sign ($), just as you would access a single item of information from an element. Using the count function to determine the number of values passed by the element allows you to specify when the for loop should end. After creating and saving the PHP page, you should review the code for the Web page that contains the form to verify that the action attribute displays the correct filename and location for the PHP page.

When you use the check box element to pass multiple selections in a form, you must include a pair of brackets after the name of the element for each option to ensure that PHP will store the selected options in an array.
Example: <form action="select.php"> <input type="checkbox" name="services[]" value="tune-up" checked>tune-up<br> <input type="checkbox" name="services[]" value="tire rotation">tire rotation<br> <input type="checkbox" name="services[]" value="oil change">oil change<br> <input type="submit" value="Submit"> </form>

When processing data from a form, you should include code in the PHP page that checks the validity of data a user submits in the form. For example, if you want users to select at least two options from a list, you can add error-checking code that ensures two selections were made.
Example: if (count($services) > 1) { for ($x = 0; $x < count($services); $x++) print "$services[$x]<br>"; } else { print "Please select at least 2 items."; }

PROCESS MULTIPLE FORM SELECTIONS

tire rotation oil change brake inspection

CREATE THE FORM

¤ To indicate that the
information from the element should be stored in an array, type [] after the name of the element.

SET UP THE PHP PAGE

¤ Type the code for the
for loop that will access each piece of data from the form element.

PROCESS MULTIPLE SELECTIONS

⁄ Type the code that creates a form with an element that allows users to select multiple options.

⁄ In the PHP page, type $ followed by the name of the form element that allows users to select multiple options.

⁄ In a Web browser, display
the Web page containing the form you want to process.

Note: To select multiple options from a drop-down list, hold down Ctrl as you click each option.

I The Web browser displays the result of processing multiple form selections.

¤ Select options in the form.

142

‹ Click the submit button to pass the data in the form to the PHP page that will process the data.

143

PHP

CREATING AND PROCESSING FORMS

6

CREATE A FORM TO UPLOAD A FILE
form can be used to allow users to upload a file to a Web server. Allowing users to upload files is useful for collecting information that is best displayed in a separate file, such as a résumé or an order form. Users can send plain text files or binary files, such as images and compressed files. The files users send are usually stored on your Web server.

You may incorporate other form elements into a form that allows users to upload files. This is useful for transferring other information, such as the sender's name and a file description, which you may want to use when processing the file that has been sent.
Example: <form action="savefile.php" enctype="multipart/form-data" method="post"> Enter File Name: <input type="file" name="uploadedFile"><br> Your Name: <input type="text" name="username" size="30"><br> File Description: <input name="fileDetails" type="text" size="50"><p> <input type="submit" value="Upload File"> </form>

A

to select a file from their computer. The name attribute of the <input> tag should indicate the name that will be used to identify the file that a user sends. As with others forms, a submit button must be added to the form, which allows users to start the process of transferring the file to the Web server. You may also want to provide users with an alternate method of transferring files, such as using an FTP server. This is especially helpful in cases where a user's Web browser is not able to upload files. After the file has been sent to a Web browser, a PHP page may be used to retrieve and process the uploaded file. For information about using a PHP page to process a file submitted using a form, see page 146.

The ability to upload files using forms is not strictly a PHP feature. It is an HTML specification and can be used to upload files to Web servers using technologies other than PHP. For more detailed information about how files are transferred using forms, you may refer to the World Wide Web Consortium (W3C) Web site at www.w3.org/TR/device-upload.

The action attribute of the <form> tag should specify the PHP page where the file is to be sent and processed. In the <form> tag, you should also use the enctype attribute with the multipart/form-data value to ensure that the files users send will transfer in the proper format. The form should also use the post method when transferring a file. To indicate that a form element will be used to upload a file, the type attribute of the <input> tag should have a value of file. This form element will allow users to type the name of the file they wish to send or use a Browse button

You may add a hidden field to your form to specify the maximum size of the file that may be sent to the Web server. The value MAX_FILE_SIZE is assigned to the name attribute, and the value attribute is used to specify the maximum size, in bytes. This hidden field must be placed before the file input field.
Example: <form action="savefile.php" enctype="multipart/form-data" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"> Enter File Name: <input type="file" name="uploadedFile"><p> <input type="submit" value="Upload File"> </form>

CREATE A FORM TO UPLOAD A FILE

⁄ In the <form> tag, type action="".

¤ Between the quotation marks, type the name of the PHP page that will process the file sent by the form.

‹ Type enctype="multipart/formdata" to ensure that the files

ˇ Between the <form>
and </form> tags, type the text you want to appear beside the area that will allow users to send files.

Á To add the element that
allows users to send a file, type <input type="file">.

° Between the
quotation marks, type the name that will be used to identify the file.

· Save the page with
the .html extension and display the HTML page in a Web browser.

users send will transfer in the proper format.

I Users can click in the box and type the location and name of the file they want to send. I Users can also click the Browse button to open a dialog box that will help them locate the file they want to send.

› Type method="post" to
specify the method used to transfer the file.

‡ In the <input> tag, type name="".

I The Web browser
displays an area that allows users to send a file.

144

145

PHP

CREATING AND PROCESSING FORMS
The php.ini file contains configuration settings that allow you to change the temporary directory used for storing uploaded files and the maximum size of files that can be uploaded. You can also disable the ability to upload files. Open the php.ini file on the Web server and look for the following section of code.
;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; file_uploads = On ; Whether to allow HTTP file uploads upload_tmp_dir = c:\temp ; temporary directory for HTTP uploaded files upload_max_filesize = 2M ; Maximum allowed size for uploaded files

6

PROCESS AN UPLOADED FILE

A

PHP page can be used to retrieve and process a file that was uploaded to a Web server by a user.

When a file is uploaded to a Web server using a PHP page, it is first temporarily stored using a filename assigned by PHP. This temporary file will be deleted after the PHP page has finished processing. You can use the copy function to save a permanent copy of the uploaded file. You need to pass two arguments to the copy function––the temporary filename and the filename to be used to save the file, which can be the original name of the file. After the file has been permanently stored, you can access the file as you would access any other file on the Web server. To determine the temporary filename of the uploaded file, you must access the $HTTP_POST_FILES array, which is an associative array that stores information about the

uploaded file. When accessing information from the $HTTP_POST_FILES array, you need to specify the name used to identify the file. This is the same name that was specified in the name attribute of the <input> tag in the form used to send the file. You must also specify the index name of the information you want to access. You use the tmp_name index name to access the temporary filename assigned to the uploaded file. You can use other index names to access additional pieces of information about the file from the $HTTP_POST_FILES array. For example, use the name index name to determine the original filename of the uploaded file. The size index name returns the file size, in bytes. To determine the file type, you specify the type index name. Some Web browsers may not allow you to determine the file type.

Before you can process uploaded files using a PHP page, you must make sure that file upload has been enabled and the temporary directory specified in the php.ini file exists on the Web server. When an uploaded file is permanently saved on a Web server, by default, the file is saved in the same directory where the PHP page is located. You may want to save the file in a different directory by appending the directory path to the name of the file. To avoid errors, you should make sure that the specified directory exists on the Web server before attempting to save the uploaded file.
Example: $tempFile = $HTTP_POST_FILES['uploadedFile']['tmp_name']; $destination = "c:\\uploads\files\\" . $HTTP_POST_FILES['uploadedFile']['name']; copy($tempFile, $destination);

PROCESS AN UPLOADED FILE

⁄ To access information about a file uploaded to the Web server, type $HTTP_POST_FILES[][].

¤ Between the first set of
brackets, type the name used to identify the uploaded file enclosed in single quotation marks.

› To save a permanent copy of the uploaded file, type copy().

‹ Between the second set of
brackets, type the index name of the information you want to access enclosed in single quotation marks.

ˇ Between the parentheses, repeat steps 1 to 3, except type the tmp_name index name, enclosed in single quotation marks, in the second set of brackets to access the temporary name of the file.

Á To use the original
filename to store the copy of the uploaded file, type a comma and then repeat steps 1 to 3, except type the name index name, enclosed in single quotation marks, in the second set of brackets.

‡ Type the code that uses the accessed information about the uploaded file. ° Save the page with the .php extension.

I After a user uploads a file to the Web server using a form, the PHP page will be able to process the file and display the result of accessing information about the uploaded file.

I The file is also permanently saved on the Web server.

146

147

PHP

MANAGING COOKIES AND SESSIONS
Instead of specifying the expiry time for a cookie in seconds, you can specify an exact date when you want the cookie to expire. This is useful for a cookie that you do not want to expire for a long period of time. To create a cookie that uses an exact date for the expiry time, you can use the header function to send the cookie to the client as an HTTP header.
Example: header("Set-Cookie: accessedBefore=Yes; expires=Friday, 07-Mar-2003 00:00:00 GMT;");

7

CREATE AND READ A COOKIE
HP pages can be used to create and read cookies. When a user accesses a page that creates a cookie, the cookie is typically stored as a small text file on the user's computer. The cookie can later be read by a PHP page to access the information stored in the cookie. For example, a cookie can store a user's name. When the user accesses the PHP page again later, the page can use the value stored in the cookie to display the user's name. To create a cookie, you use the setcookie function. The function takes several arguments, including the name you want to assign to the cookie, the value you want the cookie to store and an expiry time for the cookie. The setcookie function must be placed before any other code on a PHP page. By default, a cookie will be deleted when the user closes their Web browser. Setting an expiry time for a cookie
CREATE A COOKIE

P

allows the cookie to store information for longer periods of time. The time function can be used to set the expiry time, in seconds, for a cookie. After creating a cookie, you can have a PHP page read the cookie. When a user with a cookie stored on their computer visits a PHP page that can read the cookie, PHP automatically converts the name of the cookie to a variable and assigns the value stored in the cookie to the variable. This makes it easy to work with cookies using PHP. To read a cookie stored on a user's computer, you simply access the cookie variable by prefixing the name of the cookie with a dollar sign ($). When working with cookies, keep in mind that a client may be configured to reject cookies or may be located behind a security firewall that filters out cookie information.
READ A COOKIE

To prevent unauthorized pages from reading a cookie you placed on a user's computer, you can specify a path and domain for the cookie in the setcookie function. Only the pages stored in the specified directory and domain will be able to read the cookie.
Example: setcookie("accessedBefore", "Yes", time() + 3600, "/web/text", "www.test.com");

If a PHP page attempts to access a variable that does not exist, an error will be generated. You may want to use the isset function to verify that a cookie variable exists before attempting to access the variable in a PHP page.
Example: if (isset($cookieValue)) { print "A cookie exists on your computer"; }

a name for the cookie enclosed in quotation marks. Then type a comma followed by the value you want to assign to the cookie enclosed in quotation marks.

⁄ To create a cookie, type setcookie(). ‹ To specify when the cookie will ¤ Between the parentheses, type expire, type a comma
followed by time().

ˇ Display the PHP page in a Web browser.

I The cookie is now stored on the computer.

⁄ In the PHP page, type $
followed by the name of the cookie you want to read.

¤ Type the code that uses the value of the cookie.

‹ Display the PHP page
in a Web browser.

I The Web browser displays the result of reading a cookie.

› Type + followed
by the expiry time for the cookie in seconds.

148

149

PHP

MANAGING COOKIES AND SESSIONS

7

DELETE A COOKIE
HP allows you to delete a cookie before it expires. This is useful if you no longer need the information in the cookie. For example, you may want to delete a cookie that contains user registration information if the user cancels their registration to your Web site. It may also be necessary to remove cookies if you already have the maximum number of cookies allowed, but want to create more. PHP permits each domain to store up to 20 cookies. You can delete cookies you no longer need to make room for new cookies. To remove a cookie, you use the setcookie function to create a new cookie that has the same name as the cookie you want to remove, but has an expiry time set as a time in the past. For example, you can use the time function to set the expiry time as a negative number of seconds, such as time() - 60. This will cause the cookie to expire immediately. The setcookie function must be placed before any other code on a PHP page.

P

When deleting a cookie, the value you assign to the cookie can be an empty string. If you specified a path and domain when you created the original cookie, you must specify the same path and domain when deleting the cookie. This ensures that the correct cookie is removed. For information about specifying a path and domain for a cookie, see the top of page 148. Working with cookies is not always a simple task. Some Web servers and Web browsers work with cookies in different ways. For example, some Web servers will not allow a cookie to be removed from a client computer until the cookie reaches its original expiry time. When working with cookies, you should thoroughly test your code on all Web browsers you expect to access your PHP page.

If you want to make changes to a cookie you have previously created, you must delete the cookie and then recreate the cookie using the new information. The process of deleting and then recreating a cookie differs depending on the version of PHP you are using.
PHP Version 4 PHP Version 3

When using PHP version 4, cookies you create and delete using the setcookie function are processed in the order they appear in the PHP script. To delete and then recreate a cookie, you must place the setcookie statement that deletes the cookie before the setcookie statement that recreates the cookie.
Example: setcookie("status", "", time() - 60); setcookie("status", "approved", time() + 3600);

When using PHP version 3, cookies you create and delete using the setcookie function are processed in reverse order. To delete and then recreate a cookie, you must place the setcookie statement that recreates the cookie before the setcookie statement that deletes the cookie.
Example: setcookie("status", "approved", time() + 3600); setcookie("status", "", time() - 60);

DELETE A COOKIE

⁄ To delete a cookie, type setcookie().

¤ Between the
parentheses, type the name of the cookie you want to delete enclosed in quotation marks.

‹ Type a comma and then type "" to enter an empty string for the value of the cookie.

› To specify an expiry
time in the past, type a comma and then type time() - followed by a number of seconds.

ˇ If you specified a path
for the cookie when the cookie was created, type a comma and then type the path enclosed in quotation marks.

Á If you specified a domain
for the cookie when the cookie was created, type a comma and then type the domain enclosed in quotation marks.

‡ Display the PHP page
in a Web browser.

I The cookie has been deleted from the computer.

150

151

PHP

MANAGING COOKIES AND SESSIONS

7

START A SESSION
session is created for each user that requests a PHP page from your Web site. A session enables a Web server to use cookies to collect and use information entered by a user while the user accesses resources on the Web server. For example, if a user specifies a user name on the main page of a Web site, this user name can be used by the Web server to personalize any other Web pages the user requests during that session.

A

The Web server keeps track of each session by assigning a session ID to identify each current user. When a session is started, the Web server stores a session ID as a cookie named PHPSESSID on the user's computer. When the user requests another page from the site, the user's Web browser sends the session ID to the Web server to identify the user. To access the current session ID using a PHP page, you type $PHPSESSID. Session IDs are randomly generated by the Web server. You should not use the session ID as a unique identifier, such as the primary key in a database, as the session ID may not always be unique. For example, if the Web server is restarted, the server may assign a user a session ID that was previously assigned to a different user.

To start a session in a PHP page, you use the session_start function. The session_start function must be placed before any HTML code on your PHP page. It is also good programming practice to start a session at the beginning of your PHP page so that session information is available throughout the page. Calling the session_start function while an existing session is in progress will not create a new session or affect the existing session.

PHP typically stores session information in a directory on the Web server. The name and location of this directory is specified by the session.save_path value in the php.ini configuration file. You should check to make sure the directory exists before starting a session. If the directory does not exist, you can create it. For example, if the php.ini configuration file specifies /tmp as the session.save_path value, you can create a directory named tmp in the main directory on the Web server. You can change the name of the cookie used to store the session ID number by changing PHPSESSID in the session.name value in the php.ini configuration file on the Web server. Using a unique session.name value helps to increase the security of your PHP pages.

You can use the session_id function to specify a different value for a session ID. This is useful when you want to create unique session IDs that you can use as identifiers in your code. The session ID must be enclosed in quotation marks and placed within the parentheses following the session_id function. You should use only alphanumeric characters when specifying a session ID.
Example: session_id("User593204");

You can also use the session_id function to access the session ID instead of using the PHPSESSID cookie. Before using the session_id function, you should call the session_start function to indicate that you will use session information.
Example: print session_id();

START A SESSION

ACCESS THE SESSION ID
Access a Session ID - Microsoft Internet Explorer

⁄ To start a session, type session_start().

I The session_start
function should be placed before any HTML code on your PHP page.

¤ Display the PHP page in a Web browser.

I The session is started.

⁄ Type $PHPSESSID
where you want to access a session ID.

¤ Type the code that will
display the session ID in a Web browser.

‹ Display the PHP page
in a Web browser.

I The Web browser displays the result of accessing the session ID.

152

153

PHP

MANAGING COOKIES AND SESSIONS

7

CREATE AND READ A SESSION VARIABLE
s a user moves through the pages in your Web site, the user may be asked to enter information such as a user name, password or preferences to display each page. Creating session variables allows you to store this information and make the information available to all the pages viewed by the user in your Web site. This saves the user from having to repeatedly enter the same information to display each page during a session.

A

value assigned to a session variable in any PHP page. Changes made to a variable will affect all the PHP pages that use the variable. You can use the session variable in your PHP pages as you would use any variable. The session_start function should be called at the beginning of every PHP page that will use session information. Calling the session_start function will have no effect if a session is already in progress. If the session_register function is used before the session_start function is called, a session will be started automatically. The use of session variables is an effective way of collecting and accessing information across multiple pages on a Web site and is more secure and easier to maintain than HTML hidden fields or cookies.

All session variables and the information stored in them will be discarded when the session ends or is terminated. If necessary, you can use cookies or a database to save the information stored in a session variable. The session_is_registered function can be used to determine if a variable has been registered as a session variable. The function will return a value of true if the variable has been registered in the current session.
Example: if (session_is_registered("userName")) { print "The user name has been registered."; } else { print "The user name does not exist in this Web site."; }

You can use the session_unregister function to remove a session variable you created in the current session.
Example: session_unregister("userName");

You use the session_register function to specify the name of the variable you want to create. The name of the session variable must be enclosed in quotation marks. Once the session variable has been registered, you can assign a value to the variable. The information stored in a session variable can come from sources such as forms, databases and cookies. After creating a session variable, you can use the session_register function to read the information stored in the session variable. You can also change the
CREATE A SESSION VARIABLE

To remove all the session variables that have been created for the current session, you can use the session_unset function. The session will remain open after you use the session_unset function, but the variables created during the session will no longer be available.
Example: session_unset();

READ A SESSION VARIABLE

⁄ To create a session variable, type session_register(). ¤ Between the parentheses, type a name for the session variable, enclosed in quotation marks. 154

‹ Type $ followed by the
name of the session variable. Then type = followed by the value you want to assign to the session variable.

› Display the PHP page in a Web browser.

I The session variable is now stored on the computer.

⁄ In the PHP page where you want to read information stored in a session variable, type session_register().

¤ Between the parentheses,
type the name of the session variable you want to read, enclosed in quotation marks.

› Display the PHP page in a Web browser.

I The Web browser displays the result of reading a session variable.

I String values must be
enclosed in quotation marks.

‹ Type the code that uses
the value of the session variable.

155

PHP

MANAGING COOKIES AND SESSIONS

7

SAVE SESSION INFORMATION TO A FILE

S

ession information you store in session variables will be available for the duration of the current session. If the session times out or is otherwise terminated by the Web server or client, any session information that has been created will be lost. If you want to be able to access session information after a session has ended, you can save the session information to a file. This is useful when you want to be able to restore the information for a client at a later time. To save session information to a file, you use the session_encode function to encode the information for the session in a string. After encoding the session information, you can write the string returned by the function to a file. You must use the fopen function to open the file and use the fputs function to write the encoded session information to the file. For more information about writing data to a file, see page 124.

The encoded session information saved in a file includes session information you have stored in session variables, but does not include the session ID of the current session. This enables you to restore the session variables to a new session that has a different session ID. For example, saving session information makes it easy to transfer the information between multiple Web servers used by the same Web site. When a user accesses a different Web server on the Web site, the session information saved in a file can be passed to the new Web server with the client, maintaining continuity even though a new session has been started on the second server. After saving session information to a file, you can have a PHP page restore the session information from the file. For information about restoring session information from a file, see page 158.

Saving session information to a file is an effective way of storing relatively small amounts of session information. If you plan to store large amounts of session information, you should consider storing the information in a database. A database provides a more efficient and versatile means of storing session information. In order to store session information in a database, your Web server must have database capabilities. If you do not want the file that stores session information to be overwritten each time a client visits the PHP page, you can append data to the file. This is useful when you want to store session information for multiple users in a single file. To access the information for a particular session later, you can search the file for a unique identifier for the information.

Saving session information to a file can be used in conjunction with, or as an alternative to, storing information in cookies. Saving session information to a file can be more reliable than using cookies to store information, since some users may disable cookies in their Web browsers.

SAVE SESSION INFORMATION TO A FILE

⁄ Type the code that creates the session variables you want to use to store session information.

I For information about creating session variables, see page 154.

¤ To be able to store the encoded session information in a file, type the code that opens the file for writing.

‹ To encode the session
information in a string, type session_encode().

› Type the code that
writes the string returned by the session_encode function to the file.

ˇ Type the code that closes the file.

Á Display the PHP page
in a Web browser.

I The session information has been written to the file.

156

157

PHP

MANAGING COOKIES AND SESSIONS
If you use the session_decode function within another function, the scope of the session variables restored from a file will be limited to that function. If you want to be able to use the session variables outside the function, you must use the global keyword to give the session variables returned by the session_decode function global scope.
Example: function getname() { $fp = fopen("sessionInfo.txt", "r"); global $userName, $location; session_decode(fgets($fp, 4096)); fclose($fp); }

7

RESTORE SESSION INFORMATION FROM A FILE
ou can have a PHP page restore session information you stored in a file. This allows you to make the session information from a previous session available to a new session. For example, if you saved session variables containing a user's login information to a file, you can restore the information when the user begins a new session. This saves the user from having to re-enter the information each time a new session is started. Restoring session information from a previous session does not alter the session ID for the current session.

Y

contains the session information you want to restore from the file. For more information about the fgets function, see page 126. When session information is restored from a file, the session variables stored in the file are automatically available to the PHP page. This means that you do not need to recreate the variables in the page. After storing session information in a file, a new session must be started before the session information can be restored from the file. You should use the session_start function on a PHP page that restores session information to start a new session. The session_start function must be placed before any HTML code on the PHP page. For more information about the session_start function, see page 152.

Session information stored in a file is encoded in a format that is easy to read and understand. You can open the file that stores session information in a text editor or word processor to view the session information before restoring the information in a PHP page. Viewing session information can be useful for troubleshooting session-related problems.
Example: userName|s:4:"Paul";location|s:8:"New York";

To restore session information from a file, you first open the file for reading using the fopen function. For more information about opening a file for reading, see page 126. The session_decode function can then be used to decode and restore the session information from the file. The session_decode function takes a string of text containing encoded session information as its argument. You can use the fgets function to retrieve the string that

As with any file you want to access from within a PHP page, the file that stores session information you want to restore must have the appropriate file and operating system permissions in order for you to retrieve information from the file. For more information about file and operating system permissions, consult the documentation for your Web server and operating system.

RESTORE SESSION INFORMATION FROM A FILE

⁄ To open the file that contains the session information you want to restore, type the code that opens the file for reading. 158

¤ To restore the session
information stored in the file, type session_decode().

‹ Between the parentheses, type the code that uses the fgets function to retrieve the information stored in the file.

› Type the code that
closes the file.

ˇ Type the code that uses
the session information restored from the file.

Á Display the PHP page
in a Web browser.

I The Web browser displays the result of restoring session information from a file.

159

PHP

DEMYSTIFYING OBJECTS

8

USING OBJECTS IN PHP
nlike C++ and Java, PHP is not a true object-oriented language; however, PHP does support object-oriented programming concepts that allow programmers to write code in an object-oriented fashion.

U

Objects, which are packages of code composed of data and functions that make use of the data, are the core features of object-oriented programming. In PHP, an object's members, or properties, are made up of the data for the object. An object also has member functions, or methods, that are used to manipulate the object. A class is PHP code that serves as a template for creating an object, which is also referred to as an instance of the class. It is possible to create many objects using the same class. Once created, each object can operate independently from other objects. To create a new object, you assign a new instance of a class to a variable. For example, you can assign the dir class to a

variable to create a dir object. The dir class is a built-in PHP class used to access the contents of a directory and is instantiated by specifying the path of the directory to be searched. When creating an object from a class you defined, you must include the new keyword. For more information about defining and using classes, see page 162. Once you create a new object, you can access the properties and methods of the object. For example, the path property of the dir object contains the path to the directory specified when the object was instantiated. The read method returns the names of the files in the directory one at a time. The close method is used to close the directory once all the files have been retrieved. To access an object's properties and methods, you use the variable that represents the object followed by the member access operator (->). You then indicate the property or method you want the object to access.

The key difference between traditional and object-oriented programming is the way data and the functions that process the data are organized. Using traditional programming methods, an application is generally created as one large program, with no division between the functions of the application. For example, a shopping cart program may be designed as a single program containing customer information, item inventory and shipping functions. A slight change made to one portion of the program may greatly affect the rest of the program, which can make the program difficult to manage. Using object-oriented programming, however, allows you to structure and organize code in your applications into distinct modules, or objects. The variables and functions that deal with a specific feature, such as shipping, can be maintained separately from the other components. This can make the application easier to manage, especially if there are multiple programmers working on the same application.

One of the benefits of object-oriented programming is known as data hiding, or the black box concept. Data hiding makes classes easier to use by hiding the fields and methods of the classes from other parts of the program. The program then has to know only how to access the class, not the internal workings of the class. Data hiding is often used in programs to protect classes from tampering and to ensure that the methods of the classes are used are originally intended. A programmer can modify and maintain the code within the class without affecting the programs that use the class. This also helps ensure that objects developed by multiple people are compatible.

USING OBJECTS IN PHP

⁄ To create an object, type a variable name for the object followed by =. ¤ Type the name of the class that you want use to create the object, followed by (). 160

‹ Between the parentheses, type any arguments needed to create the object.
Note: In this example, the path of the directory is included as an argument.

› To access a property of the object, type the name of the variable that contains the object, followed by –>.

ˇ Type the name of
the property you want to access.

Á To call a method of the object, ‡ Type the name of the method
you want to call followed by ().

° Repeat steps 6 and 7 type the name of the variable that for each method you contains the object followed by –>. want to call. · Type the code that
uses the accessed properties and the called methods of the object.

‚ Display the PHP page
in a Web browser.

I Repeat steps 4 and 5 for each property you want to access.

I The Web browser displays the result of using the properties and methods of an object.

I Type any arguments for the method between the parentheses.

161

PHP

DEMYSTIFYING OBJECTS

8

DEFINE A CLASS

Y

ou may define a class that will serve as a template for an object. Classes are defined using the keyword class followed by the class name. The class name must begin with a letter followed by any combination of letters, numbers or underscore characters. Class names are case-insensitive, but it is good programming practice to use a consistent format for naming classes you define. The name of the class is followed by a pair of braces {}. The code between the braces is referred to as the body of the class and may consist of properties, which are the data for the object, and methods, which are the structures that contain the code for specific actions. For information about defining methods, see page 164. You can define properties for a class you create by using the keyword var followed by a name for the property preceded by a dollar sign ($). You may then assign an initial value to the property or leave the property unset. The value

you assign to the property can be any data type, such as integer, floating-point number, string, array or boolean. You may define as many properties in a class as needed. All properties should be declared at the beginning of the class definition. Once a class has been defined, you can create an object from the class. You create a variable to store the object and then use the new keyword followed by the name of the class to create an object. You can also access the properties of the class in the object. To access the properties, use the variable that represents the object followed by the member access operator (->). You can then indicate the property you want to access. When accessing a property, the property name must be typed exactly as it was specified in the class definition, without the dollar sign ($).

When assigning an initial value to a property of an object, you must indicate a literal value. An error will occur if you attempt to set the initial value of a property using a value obtained from a function, another variable or an expression with operators. If a value needs to be obtained from a function or an expression, you should use a method to assign the value to the property. The following example shows property declarations that will cause errors.
Example: class Fruit { var $name = "Granny" . "Smith"; var $type = $name; var $soldOn = time(); var $quantity = 1 + 1; }

Although PHP allows you to set the property of an object using the assignment operator (=), this practice is not recommended and should be avoided. In object-oriented programming, only an object's methods should be used to access and alter the object's properties. This helps protect classes from tampering, which may cause an object to work improperly.

DEFINE A CLASS

⁄ Type class followed by the name of the class you want to create. Then type the opening and closing braces for the class. 162

¤ To define a property of
the class, type var followed by $ and the name of the property.

› Repeat steps 2 and 3 for each property you want to define.

CREATE AN OBJECT USING A CLASS

ACCESS PROPERTIES OF AN OBJECT

· Type the code that
uses the accessed property.

— Display the PHP page
in a Web browser.

ˇ Type the variable name
for the object followed by =.

‡ Type the name of the
variable that contains the object followed by –>.

‹ To assign a value to the
property, type = followed by the value you want to assign.

‚ Repeat steps 7 to 9
for each property you want to access.

I The Web browser displays the result of defining and using a class.

Á Type new followed by
the name of the class you want to use to create the object.

° Type the name of the
property you want to access.

163

PHP

DEMYSTIFYING OBJECTS
You can set the values for an object's properties by using a constructor method. A constructor method is a special type of method that is always executed each time the class is accessed and an object is created. This makes constructor methods useful for performing initialization tasks for a new object. A constructor method must have the same name as the class for which it is the constructor. You can also call a constructor method after an object has been created. The body of a method is enclosed in braces {}. Within the body of a method, you can use the special variable $this to set or access the value of a property. The special variable $this is followed by the member access operator (->) and the name of the property. To set a new value, you then include the assignment operator (=) followed by the new value for the property. Similar to functions, methods may return a value using a return statement. When accessing a property of an object, you would ideally use a method that returns the value of the property rather than referring to the property directly. This practice of accessing the properties of an object through a method does not have to be strictly adhered to, but it is a more proper way of writing object-oriented programs.
TYPE THIS: class Fruit { var $name; var $color; var $saleDate; function Fruit($name, $color) { $this->name = $name; $this->color = $color; $this->saleDate = time(); } function PrintName() { print "<b>Fruit:</b> " . $this->name . "<br>"; } } $fruitObject = new Fruit("apple", "red"); $fruitObject->PrintName(); $fruitObject->Fruit("mango", "green"); $fruitObject->PrintName(); RESULT:

8

DEFINE A METHOD
fter defining a class, you can define the methods for the class. You can use methods to perform any number of tasks that relate to an object. For example, you may want to define a method that sets the properties of an object or displays the current values of the object's properties. A method is created using the function keyword followed by the name of the method and a set of parentheses. You can set up a method to accept arguments. In the function statement, you define one or more variables between the parentheses that follow the method name. Each variable represents an argument you will pass to the method. You can use the variables you create in the function statement within the body of the method. When specifying the arguments of a method, you may specify a default value for an argument of the method. You use the assignment operator (=) to assign a default value to the argument.

A

Fruit: apple Fruit: mango

DEFINE A METHOD

⁄ Type the code that defines a class. ¤ To define a method, type
function followed by the

‹ To allow the method to
accept arguments, type the names of the variables you want to store the arguments. Separate each argument with a comma.

name of the method you want to define. Then type ().

ˇ Type the opening and closing braces of the method body. The code you want the method to execute is placed between the braces.

Á To have the method
set the value of a property, type $this–> followed by the name of the property. Then type = followed by the value or variable you want to use.

‡ To define a method
that accesses properties of the class, repeat steps 2 to 5.

° To have the method
access the value of a property, type $this–> followed by the name of the property you want to access.

· Repeat steps 2 to 5 for
any other methods you want to create.

‚ To return a value from a
method, type return in the body of the method, followed by the information you want the function to return.

I You can now call a method in the PHP script. See page 166 to call a method.

› To set a default value for an
argument, type = followed by the default value after the argument.

164

165

PHP

DEMYSTIFYING OBJECTS
You can define a method that returns the value of a property or calls a method by specifying the name of the property or method as an argument. The name of the property or method is stored in a variable, which is used to access the value of the property or call a method in the body of another method. The variable name is used in place of a literal property or method name. This is useful when you want to dynamically access an object's property or call an object's method.
TYPE THIS: class Fruit { var $name; var $color; function Fruit($name, $color) { $this->name = $name; $this->color = $color; } function GetProperty($propertyName) { return $this->$propertyName; } } $fruitObject = new Fruit("Apple", "Red"); print $fruitObject->GetProperty("color") . " "; print $fruitObject->GetProperty("name"); RESULT:

8

CALL A METHOD

A

fter creating an object in your script, you can call the object's methods. Calling a method tells PHP to access and execute the code in the method.

To call a method, you type the name of the object followed by the member access operator (->) and the name of the method where you want to execute the code. The method name is followed by a set of parentheses. If the method was set up to accept arguments, you specify the arguments you want to pass to the method between the parentheses. A method can be accessed from within the body of another method in the class definition. This is useful for defining a method that is to be used only within the class itself, such as a method used to perform internal calculations. This type of method is referred to as a private method. Private methods typically contain code that is repeatedly used in a class. Private methods are also useful for breaking up methods containing a large amount of code, which improves the readability of the code.
CALL A METHOD

The special variable $this must be used when calling a private method within the body of another method. The special variable $this is followed by the member access operator (->), the name of the method and a set of parentheses. You may place any required arguments between the parentheses. Unfortunately, PHP does not make any distinctions between the different methods that you define. There is no mechanism in PHP that will allow you to restrict the access of certain methods to within the class itself. This makes it possible to misuse code. To help avoid misuse, you should include clear, descriptive comments in your code to label private methods so they are not used outside the class definition.

Red Apple

⁄ Type the code that creates a class and its methods.

¤ Type the code that
creates an object.

‹ To call a method of the object, type the name of the object followed by –>. Then type the name of the method followed by ().

› Between the parentheses, type the arguments you want to pass to the method. Separate each argument with a comma. ˇ Repeat steps 3 and 4 for each method you want to call.

Á To call a private method
within another method of the class, type $this–> followed by the name of the method. Then type ().

° Type the code that uses the result of calling the private method. · Repeat steps 6 to 8 for each private method you want to call.

‚ Display the PHP page
in a Web browser.

I The Web browser displays the results of calling the methods of an object.

‡ Between the parentheses,
type the arguments you want to pass. Separate each argument with a comma.

166

167

PHP
A class you defined as a child class can be used as the parent class of another class. This allows you to create a chain of child classes and parent classes. Although there is no limit to the number of child classes that can be created from other child classes, you should try to limit the chain of extensions to prevent your code from becoming too confusing. You should also place information about the parent class in the child class definition to prevent potential conflicts from occurring.
Example: class Spread extends Fruit { // Inherited from Fruit // Properties: name, color // Methods: Fruit, PrintMessage . . . } class Sandwich extends Spread { // Inherited from Fruit and Spread // Properties: name, color, type // Methods: Fruit, PrintMessage . . . }

DEMYSTIFYING OBJECTS
It is good programming practice to design classes so they perform only a general set of tasks. Specialized methods can then be added by extending the parent class. This prevents the parent class from becoming bloated and maximizes the re-usability of code while maintaining the code's speed and efficiency. When a class becomes too large, more memory and resources are used by an object of the class. Extending a class also maintains the integrity of the parent class. This ensures that new modifications will not have any adverse effects on the rest of the program.

8

EXTEND A CLASS

I

f a class you are defining is related to a class you have previously defined, you can make the new class an extension of the original class. This allows you to re-use properties and methods of the original class without having to retype the code in the new class. When you extend a class, the base class is usually referred to as the parent class, while the new class is called the child class.

a constructor method must be defined for the child class. In the constructor method of the child class, you must call the constructor method of the parent class using the special variable $this and indicate the appropriate arguments. For more information about the constructor methods, see the top of page 165. When creating a child class, you can override a method in the parent class that you do not want to be available when the child class is accessed. To override a method in the parent class, you must create a method in the child class that has the same name as the method you want to override. When an object is created using the child class, the method in the child class will be available instead of the method in the parent class.

When defining a class you want to use as a child class, you must use the extends keyword to specify the name of the class that will act as the parent class. When the child class is used to create an object, the resulting object inherits the properties and methods of the parent class in addition to any new properties and methods indicated in the child class. If the parent class has a constructor method, the constructor method is not automatically called when a new instance of the child class is created. If you want the constructor method to execute for each instance of the child class,

EXTEND A CLASS

⁄ Type the code that defines a class you want to be able to extend to another class. ¤ Type the code that defines a class you want to use as an extension of another class. 168

‹ In the class definition,
type extends followed by the name of the class you want to use as the parent class.

› To call the constructor method of the parent class within the constructor method of the child class, type $this–> followed by the name of the constructor method from the parent class.

ˇ Enclose any
arguments for the method in parentheses.

Á In the child class, you
may define a method that overrides one of the methods in the parent class. Note: The method must have the same name as the method in the parent class that it overrides.

‡ Type the code that creates an object using the child class. ° Type the code that calls a method of the object.

· Display the PHP page
in a Web browser.

I The Web browser displays the result of creating an object of a child class and accessing its methods.

169

PHP

DEMYSTIFYING OBJECTS

8

WORK WITH EXTERNAL DATA IN CLASSES

A

class can access functions, constants and variables that were created outside the class definition. This is useful for re-using data in your PHP script.

A function that is located outside a class definition can be called in a method by simply specifying the name of the function and any arguments the function requires. This is useful when you already have a library of useful functions that you do not want to retype as private methods of a class. Some functions also will not work properly if they are within a class definition. For example, when using the usort function in a method, you need to pass a comparison function located outside of the class definition as an argument for the comparison function to be used properly. To access a constant defined outside the class definition, you need to specify only the name of the constant. The constant definition must be placed before the class definition in the PHP script.

You can also access variables that are defined outside a class definition. The global keyword is used to make an external variable accessible to a method of a class. This is useful in cases where passing values to a class through a method is not practical, such as when you want to process an undetermined number of values from a form. You should keep in mind that a class becomes less portable when it is dependent on external data. You should use external data only when necessary. When using external data, you may also want to place comments in the class definition to indicate how constants, global variables or functions are being accessed. Comments will help avoid confusion and make potential problems easier to track.

You can place a class definition in an include file to make the class accessible to multiple PHP pages. You can name the include file using the same name as the class followed by the .inc extension. When placing a class definition in an include file, you must remember to enclose the class definition within the <?php and ?> delimiters. As with functions, classes can be declared only once in a script. To include a class file in a script, you can use the include_once statement.
Example: include_once("Fruit.inc"); include_once("Vegetable.inc");

As the complexity of your Web site increases, you may find it more practical to use include files to organize constants, functions and classes used in your PHP pages. You must keep track of any dependencies that your PHP pages have on those constants, functions and classes. As a general rule, in a PHP page, you should specify the include files for constants first, followed by the include files for functions and then the include files for class definitions.
Example: // Constants include_once("color_constants.inc"); include_once("font_constants.inc"); // Functions include_once("text_formatting_functions.inc"); // Classes include_once("Fruit.inc"); include_once("Vegetable.inc");

WORK WITH EXTERNAL DATA IN CLASSES

⁄ Type the code that creates any constants, variables and functions that will be used in a class. ¤ Type the code that
defines a class.

‹ To call a function created
outside the class definition, type the name of the function followed by ( ).

ˇ Repeat steps 3 and 4 for each function you want to call in the class. Á To use a constant defined outside the class definition, type name of the constant.

‡ Type the code that uses the constant.

° To access a variable
defined outside the class definition, type global followed by the name of the variable.

‚ Type the code that
creates an object and calls a method of the object.

— Display the PHP page
in a Web browser.

I The Web browser displays the result of using external data in a class.

› Between the parentheses,
type any arguments for the function.

· Type the code that
uses the variable.

170

171

PHP

DEMYSTIFYING OBJECTS

8

GET INFORMATION ABOUT AN OBJECT
HP provides several functions that allow you to obtain information about an object. You can use the functions to examine the attributes of an object without having to manually read through its class definition. This can save you time and effort, especially if you are working with include files. You can also use the functions to automate some tasks, such as generating documentation for your programs. This can help you avoid conflicts when naming methods and properties. You can use the get_class function to obtain the class name of an object. The get_class function takes the variable that contains the instance of the object you want to check as its argument. The function returns the name of the class the object belongs to. You can obtain a list of the properties of an object by using the get_object_vars function. To use this function, you must specify the variable that contains the instance of the

P

object you want to check. The get_object_vars function returns an associative array containing the object's properties, including any properties inherited from parent classes. The keys of the array contain the property names and the values of the array contain the current values of the properties. Properties that do not have an assigned value are not returned in the array. To obtain the methods of an object, use the get_class_methods function. To use the get_class_methods function, you need to specify the name of the class from which you want to get the list of methods. If you do not know the class name, you can use the get_class function to determine the class name of the object and then use the result in the get_class_methods function. The get_class_methods function returns an array of methods in the specified class, including any methods inherited from parent classes.

You can use the get_class_vars function to obtain the default values of the properties of a specified class. The function returns an associative array whose keys are the property names and whose values are the default property values. Properties that do not have a default value specified are not included in the array.
TYPE THIS: class Fruit { var $name = "apple"; var $color = "red"; var $size = "large"; var $onSale; } $fruitObject = new Fruit; print "<b>Default property values of Fruit:</b><br>"; foreach(get_class_vars("Fruit") as $propertyName => $defaultValue) { print "$propertyName is $defaultValue<br>"; } RESULT: Default property values of Fruit:

name is apple color is red size is large

GET INFORMATION ABOUT AN OBJECT

⁄ Type the code that defines a class and creates an instance of the class. ¤ To determine which class an object belongs to, type get_class(). 172

‹ Between the parentheses,
type the name of the object you want to check.

ˇ To determine the properties of an object, type get_object_vars(). Á Between the parentheses, type the name of the object you want to check.

‡ Type the code that uses
the get_object_vars function.

° To determine the
methods of an object, type get_class_methods().

› Type the code that uses the get_class function.

· Between the
parentheses, type the name of the class from which the object was instantiated.

I If you do not know the name of the class, use the get_class function as the argument.

— Display the PHP page
in a Web browser.

I The Web browser displays the results of retrieving information about the object.

‚ Type the code that uses the get_class_method function.

173

PHP
The is_subclass_of function is used to determine if an object was created using a child class of a specified parent class. The is_subclass_of function takes two arguments––the name of the variable that stores the object and the name of the parent class you want to check, enclosed in quotation marks. If the object was
TYPE THIS: class Spread extends Fruit { var $type; function Spread($name, $color, $type) { $this->Fruit($name, $color); $this->type = $type; } } $spreadObject = new Spread("apple", "red", "jelly"); if (is_subclass_of($spreadObject, "Fruit") == TRUE) { print "Fruit is a parent of Spread."; } else { print "Fruit is not a parent of Spread."; }

DEMYSTIFYING OBJECTS
created using a child class of the specified parent class, the function will return a value of true. The parent class being checked does not have to be an immediate parent of the child class. If the parent class being checked is a number of levels above the child class, the function will still return a value of true.
RESULT:

8

CHECK FOR CLASSES AND METHODS IN A SCRIPT
here are several functions available that you can use to check for the presence of classes and methods in your script. These functions are useful for troubleshooting large, complex PHP scripts. Using functions to test for certain conditions can save you from having to examine every line of code in a script. The get_declared_classes function is used to determine the classes that are currently being used in the script. There are no arguments required when calling the get_declared_classes function. The get_declared_classes function returns an array containing the names of the classes being used in the script. When viewing the array elements returned by the get_declared_classes function, you may see classes that you have not defined. These are built-in classes in PHP. You may want to keep these built-in
CHECK FOR CLASSES AND METHODS IN A SCRIPT

T

classes in mind so you do not inadvertently define any classes with the same name as the built-in classes. You can use the class_exists function to check if a particular class has been defined in the script. When using the class_exists function, you must specify the name of the class you want to check, enclosed in quotation marks, as an argument. The class_exists function will return a value of true if the specified class has been defined in the script. The method_exists function is used to determine if a particular method belongs to an object. The method_exists function takes two arguments––the name of the variable that contains the object and the name of the method you want to check, enclosed in quotation marks. The method_exists function will return a value of true if the specified method is part of the class used to create the object.

Fruit is a parent of Spread.

⁄ Type the code that defines a class and creates an instance of the class.

¤ To get a list of classes
used in the script, type get_declared_classes().

› To check if a class has been defined, type class_exists( ). ˇ Between the parentheses, type the name of class you want to check, enclosed in quotation marks.

Á Type the code that
uses the class_exists function.

‡ To check if a specific
method exists in an object, type method_exists().

· Type the name of the
method you want to check, enclosed in quotation marks.

— Display the PHP page
in a Web browser.

‹ Type the code that uses the
get_declared_classes function.

° Between the parentheses,
type name of the object followed by a comma.

‚ Type the code that uses
the method_exists function.

I The Web browser displays the results of checking for classes and methods in the script.

174

175

PHP

WORK WITH DATABASES

9

INTRODUCTION TO DATABASES

TYPES OF DATABASES

O

ne of the most useful features of PHP is the ability to access a database. Databases store and manage large collections of information. PHP pages can be used to make this information available to the users who visit your Web site. Instead of storing information in text files or static Web pages, a PHP page can be set up to retrieve, format and display data from a database. When a user accesses the

PHP page, the information in the PHP page will be created from the current information in the database. A PHP page can also allow users to manipulate the data in a database. Using databases to store information and then using PHP pages to access that information is an efficient method of displaying up-to-date information in a Web site.

The type of database you are using determines the structure of the database and the way data is organized in the database. A database with a simple structure allows you to access data quickly, but manipulating the data may be difficult. A database with a more complex structure allows you to easily manipulate data, but requires more

resources. When selecting a database, you should consider the amount of data that will be stored and how the data is going to change over time. PHP is commonly used with flat file, hierarchical and relational databases.

Flat File Databases
DATABASE STRUCTURE

Information in a database is made up of two components––raw data and meta-data. The raw data component of a database is the actual information being stored, such as the phone number of a client. The meta-data component of a database determines the way the data is structured and organized. For example, data in a database is usually organized into tables, which consist of fields and records. A field is a specific

category of information in a table, such as the first names of all your clients. A record is a collection of information about one person, place or thing, such as the name and address of a client. More sophisticated databases would also contain meta-data such as data types and the relationship between tables.

Flat file databases are the most basic database type. Flat file databases have minimal structure and usually store information in one large table, similar to a tab-delimited text file. A flat file database is very easy to set up and is ideal for creating simple Web applications that use small amounts of data, such as an application that keeps track of user preferences.

When working with larger applications, a flat file database can be inefficient and difficult to maintain. The simple structure of a flat file database makes it inadequate for storing complex relationships, resulting in the duplication of information. Also, if your data storage requirements change, a flat file database can be very difficult to modify.

Hierarchical Databases A hierarchical database organizes data into different levels, similar to directories and sub-directories. This organization makes data access fast and easy. You would typically use a hierarchical database to store large amounts of information that seldom need to be changed, such as contact lists or user directories. Some of the hierarchical databases supported by PHP use the Lightweight Directory Access Protocol (LDAP). This protocol was designed specifically for reading data quickly. You can use PHP's LDAP functions to access these types of databases. Due to its rigid structure, manipulating data in a hierarchical database can be very slow. Data redundancy can also be problem. For example, if you organized customers by method of payment in a hierarchical database, a customer who pays by both cash and credit card would have two accounts. Data redundancy makes hierarchical databases inefficient for certain applications.

DATABASE MANAGEMENT SYSTEM (DBMS)

To access and modify the data in a database, you need a program or set of programs called a DataBase Management System (DBMS). Depending on the type of database you are using, the DBMS can be very simple or very sophisticated. For example, you can

write your own DBMS in PHP for a flat file database. You can also obtain a DBMS, such as MySQL or Oracle, which is capable of handling more complex databases.

ACCESSING A DATABASE

Relational Databases you are using. For example, if you are using a MySQL database, you would use PHP's MySQL functions. If the database you are using does not have its own set of functions, you can use PHP's Unified ODBC functions to connect to the database. ODBC, or Open DataBase Connectivity, is a standard supported by many databases. Relational databases store information in separate tables. Each record in a table has a unique identifier, or primary key, which can be used to form relationships with entries in other tables. Using relationships to bring together information from different tables eliminates data redundancy. Relational databases are powerful, flexible and effectively store large amounts of information. A relational database is also faster and easier to maintain than other types of databases. You would typically use a relational database when building dynamic database-driven Web sites with PHP.

The way you access a database depends on the type of database you are using. You can use PHP's Filesystem functions to directly access a flat file database. For other types of databases, you must create a connection to the database before you can access the database. To create a connection to a database, you use the set of PHP functions specifically written to work with the database

176

177

PHP

WORK WITH DATABASES

9

PLAN A DATABASE
ou should take the time to properly design a database, especially when working with a relational database management system. A good database design ensures that you will be able to perform tasks efficiently and accurately. As you add information to a database, the database becomes larger and more complex. A database

SELECT A DATABASE MANAGEMENT SYSTEM
that is designed properly will be easier to modify and work with as it grows. Good planning can also make it easier for other users to work with a database you create.

Y

P

HP supports a wide variety of DataBase Management Systems (DBMS) that you can use to store and manage information you want to make available in your PHP pages. When choosing a DBMS, you should consider a number of factors, such as your budget and the volume of information the database will be required

to handle. You should also consider the ease with which you will be able to move data to a more robust system if the database grows beyond the capabilities of the current system. If the DBMS you use does not support accepted standards, moving data to a new system might be difficult.

Determine the Purpose of the Database Decide what you want the database to do and how you plan to use the information. If other people will be using the database, you should consult with them and consider their needs. This can help you determine what information you need to include to make the database complete. Security and Reliability You should determine the level of security you will need to protect the information the database will store. If the database will store sensitive information such as credit card numbers, you need to select a database system that is secure and reliable. To ensure maximum security, you may even want to create a separate database to store sensitive information. Anticipate Future Needs Decide on a naming convention for databases, tables and fields. Make sure names are concise and descriptive to prevent confusion in case changes need to be made in the future. If many people will work with the database, you should also decide on a method for documenting changes made to the database. For example, you can use a spreadsheet program to keep track of the dates and times changes were made and the name of the person who made the changes.

Determine the Tables You Need Gather all the information you want to store in the database and then divide the information into separate tables. A table should contain related information about one subject only. The same information should not appear in more than one table in a database. You can work more efficiently and reduce errors if you need to update information in only one table. Consider the Fields You Need Each field should relate directly to the subject of the table. When adding fields, make sure you break down information into its smallest parts. For example, break down names into two fields called firstName and lastName. Try to keep the number of fields in a table to a minimum. For example, do not include a field containing data you can calculate from other fields. Tables with many fields increase the time it takes to process information in a database. Determine the Relationship Between Tables A relationship tells a relational database how to bring together related information stored in separate tables. You can use the primary key to form a relationship between tables. A primary key is one or more fields that uniquely identifies each record in a table. For example, the primary key for a table of employees could be the social security number of each employee.

MySQL MySQL is the database program most commonly used to develop database-driven PHP Web sites. MySQL is a fast, efficient program that is available for use on Unix and Windows computers. MySQL is suitable for small to medium-sized projects and requires very few system resources to run. MySQL is also an Open Source product, which means you can use it free of charge. Although MySQL is very powerful, it is relatively easy to install and manage. This makes it a good program for new developers to use when learning to work with databases using PHP. More information about MySQL is available at the www.mysql.com Web site. PostgreSQL PostgreSQL is another popular DBMS used with PHP. Like MySQL, PostgreSQL is an Open Source product that is freely available for personal and commercial use, but PostgreSQL is a more advanced system that supports almost all SQL features. PostgreSQL is available for use only on Unix systems and is usually included with the RedHat distribution of the Linux operating system. For more information about PostgreSQL, you can visit the www.postgresql.org Web site.

Oracle Oracle is a powerful database program that is typically used with high-end Web servers on large commercial Web sites, such as sites that offer online shopping. Oracle is reliable, provides advanced security, is highly scalable and includes powerful tools that you can use to manage your database. Oracle is available for both Unix and Windows computers. For more information about the Oracle database program, you can visit the www.oracle.com Web site. Microsoft SQL Server Microsoft SQL Server is an industrial-strength DBMS that offers features that are comparable to Oracle. SQL Server includes advanced features, such as OnLine Analytical Processing (OLAP) and data mining, which allow you to work more efficiently with information in a large database. SQL Server is only available for use with Windows systems. For more information about SQL Server, you can visit the www.microsoft.com/sql Web site. Microsoft Access Microsoft Access is a database program that is useful for small to medium-sized applications. Access is available as a stand-alone product or as part of the Microsoft Office package. There are currently no built-in PHP functions that allow you to connect to an Access database from a PHP page, so you must use PHP's Unified ODBC functions to connect. For more information about PHP's Unified ODBC functions, you can visit the www.php.net/manual/en/ref.odbc.php Web site. Information about Access is available at the www.microsoft.com/access Web site.

178

179

PHP

WORK WITH DATABASES

9

SQL STATEMENTS

INTRODUCTION TO STRUCTURED QUERY LANGUAGE

SQL is made up of many statements and clauses. In order to work with a database in your PHP scripts, you will need to be familiar with some common SQL statements and how they are used.

CREATE TABLE The CREATE TABLE statement is used to create a new table in a database. You indicate the name of the table you want to create after the CREATE TABLE statement and then specify the fields you want to include in the table. You also specify a description of each field that includes the data type of the field and other attributes, such as the maximum number of characters the field can hold. The data types you specify will depend on the database you are using. You should refer to the database documentation for more information.
Example: CREATE TABLE orders ( invoiceNumber INT(8), orderDetails CHAR(255), totalCost FLOAT(9, 2) )

SELECT The SELECT statement allows you to retrieve data from a database. You specify the names of the fields from which you want to retrieve data after the SELECT statement. The SELECT statement uses the FROM clause to specify the name of the table that stores the data you want to retrieve. The WHERE clause specifies exactly which data you want to retrieve.
Example: SELECT invoiceNumber, totalCost FROM orders WHERE totalCost > 100.00

R

elational database management systems, such as MySQL and Oracle, are usually used for building dynamic, database-driven Web sites with PHP. In order for a PHP script to work with data in a relational database, the script must be able to communicate with the database. Structured Query Language (SQL) is the language used in a PHP script to communicate with a database.

Originally developed by IBM as a database query language for use with mainframe computers, SQL was soon adopted by many vendors for use with their relational database management systems. Most relational database management systems that have a client/server structure now support SQL.

Standardization SQL is the industry standard language for managing and manipulating data in a database. SQL can be used to work with many types of databases, which makes it easy to upgrade from one database management system to another. For example, a small Web site might start out using MySQL but then grow large enough to require a database created using Oracle. You have to learn only one language to have your PHP scripts communicate with both types of databases. Ease of Use SQL uses many easy-to-understand commands, which makes it a very simple language to work with. For example, SQL uses the INSERT statement to add information to a database and the DELETE statement to remove information. These plain-language commands make it easy for you to read and determine the purpose of SQL code. Power Although SQL is easy to use, it is a very powerful language. As well as being suitable for retrieving data from a database and performing simple tasks such as adding and deleting records, SQL can be used to perform complicated procedures, such as compiling different types of data from multiple data sources.

Flexibility The ability to easily manipulate data into many useful forms makes SQL a very effective tool. SQL allows you to easily format data you retrieve from a database in a variety of ways. You can sort data in a specific order, create summaries and combine information from different fields. This saves you from having to expend additional time and resources to format the retrieved data in PHP. Vendor Specifications Although many of the basic concepts of SQL, such as selecting and inserting data, are common to most database management systems, certain features may vary depending on the vendor of the system. For example, a database may include a unique set of commands that allow users to access information about a table. These commands may not work for other databases since they are not part of the standard set of SQL statements. The types of information that a database can store may also vary depending on the vendor.

Result Set The SELECT statement returns data in a table format called a result set. The fields you specify make up the columns of the table and the information from each field forms the rows. For example, when you issue a SELECT statement that retrieves the invoice numbers for orders totaling less than $100 from a table in a database, the result set will display a table with two columns that show the invoice numbers and the amounts. The SELECT statement allows you to access different groups of data from one or more tables and display the data in a single result set. You can indicate parameters with the SELECT statement, such as a specific sorting order, to control the way the data is displayed in the result set. DELETE The DELETE statement is used to remove data from a database. The DELETE statement uses the FROM clause to specify the name of the table that stores the data you want to delete. The WHERE clause contains information that uniquely identifies the data you want to delete.
Example: DELETE FROM orders WHERE year < 1996

INSERT The INSERT statement allows you to add records to a database. The INSERT statement uses the INTO clause to specify the name of the table to which you want to add data and the names of the fields that store the data in the table. The VALUES clause specifies the values you are adding.
Example: INSERT INTO orders (invoiceNumber, totalCost) VALUES (12843, 34.56)

UPDATE The UPDATE statement is used to modify data in a database. You indicate the table that contains the data you want to modify after the UPDATE statement. The UPDATE statement uses the SET statement to indicate which field needs to be changed and the new value. The WHERE clause is then used to specify the data to be modified.
Example: UPDATE orders SET totalCost = 55.66 WHERE invoiceNumber = 12843

180

181

PHP

WORK WITH DATABASES

9

USING A DATABASE CLIENT
he most popular relational DataBase Management Systems (DBMS) have a client/server architecture. A client/server architecture allows multiple users to simultaneously connect to a single database. Compared to other database management systems, this type of system is extremely cost effective and offers a high level of performance. The server component of the DBMS contains the actual database. The server software interprets commands from users and then manages the data in the database accordingly. The client component of the system provides the interface needed to work with the server. You can issue Structured Query Language (SQL) statements from a text-based client to perform tasks such as displaying a list of the databases on the server, finding a list of the tables in a database or viewing the contents of a table. You can also use the client software that came with your DBMS to set up a database. While it is possible to perform tasks such as creating the tables for a database by issuing
USING A DATABASE CLIENT
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 7 to server version: 3.23.33 Type 'help;' or '\h' for help. Type '\c' to clear the buffer mysql> SHOW DATABASES; Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 7 to server version: 3.23.33 Type 'help;' or '\h' for help. Type '\c' to clear the buffer mysql> SHOW DATABASES; +--------------+ | Database +--------------+ | books | school | shopping | video +--------------+ 4 rows in set (0.00 sec) mysql> USE school; Database changed mysql> SHOW TABLES;

T

SQL statements from a PHP script, this process is often more difficult and time consuming than using the client software. Typically, client software can also be used to perform administrative duties, such as adding users to the system, provided the correct access privileges have been granted. When a DBMS is installed on a server, both the server and client software are installed. To access the server from a remote computer, only the client software is required on the computer. The operating system of some client computers may have to be altered in order to work properly with the client software. For more information, consult the documentation that came with your DBMS. Before using the client software to work with a database, you must make sure that both the client and server software are running. It is a common error to launch the client software without launching the server software first.

To access a database server from a remote computer, you must connect to the server through a local area network or Internet connection. To do so, you need to know the address of the server and login information, such as a user name and password. If you are using an Internet Service Provider (ISP) to run your PHP scripts, you will typically have access to a database server, although there may be additional costs for the server's use. You can consult your ISP to obtain more information about connecting to the database server. You may want to type your SQL statements in a text editor and then copy and paste the statements into the client software. Typing long SQL statements directly into client software can be a slow and tedious process. If you make a mistake that generates an error, you will have to retype the entire statement again. When working in a text editor, you can easily edit your SQL statements and even save the statements for later use.

In addition to text-based client software, most relational database management systems also include a client that utilizes a Graphical User Interface (GUI). You can use GUI client software to modify and administer a database without having to type SQL statements. This type of client software is much easier to use than a text-based client and can help you quickly set up a database.

Type 'help;' or '\h' for help. Type '\c' to clear the buffer mysql> SHOW DATABASES; +--------------+ | Database | +--------------+ | books | school | shopping | videos +--------------+ 4 rows in set (0.00 sec) mysql> USE school; Database changed mysql> SHOW TABLES; +-------------------------+ | Tables_in_school | +-------------------------+ | courses | | students | +-------------------------+ 2 rows in set (0.06 sec) mysql> SELECT * FROM students;

| students | +--------------------+ 2 rows in set (0.06 sec) mysql> SELECT * FROM students; +--------------+-------------+------------------+ | studentID | firstName | lastName | +--------------+-------------+------------------+ | 10293843 | Martine | Edwards | | 01298348 | Lindsay | Sandman | | 10562940 | Sandy | Rodrigues | | 38290169 | Barry | Pruett | +--------------+-------------+-----------------+ 4 rows in set (0.00 sec) mysql> CREATE TABLE teachers -> ( -> teacherID CHAR(4), -> firstName CHAR(20), -> lastName CHAR(25) -> ); Query OK, 0 rows affected (0.05 sec) mysql> INSERT INTO teachers (teacherID, firstName, lastName) -> VALUES ("2323", "Maureen", "Spears");

⁄ Locate and start the client software for your database management system.

I The database server you want to connect to must be running.

I A list of the databases on the server appears.

› To display a list of
the tables in the current database, type SHOW TABLES; and then press Enter.

I A list of the tables in the database appears.

¤ To display a list of the
databases on the server, type SHOW DATABASES; and then press Enter.

182

‹ To select the database you want to work with, type USE followed by the name of the database and a semicolon. Then press Enter.

ˇ To display the contents of a table, type SELECT * FROM followed by the name of the table whose contents you want to view. Then type a semicolon and press Enter.

I The contents of the table appear.

Á To create a new table in the
current database, type CREATE TABLE followed by the name of the table you want to create. Then press Enter.

‡ Type the code that creates fields and records for the table.
I The new table is created and added to the database.

183

PHP

PHP AND MYSQL

10

CONNECT TO A MYSQL SERVER

T

o enable a PHP page to access a database stored on a MySQL server, you must create a connection to the server. The mysql_connect function allows you to create a connection to a MySQL server. The mysql_connect function takes three arguments––the host name or IP address of the computer running the MySQL server, a user name and a password. If the MySQL server is running on the same computer as the Web server, you can specify the host name localhost or the IP address 127.0.0.1 to connect to the MySQL server. If the MySQL server does not require a user name and password, you can enter empty strings ("") for these arguments. When a connection to the MySQL server is made successfully, the mysql_connect function returns a link identifier. A link identifier is a positive integer that labels the connection to the server. If a connection is not made successfully, the function will return a value of false.
CONNECT TO A MYSQL SERVER

The link identifier can be used by other functions in the PHP script, such as mysql_select_db and mysql_query, to send commands to the MySQL server. Specifying a link identifier in a function allows you to perform an operation using a specific MySQL server connection. If no link identifier is specified, the last successful connection made in the script will be used. If you include more than one mysql_connect function with the same arguments in a script, new connections will not be created when the subsequent functions are called. Instead, the functions will use the link identifier for the first connection. When a PHP script that opens a MySQL server connection terminates, the connection to the server is automatically closed. You can use the mysql_close function to explicitly close a connection.

Once a connection to a MySQL server has been established, you can use the mysql_select_db function to select the database you want to work with. To use the mysql_select_db function, you must specify the name of the database you want to access and the link identifier for the connection. This function returns a value of true if the specified database is successfully selected or false if the selection is not successful.
Example: $linkID = mysql_connect("localhost", "", ""); if (mysql_select_db("mysql", $linkID) != FALSE) { print "The database was successfully selected."; } else { print "The specified database cannot be selected."; }

The error control operator (@) is often used with the mysql_connect function. This operator prevents a PHP error message from appearing in a user's Web browser when a connection to the MySQL server cannot be established. Also, since a script is unlikely to continue working properly if a connection to the MySQL server fails, you may want to use the die function to terminate the script and display a customized error message.
Example: $linkID = @mysql_connect("localhost", "", "") or die("Connection to the database cannot be made.");

⁄ To connect to a MySQL server, type mysql_connect().

¤ Between the parentheses, type the host name or IP address of the computer running the MySQL server enclosed in quotation marks.

‹ Type a comma followed by a user name enclosed in quotation marks. › Type a comma followed
by a password enclosed in quotation marks.

Note: If a user name or password is not required, enter an empty string.

Á To test if a connection
to the MySQL server was made successfully, type the code that checks the value of the link identifier.

° Between the parentheses,
type the name of the variable that stores the link identifier.

· Display the PHP page
in a Web browser.

ˇ Type the code that assigns
the link identifier returned by the mysql_connect function to a variable.

I The Web browser displays the results of connecting to a MySQL server.

‡ To close the connection
to the MySQL server, type
mysql_close().

184

185

PHP

PHP AND MYSQL

10

CREATE A PERSISTENT CONNECTION TO A MYSQL SERVER

Y

ou can use the mysql_pconnect function to create a persistent connection to a MySQL server. When a persistent connection is established, the connection will remain open even after the PHP script is finished processing. When the mysql_pconnect function is called again in another PHP script using the same arguments as the original mysql_pconnect function call, the original connection will be used instead of creating a new connection. The mysql_pconnect function will work only if PHP is set up as a module. For information about setting up PHP as an Apache module, see the top of page 11. To set up PHP as a module on a different type of Web server, refer to PHP's documentation. The mysql_pconnect function takes three arguments–– the host name or IP address of the computer running the MySQL server, a user name and a password. If a user name or password is not required, you can enter empty strings ("") for these arguments.

When a connection to the server is made successfully, the mysql_pconnect function returns a link identifier, which is a positive number that labels the connection to the server. If a connection is not made successfully, the function will return a value of false. A connection created using the mysql_pconnect function cannot be closed using the mysql_close function. A connection using the mysql_pconnect function will eventually close after it has been idle for a specific amount of time. The mysql_pconnect function is useful in instances where many connections to the database have to be made in a short period of time using the same user name and password. Opening and closing database connections can use a substantial amount of system resources and thus slow down a server. Using a persistent connection to a database is more efficient and improves the performance of the application.

When specifying the host argument for the mysql_pconnect function, you may specify a port number by typing the host name or IP address followed by a colon (:) and the port number you want to use. By default, PHP uses port number 3306. You typically would not have to specify a port number when connecting to a MySQL server, unless the MySQL server is not set to the default port number. If multiple MySQL servers are running on the same machine, a port number needs to be specified in order to connect to the appropriate MySQL server. You may also specify a port number when calling the mysql_connect function.
Example: $linkID = mysql_pconnect("localhost:3307", "martine", "secret");

When working in the Unix environment, you can specify the path of a socket being used by a MySQL server. A socket provides a means for the client to communicate with the server and is similar to a network port number. The path of a socket can be specified in the host argument for the mysql_pconnect function by typing the host name or IP address followed by a colon (:) and the path to the socket file. The default socket is /tmp/mysql.sock. You may also specify a path to a socket when calling the mysql_connect function.
Example: $linkID = mysql_pconnect("localhost:/tmp/mysql2.sock", "martine", "secret");

CREATE A PERSISTENT CONNECTION TO A MYSQL SERVER

⁄ To create a persistent connection to a MySQL server, type mysql_pconnect().

¤ Between the parentheses,
type the host name or IP address of the computer running the MySQL server enclosed in quotation marks.

‹ Type a comma followed by a user name enclosed in quotation marks.

› Type a comma followed by a password enclosed in quotation marks.
Note: If a user name or password is not required, enter an empty string.

ˇ Type the code that assigns
the link identifier returned by the mysql_pconnect function to a variable.

Á To test if the persistent connection to the MySQL server was made successfully, type the code that checks the value of the link identifier.

‡ Display the PHP page
in a Web browser.

I The Web browser displays the results of creating a persistent connection to a MySQL server.

186

187

PHP

PHP AND MYSQL

10

ISSUE AN SQL STATEMENT TO A MYSQL SERVER

A

fter creating a connection to a MySQL server in a PHP page and selecting the database you want to work with, you can use the mysql_query function to issue an SQL statement to the server. Issuing an SQL statement to a MySQL server allows you to manipulate a database and perform tasks such as creating a table, retrieving data or adding records. To use the mysql_query function, you need to specify a valid SQL statement. You can also specify the link identifier for the MySQL server connection you want to use. If the SQL statement is successfully executed, the mysql_query function will return a value of true or a result identifier. If the statement is not successfully executed, the function will return a value of false. SQL statements that perform an operation but do not retrieve data from a database, such as CREATE TABLE and UPDATE, return a value of true if successfully executed.

SQL statements used to retrieve data from a database, such as SELECT and SHOW TABLES, return a result identifier if successfully executed. The result identifier is a positive integer that points to the data retrieved from the database, which is temporarily stored in a result set. To access the data from the result set, you specify the result identifier as an argument for the function you want to use, such as the mysql_fetch_row function. You should keep in mind that the database program you are using determines the SQL statements you can issue. Certain SQL features are not available in MySQL in order to improve the database program's performance and speed. There are also special SQL statements that can be used only on a MySQL database. You can consult the www.mysql.com Web site to find more information about the specific features of MySQL.

The mysql_create_db function can be used in a PHP script to create a database. To use this function, you need to specify the name of the database you want to create followed by the link identifier for the MySQL server connection. The mysql_create_db function returns a value of true if the database was successfully created or false if the operation fails. In order to create a database, the user name used to make the MySQL server connection must have the appropriate permissions.
Example: if (mysql_create_db("accounting", $linkID) == TRUE) { print "The database was created successfully."; } else { print "The database could not be created."; }

The mysql_drop_db function allows you to delete a database from a MySQL server. If the database is deleted successfully, a value of true is returned. Otherwise, a value of false is returned.
Example: $resultID = mysql_drop_db("customers", $linkID);

You can use the mysql_db_query function to send an SQL statement directly to a database after creating a connection to the server. The mysql_db_query function takes three arguments––the name of the database you want to query, an SQL statement and the link identifier for the MySQL server connection.
Example: $resultID = mysql_db_query("accounting", "CREATE TABLE employee(id INT(4), name CHAR(15), extension INT(4))", $linkID);

ISSUE AN SQL STATEMENT TO A MYSQL SERVER

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with. 188

¤ To issue an SQL
statement to the MySQL server, type mysql_query().

‹ Between the parentheses, type the SQL statement you want to issue, enclosed in quotation marks.

› Type a comma followed
by the name of the variable that stores the link identifier.

ˇ Type the code that
assigns the value returned by the mysql_query function to a variable.

Á To test if the SQL
statement was issued successfully, type the code that checks the value of the variable storing the mysql_query function.

‡ Display the PHP page
in a Web browser.

I The Web browser displays the result of issuing an SQL statement to a MySQL server.

189

PHP

PHP AND MYSQL
You can use the list statement with the mysql_fetch_row function to assign an array value to a variable with a meaningful name. When you want to use the array value, you can use the variable name to access the value instead of referencing the value by its numeric key. This can help simplify your code and make your arrays easier to work with.
Example: $resultID = mysql_query("SELECT firstName, extension FROM employees", $linkID); print "<table>"; print "<tr><th>First Name</th><th>Extension</th></tr>"; while (list($firstName, $extension) = mysql_fetch_row($resultID)) { print "<tr><td>$firstName</td><td>$extension</td></tr>"; } print "</table>";

10

RETRIEVE INFORMATION FROM A DATABASE

T

he SQL SELECT statement allows you to retrieve information from a database. This is useful when you want to display the contents of a table. The mysql_query function is used to issue a SELECT statement to the database.

The mysql_query function returns a result identifier, which points to the result set. If the SELECT statement is not executed successfully, the function returns a value of false. Once the SELECT statement has been successfully issued to the database, you can use the mysql_fetch_row function to access the data in the result set. You must specify the variable that stores the result identifier as the argument for the mysql_fetch_row function. The mysql_fetch_row function returns an array containing the values from one row of the result set. To retrieve subsequent rows in the result set, you can use the mysql_fetch_row function in a loop. Information retrieved from a database is commonly placed in an HTML table. This allows you to neatly display the information on a Web page.

The SELECT statement allows you to specify the data you want to retrieve from a table. You can specify the data you want to retrieve by name or use an asterisk (*) to retrieve all the data in a table. The SELECT statement uses the FROM clause to specify the name of the table that stores the information you want to retrieve. When the SELECT statement has been executed successfully, the data retrieved from the database is temporarily stored in a result set, which has the same format as a table. The fields specified in the SELECT statement make up the columns of the result set and the values from each field form the rows.

You can use the WHERE clause with a SELECT statement to specify a condition for retrieving data. To specify multiple conditions, you can also use the OR and AND operators. For more information about using the WHERE clause, consult the MySQL documentation at the www.mysql.com Web site.
Example: SELECT invoiceNumber, totalCost FROM orders WHERE totalCost = 50 OR (totalCost >= 100 AND totalCost <= 300)

RETRIEVE INFORMATION FROM A DATABASE

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with. 190

¤ To issue an SQL
statement to the MySQL server, type mysql_query( ).

‹ Between the parentheses, type SELECT * FROM followed by the name of the table that stores the information you want to retrieve. Enclose the SELECT statement in quotation marks.

› Type a comma
followed by the name of the variable that stores the link identifier.

Á To access the data
retrieved from the database, type mysql_fetch_row( ).

° Type the code that
processes the result of the mysql_fetch_row function and formats the information for display.

· Display the PHP page
in a Web browser.

ˇ Type the code that
assigns the value returned by the mysql_query function to a variable.

‡ Between the parentheses,
type the name of the variable that stores the result identifier.

I The Web browser displays the result of retrieving information from a database.

191

PHP
When adding a string value that contains quotation marks, you must escape the quotation marks by placing the backslash character (\) before each quotation mark. If the quotation marks in a string are not escaped, an error may occur when the INSERT statement is executed.
Example: mysql_query("INSERT INTO customer (customerID, firstName, lastName) VALUES (111, 'Tim', 'O\'Brien')", $linkID);

PHP AND MYSQL

10

ADD A RECORD

O

nce you establish a connection with a database, you can add records to the database using the INSERT statement.

When adding a record to a database, you use the mysql_query function to issue an INSERT statement to the MySQL server. The mysql_query function returns a value of true if the new records are added successfully. Otherwise, the function returns a value of false. The INSERT statement uses the INTO clause to specify the name of the table into which you want to insert records. After the table name, you indicate the fields into which you want to insert data. The VALUES clause is used to specify the values for each record you want to add to the table. You must specify a value that corresponds to each field name indicated in the INTO clause. You must place the values in the same order the fields were specified in the INTO clause. String values should be enclosed in single quotation marks (' ').
ADD A RECORD

If you do not specify the names of the fields you want to affect in the INTO clause, MySQL assumes that you want to insert data into all the fields in the table. The values must be specified in the same order the fields appear in the table. You may insert multiple records using the same INSERT statement. After the values for the first record are specified, values for subsequent records are included, enclosed in parentheses. Each record you add must be separated by a comma. The MySQL server requires that appropriate permissions be granted before a script can add information to a database. For information about setting permissions in a MySQL server, consult the MySQL documentation at the www.mysql.com Web site.

You can insert a string value stored in a variable into a record in your database. You should use the addslashes function to escape the quotation marks in a string stored in a variable before it is used with an INSERT statement. The addslashes function takes the variable that contains a string value as an argument. When a variable is used in an SQL statement, the variable name is enclosed in single quotation marks.
Example: $text = "O'Brien"; $escaped = addslashes($text); mysql_query("INSERT INTO customer (customerID, firstName, lastName) VALUES (111, 'Tim', '$escaped')", $linkID);

You can make changes to the php.ini file so that quotation marks, backslash characters and NULL characters in strings are automatically escaped when the strings are used in a script. When the magic_quotes_gpc directive in the php.ini file is enabled, string values that are retrieved from a form or a cookie are escaped automatically. When the magic_quotes_runtime directive is enabled, functions that retrieve information from external sources, such as databases and text files, return strings that are escaped automatically.

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with.

¤ To add a record in the
database, type mysql_query("").

‹ Between the quotation
marks, type INSERT INTO followed by the name of the table to which you want to add records. Then type ().

› Between the parentheses, type the names of the fields in the table, separating each field name with a comma. ˇ To specify the values for a record you want to add, type VALUES.

Á Type the values you want to assign to each field in the record, enclosed in parentheses. A comma separates each value. ‡ Outside the quotation
marks, type a comma followed by the link identifier.

° Type the code that assigns
the value returned by the mysql_query function to a variable.

‚ Type the code that displays information from the database in the PHP page.

— Display the PHP
page in a Web browser.

I The Web browser displays the result of adding a record to a database.

· To test if the records were
added successfully, type the code that checks the value of the variable storing the mysql_query function.

192

193

PHP

PHP AND MYSQL
The mysql_affected_rows function may be used to determine the number of records that were affected by an UPDATE statement. The link identifier to the MySQL connection is passed as an argument to the mysql_affected_rows function. The code that calls the mysql_affected_rows function is placed immediately after the line that updates the database. The mysql_affected_rows function may also be used to determine the number of records affected by an INSERT or DELETE statement.
Example: $result = mysql_query("UPDATE customer SET lastName = 'Edwards' WHERE firstName = 'Martine'", $linkID); print mysql_affected_rows($linkID) . " record(s) were updated.";

10

UPDATE A RECORD

O

nce you establish a connection with a database, you can edit the information contained in the database. Editing the information in a database allows you to keep the information up-to-date.

unique ID for the record in the WHERE clause. If a WHERE clause is not specified when using an UPDATE statement, MySQL will update all the records in the table. When specifying the value of a field, a string value must be enclosed in single quotation marks (''). If the value contains quotation marks, you must escape the quotation marks by placing the backslash character (\) before each quotation mark, such as \' and \". The MySQL server requires that appropriate permissions be granted before a script can update information in a database. For information about setting update permissions in a MySQL server, consult the MySQL documentation at the www.mysql.com Web site.

To update records in a database, you use the mysql_query function to issue an UPDATE statement to the MySQL server. The mysql_query function returns a value of true if the update is made successfully. After the UPDATE statement, you indicate the name of the table that contains the records you want to modify. The SET clause specifies which field in a record needs to be changed and the new value. You can specify more than one field to be changed. The UPDATE statement uses the WHERE clause to specify the data that identifies the record to be modified. Depending on the data specified in the WHERE clause, you may update the value of one or more records in a table. To update a single record, you would typically indicate the

You may want to store SQL statements in variables and then pass a variable as an argument to the mysql_query function. Using variables to store SQL statements is a common programming practice and can make your code easier to read and update. Storing SQL statements in variables also provides a convenient way to switch between statements when troubleshooting a script. You simply place two slashes (//) in front of each statement you temporarily do not want to use.
Example: // $query = "UPDATE customer SET lastName = 'Smith' WHERE customerID = 109"; // $query = "UPDATE customer SET firstName = 'Joe' WHERE customerID = 107"; $query = "UPDATE customer SET customerID = 103 WHERE firstName > 'Sandy'"; $result = mysql_query($query, $linkID);

UPDATE A RECORD

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with. 194

¤ To update a record
in the database, type mysql_query("").

‹ Between the quotation
marks, type UPDATE followed by the name of the table you want to update. Then type SET.

› Type the name of the field you want to change followed by =. Then type the new value you want to assign. ˇ Repeat step 4 for each field
you want to change, separating each field with a comma.

Á To specify which records
to update, type WHERE.

° Outside the quotation
marks, type a comma followed by the link identifier.

‚ To test if the update was
made successfully, type the code that checks the value of the variable storing the mysql_query function.

± Display the PHP page
in a Web browser.

‡ Type the name of the
field followed by =. Then type the value that identifies the records to be modified.

I The Web browser displays the result of updating a record in a database.

· Type the code that
assigns the result of the mysql_query function to a variable.

— Type the code that
displays the information in the database.

195

PHP

PHP AND MYSQL

10

DELETE A RECORD
fter creating a connection to a MySQL server in a PHP page and selecting the database you want to work with, you can use the DELETE statement to remove a record from the database. When deleting a record from a database, you use the mysql_query function to issue a DELETE statement to MySQL server. The mysql_query function returns a value of true if the record is deleted successfully. Otherwise, the function returns a value of false. The DELETE statement uses the FROM clause to specify the name of the table that stores the record you want to delete. The WHERE clause indicates information that uniquely identifies the record you want to delete. You should be careful when identifying the record you want to delete, as information accidentally deleted from a database often cannot be recovered. When identifying the information in the record you want to delete, a string value must be enclosed in single quotation marks (''). If the value contains quotation
DELETE A RECORD

A

marks, you must escape the quotation marks by placing the backslash character (\) before each quotation mark, such as \' and \". After the DELETE statement, you can specify the link identifier for the MySQL server connection you want to use. If you simply want to use the last connection that was made to the server, you can omit the link identifier from the mysql_query function. If you want to remove all the records from a table at one time, you can use the DELETE statement without including the WHERE clause. This will delete all the data in the table but will not delete the table from the database. The MySQL server requires that appropriate permissions be granted before a script can delete information from a database. For information about setting permissions in a MySQL server, consult the MySQL documentation at the www.mysql.com Web site.

Multiple records can be removed from a table at one time by specifying a range of values in the WHERE clause of the DELETE statement. For example, if you have a field that stores the last date on which a customer made a purchase, you can use an expression with the WHERE clause to delete all the records of customers who made their last purchase before a specific date.
Example: $result = mysql_query("DELETE FROM customer WHERE lastPurchase < '2000-04-23'", $linkID);

You can remove a field from a table by using the ALTER TABLE statement with the mysql_query function. After specifying the table you want to affect, the DROP clause is used to specify the field you want to remove. When a field is removed, all the data in the field is also deleted.
Example: $result = mysql_query("ALTER TABLE customer DROP middleName", $linkID);

To delete an entire table and all the data stored in the table from a database, you can use the DROP TABLE statement with the mysql_query function. After the DROP TABLE statement, you must specify the name of the table you want to delete. You should be careful not to delete a table that you might need at a later time.
Example: $result = mysql_query("DROP TABLE oldCustomers", $linkID);

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with.

¤ To delete a record from the database, type mysql_query(""). ‹ Between the quotation
marks, type DELETE FROM followed by the name of the table from which you want to delete a record.

› To specify the record to delete, type WHERE. ˇ Type the name of the field followed by =. Then type the value in the field that identifies the record to be deleted.

Á Outside the quotation
marks, type a comma followed by the link identifier.

‡ Type the code that assigns
the value returned by the mysql_query function to a variable.

· Type the code that
displays information from the database in the PHP page.

‚ Display the PHP page
in a Web browser.

I The Web browser displays the result of deleting a record from a database.

° To test if the record was
deleted successfully, type the code that checks the value of the variable storing the mysql_query function.

196

197

PHP

PHP AND MYSQL

10

RETRIEVE INFORMATION AS AN ASSOCIATIVE ARRAY
fter using the SELECT statement with the mysql_query function to retrieve information from a database and place it in a result set, you can use the mysql_fetch_assoc function to retrieve information from the result set as an associative array. The mysql_fetch_assoc function returns an associative array in which the keys are the same as the names of the fields in the result set and the array values correspond to the values in the fields. Many programmers assign the result of the mysql_fetch_assoc function to a variable to make the associative array easier to work with. Accessing data as an associative array can make your PHP code more readable because it identifies exactly which fields are being used instead of identifying the fields only by number. Using associative arrays also means that you do not need to consider the order in which the fields appear in the result set. This may help prevent problems that may arise if the structure of the table were to change in the future.
RETRIEVE INFORMATION AS AN ASSOCIATIVE ARRAY

A

To call the mysql_fetch_assoc function, you must pass the result identifier that points to the data stored in the result set as an argument. If the function is successful, the associative array is returned. If there is no information in the result set, the mysql_fetch_assoc function returns a value of false. To access a value from the associative array, you specify the name of the variable that stores the result of the mysql_fetch_assoc function followed by brackets []. Between the brackets, specify the name of the field that stores the value you want. The mysql_fetch_assoc function is often used with a loop to allow access to all the information from the result set. You can use the mysql_num_rows function in the loop code to indicate when the loop should end. The mysql_num_rows function determines the number of rows returned by the SELECT statement issued by the mysql_query function.

The mysql_fetch_object function allows you to retrieve information from a result set as an object. This function returns an object with property names that are the same as the field names in the table. To access the value of a field, specify the name of the variable that stores the object followed by the member access operator (->) and the field name.
Example: while ($row = mysql_fetch_object($resultID)) { print "<tr>"; print "<td>" . $row->customerID . "</td>"; print "<td>" . $row->firstName . "</td>"; print "<td>" . $row->lastName . "</td>"; print "</tr>"; }

The mysql_fetch_array function is used to retrieve information from a database as an array that contains both numeric and associative keys. The mysql_fetch_array function returns an array in which each field value appears twice––once with a numeric key and once with an associative key. This duplication of values makes the mysql_fetch_array function inefficient for retrieving large amounts of information from a result set. You should use this function only when both the numeric order and the field names to which the values belong are needed.
Example: while ($row = mysql_fetch_array($resultID)) { print "<tr>"; print "<td>" . $row[0] . "</td>"; print "<td>" . $row[firstName] . "</td>"; print "<td>" . $row[2] . "</td>"; print "</tr>"; }

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with. 198

¤ Type the code that uses
a mysql_query function to retrieve information from the database and assigns the result identifier returned by the mysql_query function to a variable.

‹ To retrieve information from the result set as an associative array, type mysql_fetch_assoc(). › Between the parentheses, type the name of the variable that stores the result identifier.

ˇ Type the code that
assigns the result of the mysql_fetch_assoc function to a variable.

Á To access a value from the
result set, type the name of the variable that stores the associative array. Then type the name of the field that stores the value you want to access, enclosed in brackets [].

‡ Repeat step 6 for each value you want to retrieve. ° Type the code that uses the information retrieved as an associative array and formats the information for display.

· Display the PHP page
in a Web browser.

I The Web browser displays the result of retrieving information from a database as an associative array.

199

PHP
You can use the MySQL AS construct to specify a different name for a field you are retrieving. Specifying a different name for a field can be particularly useful when using the mysql_fetch_assoc function. The associative array returned by this function is indexed using only field names. This can cause problems if you retrieve fields that have the same name from different tables.
Example: SELECT orders.totalCost AS orderTotal, shipping.totalCost AS shippingTotal FROM orders, shipping WHERE orders.customerID = shipping.customerID

PHP AND MYSQL

10

RETRIEVE INFORMATION FROM MULTIPLE TABLES

O

ne of the most useful features of a relational database is the ability to retrieve data from multiple tables and then combine the data into a single result set.

You use the SELECT statement to combine related data from multiple tables. This operation is referred to as a join. To select a field for a join, you specify the name of the table containing the field and the name of the field, separated by a dot(.). You can select as many fields as you need for a join. You use the FROM clause to specify the names of the two tables from which you want to retrieve information. The WHERE clause allows you to specify the relationship between the tables being joined. Each table has a field that stores a unique identifier for each record, referred to as a primary key. To specify the relationship between the two
RETRIEVE INFORMATION FROM MULTIPLE TABLES

tables, you specify the name of the first table and the name of the primary key for that table. You then enter the name of the second table and the name of the field that stores the same values as those stored in the primary key of the first table. If the unique identifier for a record in the first table matches information in the second table, then the record will be retrieved from both tables. For example, you may want to join data from two tables called customer and orders. The customer table has a primary key field that stores a unique customer id for each customer, as well as fields containing information such as first and last names. The orders table contains the orders made by each customer and includes each customer's id. You can join data from the two tables to create a report that includes specific information for each customer who has placed an order.

When you want to display all the records from one of the tables in a join, you can use the LEFT JOIN clause. This clause allows you to retrieve all the records from a table, regardless of whether the records have corresponding entries in the second table. To use the LEFT JOIN clause, specify the name of the table from which you want to retrieve all the records directly following the FROM clause. Type LEFT JOIN followed by the name of the second table. Then type ON followed by the relationship between the two tables.
Example: SELECT customer.firstName, customer.lastName, orders.itemDescription, orders.quantity, orders.purchaseDate FROM orders LEFT JOIN customer ON customer.customerID = orders.customerID

You can use the MySQL CONCAT function to combine data from different fields into a single field. To use the CONCAT function, you must specify the names of the fields you want to retrieve, separated by commas. You can also include a string, such as a space (' '), to separate the fields. You can then use the AS construct to specify a name for the new field.
Example: SELECT CONCAT(firstName, ' ', lastName) AS fullName, customerID FROM customer

⁄ To issue an SQL statement to the MySQL server, type mysql_query(""). ¤ Between the quotation marks, type SELECT.

‹ To specify a field for the
join, type the name of the table followed by a dot and the name of the field.

ˇ Type FROM followed
by the names of the tables containing information you want to retrieve, separated by commas.

Á To specify the
relationship between the tables, type WHERE.

° Type = followed by the name
of the second table and a dot. Then type the name of the field that stores the same values as those stored in the primary key of the first table.

‚ Type the code that uses
the mysql_fetch_row function to access and retrieve data and formats the data for display.

— Display the PHP page
in a Web browser.

› Repeat step 3 until you
have specified all the fields for the join, separating each table and field name pair with a comma.

‡ Type the name of the
first table followed by a dot and the name of the primary key field for the table.

I The Web browser displays the result of retrieving information from multiple tables.

· Type the code that assigns
the result of the mysql_query function to a variable.

200

201

PHP

PHP AND MYSQL
You can use the mysql_result function to retrieve a single value from a result set. To use the mysql_result function, you specify the result identifier for the result set and the offset position of the row that contains the value you want to retrieve. The mysql_result function will return the value of the first field in the specified row.
TYPE THIS: $resultID = mysql_query("SELECT customer.firstName, customer.lastName, orders.itemDescription, orders.quantity, orders.purchaseDate FROM customer, orders WHERE customer.customerID = orders.customerID", $linkID); print mysql_result($resultID, 3); RESULT:

10

ACCESS A PORTION OF A RESULT SET
fter information has been retrieved from a database and placed in a result set, you can use the mysql_data_seek function to access a portion of the result set. The mysql_data_seek function advances the row pointer of the result set to a row you specify. This allows you to work with a small portion of a large result set without having to iterate through the entire result set. The mysql_data_seek function is typically used to separate a large number of records to be displayed on a Web page. For example, if a user's query retrieves a large number of records from a database, you may want to display the records on the Web page in small segments at a time instead of displaying all the records at once. Handling a large result set in this manner is very efficient, since you retrieve only the data you need. To use the mysql_data_seek function, you must specify the result identifier that points to the data stored in the result set. You also specify the offset position of the row you want

A

to access in the result set. The offset positions of the rows in a result set are numbered starting from zero (0). If you specify an offset position that is equal to or greater than the number of rows in the result set, an error will be generated. The mysql_data_seek function will return a value of true or false depending on whether the function was executed successfully. Once the pointer is positioned at the first row you want to access in the result set, you can call the mysql_fetch_row function to retrieve the information in the row. The pointer is then advanced to the next row. To retrieve subsequent rows, you can call the mysql_fetch_row function repeatedly using code that creates a loop, such as a for statement.

Martine

When using the mysql_result function, you can specify the value you want to retrieve from a row. To retrieve a value from a specific field in the row, you can include a third argument to specify the offset position of the field. You can also specify the name of the field instead of the offset position of the field. Another option allows you to prefix the field name with the name of the table from which you want to retrieve the data. This is useful when working with a result set created from multiple tables.
Example: mysql_result($resultID, 3, 4); Can be typed as: mysql_result($resultID, 3, "purchaseDate"); Or mysql_result($resultID, 3, "orders.purchaseDate");

ACCESS A PORTION OF A RESULT SET
Portion of a Result Set - Microsoft Internet Explorer

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with. 202

¤ Type the code that uses
a mysql_query function to retrieve information from the database and assigns the result identifier returned by the mysql_query function to a variable.

‹ To move the row pointer to a specific row in the result set, type mysql_data_seek(). › Between the parentheses, type the name of the variable that stores the result identifier.

ˇ Type a comma, followed by the number that specifies the offset position of the row where you want to place the pointer.

Á To retrieve the row at which
the pointer is positioned, type mysql_fetch_row( ).

° Type the code that
processes the result of the mysql_fetch_row function and formats the information for display.

· Display the PHP page
in a Web browser.

‡ Between the parentheses,
type the name of the variable that stores the result identifier.

I The Web browser displays the result of accessing a portion of a result set.

203

PHP
You can use functions to obtain information about the tables in a database. To obtain a list of tables in a database, you can use the mysql_list_tables function. The function takes two arguments––the name of the database and the link identifier of the MySQL server connection. To determine the number of tables in a database, you can use the mysql_num_rows function, which takes the result

PHP AND MYSQL

10

GET INFORMATION ABOUT FIELDS
he mysql_list_fields function returns a result identifier that can be used to obtain information about the fields in a table. You may find it useful to retrieve information such as the names or data types of fields before making an SQL query. The mysql_list_fields function takes three arguments––the name of a database, the name of the table containing the fields you want to work with and the link identifier of the MySQL server connection. If you do not specify a link identifier, the last successful connection to the MySQL server will be used. The mysql_list_fields function will return a result identifier if successful, otherwise it will return a value of false. You can obtain the number of fields in a table by using the mysql_num_fields function. When calling the mysql_num_fields function, you must pass the result identifier obtained from the mysql_list_fields function as an argument. The mysql_num_fields function is often used as a counter in a loop that cycles through each field in a table. This type of loop allows you to access information about each field.
GET INFORMATION ABOUT FIELDS

T

There are a number of functions that use the result identifier obtained from the mysql_list_fields function to retrieve information about a field. The mysql_field_name function is used to retrieve the name of a field. You can use the mysql_field_type function to retrieve the data type of a field. The mysql_field_len function is used to retrieve the maximum length of a field. You can use the mysql_field_flags function to retrieve other information about a field. These functions all take two arguments––the result identifier obtained from the mysql_list_fields function and the offset position of the field in the table. The offset positions of the fields are numbered starting from zero (0) and are determined by where the fields appear in the table. An error will occur if an offset position that is equal to or greater than the number of fields in a table is specified.

identifier obtained from the mysql_list_tables function as an argument. You can also determine the name of a table by using the mysql_tablename function. You must specify the result identifier obtained from the mysql_list_tables function and the offset position of the table in the database as arguments for the mysql_tablename function.

Example: $resultID = mysql_list_tables("shopping", $linkID); for ($tablePos = 0; $tablePos < mysql_num_rows($resultID); $tablePos++) { print mysql_tablename($resultID, $tablePos) . "<br>"; }

You can obtain a list of databases on a MySQL server by using the mysql_list_dbs function. The mysql_list_dbs function takes the link identifier of the MySQL server connection as an

argument. You can then use the mysql_num_rows function to determine the number of databases in the list. You can also determine the name of a database by using the mysql_tablename function.

Example: $resultID = mysql_list_dbs($linkID); for ($dbPos = 0; $dbPos < mysql_num_rows($resultID); $dbPos++) { print mysql_tablename($resultID, $dbPos) . "<br>"; }

⁄ Type the code that connects the PHP page to the MySQL server. ¤ To retrieve information
about a table, type mysql_list_fields().

‹ Between the parentheses,
type the name of the database, enclosed in quotation marks.

› Type a comma followed
by the name of the table, enclosed in quotation marks. Then type a comma followed by the link identifier.

ˇ Type the code that assigns the result identifier returned by the mysql_list_fields function to a variable. Á To obtain the number
of fields in a table, type mysql_num_fields( ).

‡ Between the parentheses, type the result identifier. ° Type the code that uses the mysql_num_fields function.

· To obtain information
about a specific field, type the name of the function you want to call followed by ().

— Repeat steps 9 and 10 for each function you want to call. ± Type the code the uses the results of the functions you called.

¡ Display the PHP page
in a Web browser.

I The Web browser displays the result of obtaining information about the fields in a table.

‚ Between the parentheses,
type the result identifier. Then type a comma followed the offset position of the field.

204

205

PHP

PHP AND MYSQL
When a user submits an SQL statement that generates an error, you can have the PHP page display information about the error that the user may find helpful. You can use the mysql_errno function to retrieve the error number from the MySQL server and the mysql_error function to retrieve the error message.
Example: if ((gettype($resultID) == "boolean") && ($resultID == FALSE)) { print "There was an error in the SQL statement.<br>"; print "Error #" . mysql_errno($linkID) . ": " . mysql_error($linkID); }

10

USE A FORM TO WORK WITH A DATABASE
orms provide an easy-to-use interface for manipulating data in a database and can be used to issue SQL statements to a MySQL database. The form passes an SQL statement to a PHP page that connects to the database, processes the statement and displays the result.

F

If the result of the mysql_query function is of the boolean data type and has a value of false, the SQL statement passed by the form contains an error. You should create an error message that will be displayed in this situation. If the returned result is of the boolean data type and has a value of true, the SQL statement was successfully executed. You may want to use the mysql_affected_rows function to display the number of records that were affected by the query. When the returned result is not of the boolean data type, the SQL statement returned a result set. You can use the mysql_num_rows function to display the number of rows in the result set. You can also retrieve the records in the result set using the mysql_fetch_row function.

When creating the code for a form that will be used to issue SQL statements to a database, you must specify the name of the PHP page that connects to the database in the action attribute of the <form> tag. You can use the <textarea> tag to create a text area element on the form that users can enter SQL statements into. The PHP page will use the value of the name attribute for the <textarea> tag to access the SQL statement passed by the form. The PHP page used to process the form must have a connection to the MySQL server and select the database you want to work with. The PHP page must also contain the mysql_query function, which will process the SQL statement passed by the form.
USE A FORM TO WORK WITH A DATABASE

When creating a table that displays retrieved records, you can use the mysql_num_fields function to retrieve the number of fields in the result set. You can use the result of this function to create a for loop that uses the mysql_field_name function to retrieve all the field names.
Example: print "<table border=\"1\">"; print "<tr>"; for ($i = 0; $i < mysql_num_fields($resultID); $i++) { print "<th>" . mysql_field_name($resultID, $i) . "</th>"; } print "</tr>";

⁄ Type the code that connects the PHP page to the MySQL server and selects the database you want to work with.

¤ To have the PHP page
accept and process an SQL statement passed by a form, type mysql_query().

› Type a comma followed by the name of the variable that stores the link identifier. ˇ Type the code that
assigns the result of the mysql_query function to a variable.

Á Type the code that
determines if the result of the mysql_query function is of the boolean data type and is false. Then type the code you want to process in this situation.

‹ Between the parentheses,
type $ followed by the value assigned to the name attribute of the <textarea> tag in the form.

‡ Type the code that determines if the result of the mysql_query function is of the boolean data type and is true. Then type the code you want to process in this situation.

° Type the code you want
to process when the result of the mysql_query function is of a data type other than boolean.

· In a Web browser,
display the form you created to issue SQL statements to the database.

— Click the submit button to pass the SQL statement to the PHP page.
I The PHP page that processes the SQL statement will appear and the database will be modified.

‚ Enter an SQL statement
into the form.

206

207

PHP

TROUBLESHOOTING PHP SCRIPTS
When specifying the information you want to display in the error log, you may want to append a newline character (\n) to the end of the error message you specify in the error_log function. The newline character will help ensure that each entry in the error log is placed on its own line, making the error log easier to read when viewed in a text editor. If you are using Windows NT, 2000 or XP, you can add error information to the operating system's log instead of logging errors to a file. In the php.ini configuration file, remove the semicolon preceding the error_log directive that specifies the syslog value. If you previously specified a file to which error information was to be saved, place a semicolon in front of that error_log line to have the php.ini file ignore the command.
log_errors ;error_log error_log = = = On c:\php\error.log syslog

11

LOG ERRORS TO A FILE
hen an error is generated in a PHP script, you may want to save information about the error in a file for later review. Saving error information to a file is useful for keeping track of non-critical errors that do not require immediate attention, such as an error generated when a user forgets to enter a user name. Before you can log errors to a file, you must make changes to the php.ini configuration file. To specify that you want to log errors, change the value of the log_errors directive in the php.ini file to "On." To specify a file to which you want to log errors, you enter the location and name of the file as the value for the error_log directive. If the file you specify does not exist, PHP will create the file when the first error occurs. For more information about the php.ini file, see page 26. To pass error information from a PHP page to an error log, you include the error_log function in the PHP code for the page. The error_log function takes two arguments.
LOG ERRORS TO A FILE

W

The first argument specifies the message you want to display in the error log when an error occurs. The second argument indicates the message type, which determines how the message will be stored. To specify that you want a message to be stored in an error log, you use a message type of 0. When a PHP script encounters an error, PHP will use a built-in error-handling function to save the date and time of the error and the message you specified to the error log. You can create a custom error-handling function to keep track of additional details about errors. For more information about creating a custom error-handling function, see page 214. The error log is a simple text file that can be viewed at any time using a text editor or word processor.

To view the error information saved to the operating system's log with Windows NT, 2000 or XP, open the Control Panel and double-click Administrative Tools. Then double-click Event Viewer and click Application Log. For more information about logging errors and the location of system logs, consult your operating system's documentation.

CHANGE THE PHP.INI SETTINGS

⁄ In the php.ini file, select
the value of the log_errors directive and type On.

‹ To activate the error_log directive, delete the semicolon preceding the directive. › Save the file.

SET UP THE PHP PAGE

‹ To specify that the
message should be stored in an error log, type a comma followed by 0.

ˇ Display the PHP page
in a Web browser.

⁄ In the PHP page for
which you want to save error information, type error_log().

I When an error is generated, the message you specified will be written to the error log.

DISPLAY THE ERROR LOG

⁄ Locate and open the
error log in a text editor.

¤ To specify a file in which to
log errors, select the value of the error_log directive and type the location and name of the file you want to use.

¤ Between the parentheses,
type the message you want to display in the error log, enclosed in quotation marks.

› Type the code that
uses the error_log function.

I The error log displays the date and time an error was generated and the error message you specified.

208

209

PHP

TROUBLESHOOTING PHP SCRIPTS

11

SEND AN ERROR MESSAGE TO AN E-MAIL ADDRESS
he error_log function allows you to send a message to an e-mail address when an error occurs in a PHP page. This is useful when a critical error occurs that requires the immediate attention of support personnel, such as an error generated by a database that is not responding or a failed attempt to log on as the administrator. With the advent of telecommunication devices that can receive e-mail messages, such as pagers and mobile telephones, sending error messages to an e-mail address is an efficient way for Webmasters to stay informed about the status of their Web servers. To use the error_log function to send an error message to an e-mail address, you must specify the error message you want to send. You must also specify the message type, which determines where the error message will be sent.
SEND AN ERROR MESSAGE TO AN E-MAIL ADDRESS

T

To send an error message to an e-mail address, you use a message type of 1. You must also specify the e-mail address to which you want to send the message. Although not required, you can also specify new header information for the e-mail message. E-mail message headers contain information such as the name of the person who sent the message, the subject of the message and the date the message was sent. You can alter an existing header or you can add a new header to the e-mail message. For example, you may want to change the 'From:' header to reflect the name of the computer that generated the error. If you specify a header that does not exist, the new header will be created and sent with the e-mail message. Creating a new header is useful for support departments that organize error messages according to the value of a customized header.

Before you can use the error_log function to send an error message to an e-mail address, you must configure PHP to work with the mail system available to the Web server. On Windows computers, you must ensure that the php.ini file specifies the name of the mail server used to send mail, often referred to as the SMTP server. You must also specify an e-mail address that is authorized to send mail using the mail server. In the php.ini file, locate the [mail function] section heading and then change the value of the SMTP directive to reflect the name of the outgoing mail server. Then change the value of the sendmail_from directive to reflect a valid e-mail address.
Example: [mail function] SMTP = mail.c1.us sendmail_from = ted@abccorp.com

On Unix-based systems, such as computers running the Linux operating system, Sendmail is the universally accepted program used to process e-mail messages. You must use the php.ini file to specify the location of the Sendmail program on the Web server. The e-mail account on the Web server used to send messages will be used when the error_log function is processed. Locate the [mail function] section heading in the php.ini file and then change the value of the sendmail_path directive to reflect the location of the Sendmail program.
Example: [mail function] sendmail_path = usr/bin/sendmail

⁄ To send a message to an e-mail address when an error occurs, type error_log().

¤ Between the parentheses, type the message you want to send, enclosed in quotation marks.

‹ To specify that the message should be sent to an e-mail address, type a comma followed by 1.

› To specify the e-mail
address you want to send the message to, type a comma followed by the e-mail address enclosed in quotation marks.

ˇ To specify new header
information for the e-mail message, type a comma followed by the header information enclosed in quotation marks.

Á Type the code that
uses the error_log function.

‡ Display the PHP page
in a Web browser.

I When an error occurs, the message you created is sent to the specified e-mail address.

210

211

PHP

TROUBLESHOOTING PHP SCRIPTS

11

CHANGE THE ERROR REPORTING LEVEL
hen PHP encounters an error in a section of code, the program generates an error message that is displayed in the user's Web browser. You can change the error reporting level of PHP to specify which errors PHP should generate an error message for. PHP can detect several different types of errors. Simple errors, such as dividing a number by zero, are the most common type of error. PHP can also identify and report more serious errors, such as calling a function without passing the correct number or type of arguments. Some errors, called fatal errors, force PHP to terminate the processing of a script. Fatal errors are caused by critical problems, such as memory allocation problems. The error_reporting function allows you to specify which errors PHP should report. The error reporting level is specified using predefined constants. Commonly used

W

constants include E_NOTICE, E_WARNING and E_ERROR. You can use the E_NOTICE constant as the argument for the error_reporting function when you want PHP to detect inconsistencies that could be errors, but you do not want PHP to print error messages for the inconsistencies. You can use the E_WARNING constant to detect more serious types of errors that may require attention and print error messages for the errors. The E_ERROR constant reports only fatal errors in a script. If a fatal error occurs, the script is terminated after the error_reporting function is called. You can specify more than one constant in the error_reporting function. This allows you to specify more than one error reporting level. To use more than one constant, use the OR operator (|) to separate each constant in the error_reporting function.

Besides E_NOTICE, E_WARNING and E_ERROR, two other commonly used error reporting level constants are E_CORE_ERROR and E_CORE_WARNING. These two constants are similar to E_ERROR and E_WARNING, except that E_CORE_ERROR and E_CORE_WARNING detect errors generated by the PHP program itself and not by a script. Other error reporting levels include E_PARSE, E_COMPILE_ERROR, E_COMPILE_WARNING, E_USER_ERROR, E_USER_WARNING and E_USER_NOTICE. When using the error_reporting function to change the error reporting level, you can assign the function to a variable. You can then use the value of the variable later in your script to return to the original error reporting level.
Type this: $oldLevel = error_reporting(E_NOTICE | E_ERROR); To return to the original level, type: error_reporting($oldLevel);

If you do not want to report any errors in a PHP script, you can turn off error reporting. To turn off error reporting, set the argument for the error_reporting function to zero (0).
Example: error_reporting(0);

CHANGE THE ERROR REPORTING LEVEL

⁄ Type the code that will generate an error.

¤ To change the error
reporting level, type error_reporting().

‹ Between the parentheses, type the constant that represents the error reporting level you want to use.

› To specify another
error reporting level, type |.

ˇ Type the constant that
represents another error reporting level you want to use.

I You can repeat steps 4 and 5 for each error reporting level you want to specify.

‡ Display the PHP page in
a Web browser.

Á Type the code that will
generate another error.

I When an error occurs, PHP uses the specified reporting level to determine if an error message should be displayed.

I In this example, an error message is displayed only for the first error.

212

213

PHP

TROUBLESHOOTING PHP SCRIPTS

11

CREATE AN ERROR-HANDLING FUNCTION
n error occurs when a PHP script that contains a mistake is processed. Common mistakes include trying to divide a number by 0 or attempting to access an array that does not exist. When an error occurs, you can have PHP use a custom error-handling function you created to display information about the error.

A

Using a custom error-handling function allows you to enhance the functionality of a PHP script when an error occurs. For example, you can use a custom error-handling function to access detailed information about an error and display the information in a format that is easy to read and understand. When an error occurs, PHP passes several values to the error-handling function. The values include the code number for the error, a brief description of the error, the name of the PHP script that generated the error and the number of the line in the script where the error was detected. The values are always passed to the error-handling function in this order.
CREATE AN ERROR-HANDLING FUNCTION

To set up the error-handling function to access the values, you specify a variable to store each value. Since PHP passes all the values at once and in a fixed order, you cannot access a value without also accessing the preceding values. For example, in order to access the name of the script that generated an error, you will need to also specify variables for the error code number and description. After creating a custom error-handling function, you include the set_error_handler function in the PHP code for the page. The set_error_handler function takes as its argument the name of the custom function you want to use. You should use the set_error_handler function at the beginning of your PHP code to ensure that the custom error-handling function you specify will be accessible throughout your code.

After an error occurs, PHP will try to continue processing the remainder of the PHP script from the point at which the error occurred. Since a script may not continue working properly when a command fails, you may want to have the script stop executing when an error is found. To stop the script from executing when an error is found, include the die function as part of the error-handling function.
TYPE THIS: set_error_handler("CustomErrorHandler"); print "The result of the calculation is: "; $x = 1/0; print "$x<br>"; print "The script has been processed."; function CustomErrorHandler($errNumber, $errDescript, $errFile, $errLine) { print "<h2>An error has occurred.</h2>"; print "Error number: $errNumber<br>"; print "Description: $errDescript<br>"; print "Script name: $errFile<br>"; print "Line number: $errLine<br>"; die(); } RESULT: The result of the calculation is:

An error has occurred.
Error number: 2 Description: Division by zero Script name: c:\web_apps\apache\htdocs\errorhandler.php Line number: 12

⁄ To create an error-handling function, type function followed by the name of the function. Then type (). 214

¤ Between the parentheses,
type a variable name for each value PHP will pass to the function when an error occurs. Separate each variable name with a comma.

‹ Type the code that uses the variables that store the error information. Enclose the code in braces.

› To specify that you
want to use the custom error-handling function you created, type set_error_handler().

ˇ Between the parentheses,
type the name of the error-handling function, enclosed in quotation marks.

Á Display the PHP page
in a Web browser.

I When an error occurs, the Web browser displays the result of using a custom error-handling function.

215

PHP

TROUBLESHOOTING PHP SCRIPTS

11

EMBED DEBUGGING MESSAGES
mbedding debugging information into the HTML code of a PHP page is often the fastest and most efficient way of tracking errors in your PHP code. Debugging information is usually used to indicate the status of each major task that is executed in a PHP script.

E

When specifying debugging information to be embedded, you can include information such as the values of variables, the functions that are being called from within the PHP script and the number of iterations performed by loops. Debugging information can be a simple text message or can contain PHP or HTML code. The message can also contain scripting code such as JavaScript or VBScript and can be one or more lines long. Debugging information is often inserted into HTML code using a custom function. This enables you to standardize the message that is inserted into the HTML code each time the function is called. For example, you can include formatting code in the function to make the information easy to identify in the HTML code.
EMBED DEBUGGING MESSAGES

You include debugging information within HTML code by enclosing the information between the <!-- and --> delimiters. Any text enclosed in these delimiters will be sent to the Web browser, but will not be displayed on the Web page. Any code enclosed in the delimiters will be processed by the Web server and the results will be sent to the Web browser. After the PHP page is viewed in a Web browser, you can view the debugging information within the HTML code by displaying the source code of the page. Users who display the HTML source code will also be able to view the information. To ensure the security of your Web pages, you should include debugging messages in HTML code only when developing and testing your Web pages.

You can use the show_source function to display a syntax-highlighted version of the source code for a PHP page in the same Web browser window that displays the PHP page. Viewing the output and source code on the same page makes it easy to compare the information when troubleshooting your code. The show_source function takes the name of the current PHP page as its argument.
TYPE THIS: <html> <head> <title>Test Page</title> </head> <body> <?php print "Hello"; print "<hr>"; show_source("test.php"); ?> </body> </html> RESULT:

Hello
<html> <head> <title>Test Page</title> </head> <body> <?php print "Hello"; print "<hr>"; show_source("test.php"); ?> </body> </html>

⁄ To create a function that generates an HTML comment, type function followed by a name for the function. Then type (). ¤ Between the parentheses, type
the name of a variable that will store the debugging message.

‹ Type the braces {} that will hold the body of the function.
function, type <!– – and – –>.

› In the body of the

216

ˇ Between the opening and closing delimiters, type the message you want the function to embed in the HTML code. The message can include text, HTML or PHP code, as well as the variable that stores the information passed to the function.

Á Type the code
that will display the debugging message in the HTML source code.

‡ Type the code that
calls the function and passes the information you want to display in the debugging message to the function.

° Repeat step 7 at each
location in the PHP code where you want to generate a debugging message.

· Display the PHP page
in a Web browser.

‚ Display the source
code of the PHP page.

I The HTML source code displays the debugging messages generated when the PHP page was processed.

217

PHP

TROUBLESHOOTING PHP SCRIPTS

11

USING TELNET TO CONNECT TO A WEB SERVER

O

nce a PHP page is stored on a Web server, you may want to access more information than what is shown when viewing the PHP page in a Web browser. For example, you may need to access HTTP headers, which are not typically accessible through a Web browser, in order to troubleshoot a PHP page. You can view information for a PHP page, such as the HTTP headers, by connecting to the Web server using a telnet program. A telnet program uses a text-based interface and allows you to view the content of a page in text form. When using a telnet program to connect to a Web server, you must specify the URL or IP address of the Web server and the port number used by the Web server. A Web server typically uses port 80. Once a telnet program has established a connection to a Web server, you can issue an HTTP command that will display information about a PHP page on the server. The
USING TELNET TO CONNECT TO A WEB SERVER

commands you can issue to a Web server are part of the HTTP specification that is also used by Web browsers to retrieve information. For more information about the HTTP specification, you may refer to the World Wide Web Consortium (W3C) Web site at www.w3.org. Two common HTTP commands are GET and HEAD. The GET command allows you to retrieve a PHP page from a Web server. The HEAD command is used to retrieve the HTTP header information from a PHP page. Some telnet programs require you to enable local echo before you can view the commands you are typing. You can consult your telnet program's documentation for more information about local echo.

Using troubleshooting features may increase the processing time of a PHP script. As a result, the processing time may exceed the maximum execution time allowed by PHP. You can change the maximum execution time allowed by PHP to better accommodate PHP scripts that require more time to process completely. The php.ini file contains the max_execution_time directive, which allows you to set the maximum execution time allowed by PHP, in seconds. The max_execution_time directive will apply to all PHP scripts processed by the Web server. To change the maximum execution time, open the php.ini file on the Web server and look for the following section of code.
;;;;;;;;;;;;;;;;;;; ; Resource Limits ; ;;;;;;;;;;;;;;;;;;; max_execution_time = 120 ; Maximum execution time of each script, in seconds

Most Unix and Windows computers include a telnet program as part of the operating system files. If you do not have a telnet program installed on your computer, you can download a telnet program from the Tucows Web site at www.tucows.com.

www.abccorp.com

www.abccorp.com

RETRIEVE A PHP PAGE

¤ Type the URL or IP
address of the Web server you want to connect to. Then type the port number used by the Web server.

⁄ At the command prompt, type telnet.

› Type GET /. ˇ Type the name of the
PHP page you want to retrieve and then press Enter.

I The HTML code for the PHP page is displayed in the telnet window.
Note: The HTML code may be formatted differently, depending on the Web server and telnet program you are using.

VIEW HTTP HEADERS

¤ Type the URL or IP
address of the Web server you want to connect to. Then type the port number used by the Web server.

⁄ At the command
prompt, type telnet.

› Type HEAD /. ˇ Type the name of the
PHP page for which you want to view the HTTP header information.

I The HTTP header information for the PHP page is displayed.
Note: The information may be formatted differently, depending on the Web server and telnet program you are using.

‹ Press Enter to start the 218
telnet program and connect to the Web server.

‹ Press Enter to start the
telnet program and connect to the Web server.

Á Type http/1.0 and then press Enter twice.

219

PHP
ARRAY FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
Legend
plain courier text = required italics = user-defined

Function
array_slice(array, offset [, length]) array_splice(array, offset [, length [, replacement]]) array_sum(array) array_unique(array) array_unshift(array, variables) array_values(array)

Description Returns a slice from an array. Replaces elements in an array and returns the removed elements. Calculates the sum of values in an array. Removes duplicate values. Pushes elements onto the beginning of an array. Returns all the values in an array. Applies a function to array elements. Sorts an array in descending order and retains index association. Creates an array using variables. Counts array elements. Returns the current array element. Returns the current array element. Makes the last element the current element. Imports variables into the symbol table from an array.

Returns Array Array Mixed Array Integer Array Integer Void

[] = optional ... = list of items | = or
APACHE-SPECIFIC FUNCTIONS

Function
apache_lookup_uri(filename) apache_note(note_name [, note_value]) ascii2ebcdic(ascii_string) ebcdic2ascii(ebcdic_string) getallheaders() virtual(filename)

Description Returns information about a URI. Gets or, if the second parameter is used, sets values in a notes table. Translates a string from ASCII to EBCDIC. Translates a string from EBCDIC to ASCII. Returns HTTP request headers. Performs an Apache sub-request.

Returns Class String Integer Integer Array Integer

array_walk(array, function [, parameter]) arsort(array) asort(array) compact(varnames) count(array) current(array) each(array) end(array)

Sorts an array in ascending order and retains index association. Void Array Integer Mixed Array Mixed Integer Boolean Mixed Integer Integer Void Void Void Mixed Mixed Mixed Array Mixed Void Void Integer Void Void Void Void

ARRAY FUNCTIONS

extract(array [, extract_type [, prefix]])

Function
array([...]) array_count_values(array) array_diff(arrays) array_flip(array) array_intersect(arrays) array_keys(array [, search_value]) array_merge(arrays) array_merge_recursive(arrays) array_multisort(array [, mixed]) array_pad(array, size, value) array_pop(array) array_push(array, variables) array_rand(array [, num_req]) array_reverse(array) array_search(value, array, strict) array_shift(array)

Description Creates an array from provided parameters. Counts the values in an array. Returns values in the first array that do not occur in the other arrays. Flips the values and keys in an array. Returns values in the first array that occur in the other arrays. Returns all keys or only specified keys. Merges arrays. Merges arrays recursively. Sorts several arrays or a multi-dimensional array. Pads an array to the specified size with a value. Removes and returns the last array element. Pushes elements onto the end of an array. Returns one or more random entries from an array. Returns array elements in reverse order. Searches an array for a specified value and returns the corresponding key. Removes and returns the first array element.

Returns Array Array Array Array Array Array Array Array Boolean Array Mixed Integer Mixed Array Mixed Mixed

in_array(value, array, strict) Indicates if a value exists in an array. key(array) krsort(array) ksort(array) list(variables) natcasesort(array) natsort(array) next(array) pos(array) prev(array) range(low, high) reset(array) rsort(array) shuffle(array) sizeof(array) sort(array) uasort(array, function) uksort(array, function) usort(array, function)

Returns the key for the current element. Sorts an array by key in reverse order. Sorts an array by key. Assigns variables as if they were an array. Sorts an array in a case-insensitive "natural order." Sorts an array in a "natural order." Advances the pointer one element in an array. Returns the current array element. Moves the pointer back one element in an array. Creates an array containing the integers in the specified range. Moves the pointer to the first array element. Sorts an array in descending order. Shuffles an array. Returns the number of array elements. Sorts an array in ascending order. Sorts an array using a function and retains index association. Sorts an array by key using a function. Sorts an array by value using a function.

220

221

PHP
CLASS/OBJECT FUNCTIONS

PHP FUNCTIONS QUICK REFERENCE

12

Function
call_user_method(method_name, object [, parameters]) call_user_method_array (method_name, object [, parameters_array]) class_exists(class_name) get_class(object) ASPELL FUNCTIONS get_class_methods(class_name) get_class_vars(class_name)

Description Calls a user method from an object. Calls a user method from an object using an array of parameters. Checks if a class has been defined. Returns the class name of an object. Returns the methods for a class. Returns the default properties for a class. Returns defined classes for the current script. Returns the properties of an object. Returns the parent class name of an object. Determines if an object belongs to a subclass of a specified superclass. Checks if a method exists.

Returns Mixed Mixed Boolean String Array Array Array Array String Boolean Boolean

PHP FUNCTIONS QUICK REFERENCE
Function
aspell_check(link, word) aspell_check_raw(link, word) aspell_new(master, personal) aspell_suggest(link, word)

Description Checks the spelling of a word. Checks the spelling of a word without changing case or trimming. Loads a new directory. Suggests spellings for a word.

Returns Boolean Boolean Integer Array

get_declared_classes() get_object_vars(object) get_parent_class(object) is_subclass_of(object, superclass) method_exists(object, method_name)

CALENDAR FUNCTIONS CLIENT URL LIBRARY (CURL) FUNCTIONS

Function
easter_date([year]) easter_days([year]) frenchtojd(french) gregoriantojd(gregorian) jddayofweek(julianday, mode) jdmonthname(julianday, mode) jdtofrench(julianday) jdtogregorian(julianday) jdtojewish(julianday) jdtojulian(julianday) jdtounix(julianday) jewishtojd(jewish) juliantojd(julian) unixtojd(timestamp)

Description Returns a UNIX timestamp for midnight on Easter in a specified year. Returns the number of days after March 21 that Easter falls in a specified year. Converts a French Republican Calendar date to Julian Day Count. Converts a Gregorian Calendar date to Julian Day Count. Returns the day of the week. Returns the month of the year. Converts a Julian Day Count to a French Republican Calendar date. Converts a Julian Day Count to a Gregorian Calendar date. Converts a Julian Day Count to a Jewish Calendar date. Converts a Julian Day Count to a Julian Calendar date. Converts a Julian Day Count to a UNIX timestamp. Converts a Jewish Calendar date to Julian Day Count. Converts a Julian Calendar date to Julian Day Count. Converts a UNIX timestamp to Julian Day Count.

Returns Integer Integer Integer Integer Mixed String String String String String Integer Integer Integer Integer

Function
curl_close(handle) curl_exec(handle) curl_init([url]) curl_setopt(handle, option, value) curl_version()

Description Closes a CURL session. Executes a CURL session. Initializes a CURL session. Sets an option for a CURL session. Returns the current CURL version.

Returns Void Boolean Integer Boolean String

DATABASE FUNCTIONS

Database Abstraction Layer Functions Function
dba_close(handle) dba_delete(key, handle) dba_exists(key, handle) dba_fetch(key, handle) dba_firstkey(handle)

Description Closes a database. Deletes an entry in a database. Checks if a key exists in a database. Returns the requested data. Returns the first key in a database.

Returns Void String Boolean String String

222

223

PHP

PHP FUNCTIONS QUICK REFERENCE

12

DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

DBM Functions Function
dblist() dbmclose(dbm_id) dbmdelete(dbm_id, key)

Description Describes the DBM-compatible library being used. Closes a DBM database. Deletes a value from a DBM database. Checks if a value exists for a key in a DBM database. Returns a value for a key from a DBM database. Returns the first key in a DBM database. Inserts a key-value pair into a DBM database. Returns the next key in a DBM database. Opens a DBM database.

Returns String Boolean Boolean Boolean String String Integer String Integer Boolean

Database Abstraction Layer Functions (Continued) Function
dba_nextkey(handle) dba_open(path, mode, handler) dba_optimize(handle) dba_popen(path, mode, handler [, ...]) dba_replace(key, value, handle) dba_sync(handle)

dbmexists(dbm_id, key)

Description Returns the next key in a database. Opens a database. Optimizes a database. Opens a persistent connection to a database. Replaces or inserts an entry in a database. Synchronizes a database.

dba_insert(key, value, handle) Inserts an entry into a database.

Returns Boolean String Integer Boolean Integer Boolean Boolean

dbmfetch(dbm_id, key) dbmfirstkey(dbm_id) dbminsert(dbm_id, key, value) dbmnextkey(dbm_id, key) dbmopen(filename, flags)

dbmreplace(dbm_id, key, value) Replaces a value in a DBM database.

Informix Functions Function
ifx_affected_rows(result_id)

Description Returns the number of rows affected by a query. Sets the default BLOB mode. Sets the default byte mode. Closes the connection to an Informix database. Opens a connection to an Informix database. Copies a BLOB object. Creates a BLOB object. Creates a char object. Executes a prepared SQL statement. Returns the last error. Returns the error message for the last error or a specified error code. Fetches a row as an enumerated array. Returns the field names and SQL field properties. Returns the field names and SQL field types.

Returns Integer Void Void Integer Integer Integer Integer Integer Integer String String Array Array Array

dBase Functions Function
dbase_add_record(dbase_id, record) dbase_close(dbase_id)

ifx_blobinfile_mode(mode)

Description Adds a record to a dBase database. Closes a dBase database. Deletes a record from a dBase database. Returns a record from a dBase database. Returns a record from a dBase database as an associative array. Returns the number of fields in a dBase database. Returns the number of records in a dBase database. Opens a dBase database. Removes deleted records from a dBase database.

Returns Boolean Boolean Integer Boolean Array Array Integer Integer Integer Boolean Boolean

ifx_byteasvarchar(mode) ifx_close([link_identifier]) ifx_connect([database [, userid [, password]]]) ifx_copy_blob(bid) ifx_create_blob(type, mode, param) ifx_create_char(param) ifx_do(result_id) ifx_error() ifx_errormsg([error_code]) ifx_fetch_row(result_id [, position]) ifx_fieldproperties (result_id) ifx_fieldtypes(result_id)

dbase_create(filename, fields) Creates a dBase database. dbase_delete_record (dbase_id, record) dbase_get_record(dbase_id, record) dbase_get_record_with_names (dbase_id, record) dbase_numfields(dbase_id) dbase_numrecords(dbase_id) dbase_open(filename, flags) dbase_pack(dbase_id)

dbase_replace_record Replaces a record in a dBase database. (dbase_id, record, record_num)

224

225

PHP
DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

InterBase Functions

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

Function
ibase_close([connection_id])

Description Closes the connection to an InterBase database.

Returns Integer Integer Integer

ibase_commit([link_identifier, Commits a transaction. trans_number]) ibase_connect(database [, username [, password [, charset [, buffers [, dialect [, role]]]]]])

Opens a connection to an InterBase database.

Informix Functions (Continued) Function
ifx_free_blob(bid) ifx_free_char(bid) ifx_free_result(result_id) ifx_get_blob(bid) ifx_get_char(bid) ifx_getsqlca(result_id) ifx_htmltbl_result(result_id [, html_table_options]) ifx_nullformat(mode) ifx_num_fields(result_id) ifx_num_rows(result_id) ifx_pconnect([database [, userid [, password]]]) ifx_prepare(query [, link_identifier [, cursor_type [, blobidarray]]]) ifx_query(query [, link_identifier [, cursor_type [, blobidarray]]]) ifx_textasvarchar(mode) ifx_update_blob(bid, content) ifx_update_char(bid, content) ifxus_close_slob(bid) ifxus_create_slob(mode) ifxus_free_slob(bid) ifxus_open_slob(bid, mode) ifxus_read_slob(bid, bytes) ifxus_seek_slob(bid, mode, offset) ifxus_tell_slob(bid)

Description Deletes a BLOB object. Deletes a char object. Frees resources used by a query. Returns the contents of a BLOB object. Returns the contents of a char object. Returns the contents of sqlca.sqlerrd[0..5]after a query. Formats rows of a query in an HTML table. Sets the default value for NULL values in a fetched row. Returns the number of fields in a query. Returns the number of rows fetched for a query. Opens a persistent connection to an Informix database. Prepares an SQL statement for execution.

Returns Integer Integer Integer Integer Integer Array Integer Void Integer Integer Integer Integer

ibase_errmsg() ibase_execute(query [, bind_args]) ibase_fetch_object (result_id) ibase_fetch_row(result_id) ibase_field_info(result_id, field_number) ibase_free_query(query) ibase_free_result(result_id) ibase_num_fields(result_id) ibase_pconnect(database [, username [, password [, charset [, buffers [, dialect [, role]]]]]]) ibase_prepare ([link_identifier, query]) ibase_query([link_identifier, query [, bind_args]])

Returns an error message. Executes a prepared query. Returns a row as an object. Returns the next row in a result set. Returns information about a field in a result set. Frees a prepared query. Frees a result set. Returns the number of fields in a result set. Opens a persistent connection to an InterBase database.

String Integer Object Array Array Integer Integer Integer Integer

Prepares a query for execution. Executes a query. Rolls back a transaction. Sets the format of timestamp, date and time columns returned from queries. Begins a transaction.

Integer Integer Integer Integer Integer

Executes a query.

Integer

ibase_rollback ([link_identifier, trans_number]) ibase_timefmt(format, [columntype]) ibase_trans([trans_args [, link_identifier]])

Sets the default text mode. Updates a BLOB object. Updates a char object. Deletes a SLOB object. Creates and opens a SLOB object. Deletes a SLOB object. Opens a SLOB object. Reads bytes from a SLOB object. Sets the current seek position of a SLOB object. Returns the current seek position of a SLOB object.

Void Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer

Microsoft SQL Server Functions Function
mssql_close(link_id) mssql_connect([server_name [, username [, password]]]) mssql_data_seek(result_id, row_number) mssql_fetch_array(result_id)

Description Closes the connection to an MS SQL database. Opens a connection to an MS SQL database. Moves to a specified row in a result set. Returns the next row as an array.

Returns Integer Integer Integer Integer

ifxus_write_slob(bid, content) Writes content to a SLOB object.

226

227

PHP
DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

mSQL Functions (Continued) Function
msql_connect([hostname]) msql_create_db(name [, link_id]) msql_createdb(name [, link_id])

Description Opens a connection to an mSQL database. Creates an mSQL database. Creates an mSQL database. Moves to a specified row in a result set. Returns the name of an mSQL database. Deletes an mSQL database. Deletes an mSQL database. Returns an error message from the last SQL operation. Returns the next row as an array. Returns field information. Returns the next row as an object. Returns the next row as an enumerated array. Moves to a specified field in a result set. Returns flags for a field in a result set.

Returns Integer Integer Integer Integer String Integer Integer String Integer Object Integer Array Integer String Integer String Integer String Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer

Microsoft SQL Server Functions (Continued) Function
mssql_fetch_field(result_id [, field_offset]) mssql_fetch_object (result_id) mssql_fetch_row(result_id) mssql_field_length(result_id [, offset]) mssql_field_name(result_id [, offset]) mssql_field_seek(result_id, field_offset) mssql_field_type(result_id [, offset]) mssql_free_result(result_id) mssql_get_last_message() mssql_min_error_severity (severity) mssql_min_message_severity (severity) mssql_num_fields(result_id) mssql_num_rows(result_id) mssql_pconnect([servername [, username [, password]]])

Description Returns field information. Returns the next row as an object. Returns the next row as an enumerated array. Returns the length of a field in a result set. Returns the name of a field in a result set. Moves to a specified field in a result set. Returns the type of a field in a result set. Frees memory used by a result set. Returns the last server message. Sets the lower error severity. Sets the lower message severity. Returns the number of fields in a result set. Returns the number of rows in a result set. Opens a persistent connection to an MS SQL database.

Returns Object Integer Array Integer Integer Integer String Integer String Void Void Integer Integer Integer Integer Integer Integer

msql_data_seek(query_id, row_number) msql_dbname(query_id, index) msql_drop_db(name, link_id) msql_dropdb(name, link_id) msql_error() msql_fetch_array(query_id [, result_type]) msql_fetch_field(query_id, field_offset) msql_fetch_object(query_id [, result_type]) msql_fetch_row(query_id) msql_field_seek(query_id, field_offset) msql_fieldflags(query_id, field)

msql_fieldlen(query_id, field) Returns the length of a field in a result set. msql_fieldname(query_id, field) msql_fieldtable(query_id, field) msql_fieldtype(query_id, field) msql_free_result(query_id) msql_freeresult(query_id) msql_list_dbs() msql_list_fields(database, table) msql_list_tables(database)

Returns the name of a field in a result set. Returns the name of the table a field belongs to. Returns the type of a field in a result set. Frees the memory used by a result set. Frees the memory used by a result set. Lists the mSQL databases on a server. Lists the fields in a table. Lists the tables in an mSQL database. Lists the mSQL databases on a server. Lists the fields in a table. Lists the tables in an mSQL database. Returns the number of fields in a result set. Returns the number of rows in a result set.

mssql_query(query [, link_id]) Executes a query. mssql_result(result_id, row, field) mssql_select_db(database, link_id)

Returns the contents of a cell in a result set. Makes an MS SQL database the current database.

mSQL Functions Function Description msql(database, query, link_id) Executes a query.
msql_affected_rows(query_id) msql_close(link_id)

msql_listdbs()

Returns Integer Integer Integer

msql_listfields(database, table) msql_listtables(database) msql_num_fields(query_id) msql_num_rows(query_id)

Returns the number of rows a query affects. Closes the connection to an mSQL database.

228

229

PHP

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

DATABASE FUNCTIONS (CONTINUED)

MySQL Functions (Continued) Function
mysql_error([link_id]) mysql_fetch_array(result_id [, result_type]) mysql_fetch_assoc(result_id) mysql_fetch_field(result_id [, field_offset]) mysql_fetch_lengths(result_id) mysql_fetch_object(result_id [, result_type]) mysql_fetch_row(result_id) mysql_field_flags(result_id, field) mysql_field_len(result_id, field) mysql_field_name(result_id, field) mysql_field_seek(result_id, field_offset) mysql_field_table(result_id, field)

Description Returns the error message from the last MySQL operation. Returns the next row as an array. Returns a row as an associative array. Returns field information. Returns the length of each field in a result set. Returns the next row as an object. Returns the next row as an enumerated array. Returns the flags for a field in a result set. Returns the length of a field in a result set. Returns the name of a field in a result set. Moves to a specified field offset. Returns the name of the table a field belongs to. Returns the type of a field in a result set. Frees the memory used by a result set. Returns the ID generated from the last INSERT operation. Lists the databases on a MySQL server. Lists the fields in a table. Lists the tables in a MySQL database. Returns the number of fields in a result set. Returns the number of rows in a result set. Opens a persistent connection to a MySQL database.

Returns String Array Array Object Array Object Array String Integer String Integer String String Integer Integer Integer Integer Integer Integer Integer Integer Integer Mixed Integer String

mSQL Functions (Continued) Function
msql_numfields(query_id) msql_numrows(query_id) msql_pconnect([hostname]) msql_query(query, link_id) msql_regcase(string) msql_result(query_id, row, field) msql_select_db(database, link_id) msql_selectdb(database, link_id) msql_tablename(query_id, field)

Description Returns the number of fields in a result set. Returns the number of rows in a result set. Opens a persistent connection to an mSQL database. Executes a query. Makes a regular expression for a case-insensitive match. Returns the contents of a cell in a result set. Makes an mSQL database the current database. Makes an mSQL database the current database. Returns the name of the table for a field.

Returns Integer Integer Integer Integer String Integer Integer Integer String

MySQL Functions Function
mysql_affected_rows(link_id) mysql_change_user(user, password [, database [, link_id]]) mysql_close([link_id]) mysql_connect([hostname [:port] [:/path/to/socket] [,username [,password]]]) mysql_create_db(database [, link_id]) mysql_data_seek(result_id, row_number) mysql_db_name(result_id, row [, field]) mysql_db_query(database, query [, link_id]) mysql_drop_db(database_name [, link_id]) mysql_errno([link_id])

Description Returns the number of rows affected by the last query. Changes the logged in user of the connection. Closes the connection to a MySQL database. Opens a connection to a MySQL database. Creates a MySQL database. Moves to a specified row in a result set. Returns result data. Executes a query. Deletes a MySQL database. Returns the error number from the last MySQL operation.

Returns Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer

mysql_field_type(result_id, field) mysql_free_result(result_id) mysql_insert_id([link_id]) mysql_list_dbs([link_id]) mysql_list_fields(database, table [, link_id]) mysql_list_tables(database) mysql_num_fields(result_id) mysql_num_rows(result_id) mysql_pconnect([hostname [:port] [:/path/to/socket] [, username [, password]]])

mysql_query(query [, link_id]) Executes a query. mysql_result(result_id, row [, field]) mysql_select_db(database [, link_id]) mysql_tablename(result_id, index)

Returns the contents of a cell in a result set. Makes a MySQL database the current database. Returns the name of the table for a field.

230

231

PHP
DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

Oracle 8 Functions (Continued) Function
OCIPLogon(username, password [, database]) OCIResult(statement, column) OCIRollback(connection) OCIRowCount(statement)

Description Creates a persistent connection to an Oracle database. Returns column data for a fetched row. Aborts all pending transactions on a connection. Returns the number of affected rows in a result set. Returns server version information. Returns the type of an OCI statement.

Returns Integer Mixed Integer Integer String String

Oracle 8 Functions Function
OCIBindByName(statement, ph_name, &variable, length [, type]) OCIColumnIsNULL(statement, column) OCIColumnName(statement, column_number) OCIColumnSize(statement, column) OCIColumnType(statement, column_number) OCICommit(connection) OCIDefineByName(statement, column_name, &variable [, type]) OCIError([statement | connection | global])

Description Binds a PHP variable to an Oracle Placeholder. Tests whether a column contains a NULL value. Returns the name of a column in a result set. Returns the size of a column in a result set. Returns the type of a column in a result set. Commits pending transactions on a connection. Fetches a column into a PHP variable. Returns the code for the last error.

Returns Integer Integer String Integer Mixed Integer Integer Array Integer Integer Integer Integer Integer Integer Integer Void Integer Integer Integer String Integer Integer Integer

OCIServerVersion(connection) OCIStatementType(statement)

Oracle Functions Function Description Returns Integer Integer String Integer String Integer Integer Integer Integer String Integer Integer Integer Integer Mixed Integer Integer Integer Integer Integer Integer Integer Integer

ora_bind(cursor, &variable, Binds a PHP variable to an Oracle parameter. SQLparameter, length [, type]) ora_close(cursor)

Closes an Oracle cursor.

ora_columnname(cursor, column) Returns the name of a column. ora_columnsize(cursor, column) Returns the size of a column. ora_columntype(cursor, column) Returns the type of a column. ora_commit(connection) ora_commitoff(connection) ora_commiton(connection) ora_do(connection, query)

Commits a transaction. Disables automatic committing of transactions. Enables automatic committing of transactions. Parses and executes a statement. Then fetches the first row. Returns the code for the last error. Executes a parsed statement on a cursor. Fetches a row from a cursor. Fetches a row into a result array. Returns data from a column. Closes an Oracle connection. Opens an Oracle connection. Returns the number of columns in a result set. Returns the number of rows in a result set. Opens an Oracle cursor. Parses an SQL statement. Opens a persistent connection to an Oracle database. Aborts a transaction.

OCIExecute(statement [, mode]) Executes an SQL statement. OCIFetch(statement) OCIFetchInto(statement, result [, mode]) OCIFetchStatement(statement, variable) OCIFreeCursor(statement) OCIFreeDesc(lob) OCIFreeStatement(statement) OCIInternalDebug(OnOff) OCILogOff(connection) OCILogon(username, password [, database]) OCINewCursor(connection) OCINewDescriptor(connection [, type]) OCINLogon(username, password [, database]) OCINumCols(statement) OCIParse(connection, query)

Fetches the next row from a result set. Fetches the next row from a result set into an array. Fetches all rows from a result set into an array. Frees the resources used by the cursor for a statement. Deletes a large object descriptor. Frees the resources used by a statement. Enables or disables internal debugging. Closes the connection to an Oracle Database. Creates a connection to an Oracle database. Returns a new cursor for a connection. Initializes a new empty LOB or FILE descriptor. Creates a new connection to an Oracle database. Returns the number of columns in a result set. Parses a query.

ora_error(cursor | connection) Returns the message for the last error. ora_errorcode(cursor | connection) ora_exec(cursor) ora_fetch(cursor) ora_fetch_into(cursor, result [, flags]) ora_getcolumn(cursor, column) ora_logoff(connection) ora_logon(user, password) ora_numcols(cursor_ind) ora_numrows(cursor_ind) ora_open(connection) ora_parse(cursor, SQL_statement, defer) ora_plogon(user, password) ora_rollback(connection)

232

233

PHP
DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

PostgreSQL Functions (Continued)

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

Function
pg_loopen(connection, object_id, mode) pg_loread(file_descriptor, len) pg_loreadall(file_descriptor)

Description Opens a large object. Reads a specified number of bytes from a large object. Reads an entire large object and sends it to a browser. Deletes a large object. Writes to a large object. Returns the number of fields in a result set. Returns the number of rows in a result set. Returns connection options. Opens a persistent connection to a PostgreSQL database. Returns the port number for a connection. Sends a NULL-terminated string to the PostgreSQL backend server. Returns values from a result set. Sets the client encoding. Enables tracing of a PostgreSQL connection. Returns the connection's associated tty name. Disables tracing of a PostgreSQL connection.

Returns Integer String Void Void Integer Integer Integer String Integer Integer Boolean Mixed Integer Boolean String Boolean

PostgreSQL Functions Function
pg_client_encoding ([connection]) pg_close(connection) pg_cmdtuples(result_id) pg_connect(conn_string) pg_dbname(connection) pg_end_copy([connection]) pg_errormessage(connection) pg_exec(connection, query) pg_fetch_array(result, row [, result_type]) pg_fetch_object(result, row [, result_type]) pg_fetch_row(result, row) pg_fieldisnull(result_id, row, field) pg_fieldname(result_id, field_number) pg_fieldnum(result_id, field_name) pg_fieldprtlen(result_id, row_number, field_name) pg_fieldsize(result_id, field_number) pg_fieldtype(result_id, field_number) pg_freeresult(result_id) pg_getlastoid(result_id) pg_host(connection) pg_loclose(file_descriptor) pg_locreate(connection) pg_loexport(object_id, file [, connection_id]) pg_loimport(file [, connection_id])

pg_lounlink(connection, object_id)

Description Returns the client encoding. Closes a PostgreSQL connection. Returns the number of tuples affected by queries. Opens a connection to a PostgreSQL database. Returns the name of a database. Synchronizes PostgreSQL frontend with backend after a copy. Returns an error message. Executes a query. Fetches a row as an array. Fetches a row as an object. Fetches a row as an enumerated array. Indicates whether a field contains a NULL value. Returns the name of a field in a result set. Returns the number of a field in a result set. Returns the printed length of a field in a result set. Returns the internal storage size of a field in a result set. Returns the type of a field in a result set. Frees the memory used by a result set. Returns the last object identifier. Returns the connection's associated host name. Closes a large object. Creates a large object. Exports a large object to a file. Imports a large object from a file.

Returns String Boolean Integer Integer String Boolean String Integer Array Object Array Integer String Integer Integer Integer String Integer Integer String Void Integer Boolean Integer

pg_lowrite(file_descriptor, buf) pg_numfields(result_id) pg_numrows(result_id) pg_options(connection) pg_pconnect(conn_string) pg_port(connection) pg_put_line([connection, data]) pg_result(result_id, row_number, field_name) pg_set_client_encoding ([connection, encoding]) pg_trace(filename [, mode [, connection]]) pg_tty(connection) pg_untrace([connection])

Sybase Functions Function
sybase_affected_rows ([link_id]) sybase_close(link_id) sybase_connect(server_name, username, password [, charset]) sybase_data_seek(result_id, row_number) sybase_fetch_array(result_id) sybase_fetch_field(result_id [, field_offset]) sybase_fetch_object(result_id) sybase_fetch_row(result_id) sybase_field_seek(result_id, field_offset)

Description Returns the number of rows affected by the last query. Closes the Sybase connection. Opens a connection to a Sybase server. Moves to a specified row in a result set. Fetches the next row as an array. Returns field information. Fetches the next row as an object. Fetches the next row as an enumerated array. Moves to a specified field offset.

Returns Integer Boolean Integer Boolean Array Object Integer Array Integer

234

235

PHP
DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

Unified ODBC Functions (Continued) Function
odbc_connect(DSN, userid, password [, cursor_type]) odbc_cursor(result_id) odbc_do(connection_id, query)

Description Connects to an ODBC data source. Returns the cursorname for a result set. Prepares and executes a query. Returns the last error code. Prepares and executes a query. Executes a prepared SQL statement. Fetches a row from a result set. Fetches a row from a result set. Returns the length of a field in a result set. Returns the name of a field in a result set. Returns the column number for a field in a result set. Returns the length of a field in a result set. Returns the scale of a field in a result set. Returns the type of a field in a result set. Returns information about foreign keys in a table.

Returns Integer String Integer Integer Integer Integer Integer Integer Integer Integer String Integer String String String Integer

Sybase Functions (Continued) Function
sybase_free_result(result_id) sybase_get_last_message() sybase_min_client_severity (severity) sybase_min_error_severity (severity) sybase_min_message_severity (severity) sybase_min_server_severity (severity) sybase_num_fields(result_id) sybase_num_rows(result_id) sybase_pconnect(server_name, username, password [, charset]) sybase_query(query, link_id) sybase_result(result_id, row, field) sybase_select_db(database, link_id)

Description Frees the memory used by a result set. Returns the last message from the server. Sets the minimum client severity level. Sets the minimum error severity level. Sets the minimum message severity level. Sets the minimum server severity level. Returns the number of fields in a result set. Returns the number of rows in a result set. Opens a persistent connection to a Sybase server. Executes a Sybase query. Fetches the contents of a cell in a result set. Makes a Sybase database the current database.

Returns Boolean String Void Void Void Void Integer Integer Integer Integer String Boolean

odbc_error([connection_id])

odbc_errormsg([connection_id]) Returns the last error message. odbc_exec(connection_id, query) odbc_execute(result_id, [parameters]) odbc_fetch_into(result_id [, row_number, result]) odbc_fetch_row(result_id [, row_number]) odbc_field_len(result_id, field_number) odbc_field_name(result_id, field_number) odbc_field_num(result_id, field_name) odbc_field_precision (result_id, field_number) odbc_field_scale(result_id, field_number) odbc_field_type(result_id, field_number) odbc_foreignkeys (connection_id, pk_qualifier, pk_owner, pk_table, fk_qualifier, fk_owner, fk_table)

Unified ODBC Functions Function
odbc_autocommit (connection_id, [OnOff]) odbc_binmode(result_id, mode) odbc_close(connection_id) odbc_close_all() odbc_columnprivileges (connection_id [, qualifier [, owner [, table_name [, column_name]]]]) odbc_columns(connection_id [, qualifier [, owner [, table_name [, column_name]]]]) odbc_commit(connection_id)

Description Sets or gets autocommit behavior for a database. Sets the mode for converting binary data. Closes an ODBC connection. Closes all ODBC connections. Lists columns and privileges for a table.

Returns Integer Integer Void Void Integer

odbc_free_result(result_id) odbc_gettypeinfo (connection_id [, data_type]) odbc_longreadlen(result_id, length) odbc_num_fields(result_id) odbc_num_rows(result_id) odbc_pconnect(DSN, userid, password [, cursor_type])

Frees the memory used by a result set. Returns information about the data types supported by a data source. Determines the number of bytes returned by fields of the LONG data type. Returns the number of fields in a result set. Returns the number of rows in a result set. Opens a persistent connection to an ODBC data source. Prepares an SQL statement for execution. Gets the column names that make up the primary key for a table.

Integer Integer Integer Integer Integer Integer Integer Integer

Lists all column names in a specified range.

Integer

odbc_prepare(connection_id, query) odbc_primarykeys (connection_id, qualifier, owner, table)

Commits the ODBC transactions on a connection.

Integer

236

237

PHP

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
DATABASE FUNCTIONS (CONTINUED)

DATE AND TIME FUNCTIONS (CONTINUED)

Function
gmstrftime(format [, timestamp]) localtime([timestamp [, is_associative]]) microtime()

Description Formats a time/date using locale settings and returns a GMT time/date. Returns the local time. Returns the current UNIX timestamp with microseconds. Returns the UNIX timestamp for a date.

Returns String Array String Integer String Integer

Unified ODBC Functions (Continued) Function Description Retrieves information about the parameters for procedures. Returns Integer

mktime(hour, minute, second, month, day, year [, is_dst])

odbc_procedurecolumns (connection_id, [, qualifier [, owner [ ,proc [, column]]]]) odbc_procedures(connection_id, Gets a list of procedures in a data source. [, qualifier [, owner [, name]]]) odbc_result(result_id, field) odbc_result_all(result_id [, format]) odbc_rollback(connection_id) odbc_setoption(ID, function, option, parameter) odbc_specialcolumns (connection_id, type, qualifier, owner, table, scope, nullable)

strftime(format [, timestamp]) Formats a local time/date using locale settings. strtotime(time [, now]) time()

Parses an English datetime description into a UNIX timestamp. Integer Returns the current UNIX time in seconds.

Integer String Integer Integer Integer Integer

Returns the contents of a field in a result set. Prints a result set in an HTML table. Aborts all transactions on a connection. Sets an ODBC option. Returns the optimal set of columns that uniquely identifies a row or columns that are automatically updated.

DIRECTORY FUNCTIONS

Function
chdir(directory) chroot(directory) closedir(dir_handle) dir(directory) getcwd()

Description Sets a directory as the current directory. Sets a directory as the current root directory. Closes a directory handle. Returns a directory class. Returns the current working directory. Opens a directory handle. Reads the next entry from a directory. Resets a directory handle to the beginning of the directory.

Returns Integer Integer Void New String Integer String Void

odbc_statistics(connection_id, Returns statistics about a table. qualifier, owner, table_name, unique, accuracy) odbc_tableprivileges (connection_id [, qualifier [, owner [, name]]]) odbc_tables(connection_id [, qualifier [, owner [, name [, types]]]])

Integer Integer

opendir(path) readdir(dir_handle) rewinddir(dir_handle)

Lists the tables and their privileges. Lists the tables in a data source.

DOM XML FUNCTIONS

Integer Function
domxml_add_root(doc, name) domxml_attributes(node)

Description Adds a root element node to a DOM document. Returns all attributes of a node. Returns all children of a node. Creates an XML document from the DOM representation. Returns an attribute of a node. Adds a new child to a node. Creates a DOM document from scratch. Returns the root element node of a DOM document. Sets an attribute of a node.

Returns Resource Array Array String Object Resource Object Object Object

DATE AND TIME FUNCTIONS

domxml_children(doc | node)

Function
checkdate(month, day, year) date(format [, timestamp]) getdate([timestamp]) gettimeofday() gmdate(format [, timestamp])

Description Validates a date. Formats a local time/date. Returns date/time information. Returns the current time. Formats a local date/time and returns a GMT date/time.

Returns Integer String Array Array String Integer

domxml_dumpmem(doc) domxml_get_attribute(node, name) domxml_new_child(name, content) domxml_new_xmldoc(version) domxml_root(doc) domxml_set_attribute(node, name, value)

gmmktime(hour, minute, second, Returns the UNIX timestamp for a GMT time/date. month, day, year [, is_dst])

238

239

PHP
FILESYSTEM FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
DOM XML FUNCTIONS (CONTINUED)

Function
fclose(file_pointer) feof(file_pointer) fflush(file_pointer) fgetc(file_pointer)

Description Closes a file. Tests for end-of-file on a file. Flushes the buffered output to a file. Reads the next character from a file. Returns the next line of a file. Reads a line of a specific length from a file. Reads a line of a specific length from a file and strips PHP and HTML tags. Reads an entire file. Checks whether a file exists. Returns the time a file was last accessed. Returns the time the inode data of a file was last changed. Returns a file owner's group ID. Returns a file's inode number. Returns the time a file was last modified. Returns a file owner's user ID. Returns a file's permissions. Returns the size of a file. Returns the type of a file. Sets or releases a lock on a file. Opens a file. Outputs all remaining data from a file. Writes a string of a specific length to a file. Reads a specific number of characters from a file. Parses input from a file according to a specified format. Moves the pointer in a file. Returns information about a file. Returns the position of the pointer in a file. Truncates a file to a specific length. Writes a string of a specific length to a file. Indicates whether a file is a directory.

Returns Integer Integer Integer String Array String String Array Boolean Integer Integer Integer Integer Integer Integer Integer Integer String Boolean Integer Integer Integer String Mixed Integer Array Integer Integer Integer Boolean

Function
xmldoc(str) xmldocfile(filename) xmltree(str) xpath_eval(xpath_context) xpath_new_context(doc)

Description Creates a DOM object from an XML document. Creates a DOM object from an XML file. Creates a tree of PHP objects from an XML document. Evaluates an xpath expression. Creates a new xpath context.

Returns Object Object Object Array Object

fgetcsv(file_pointer, length [, delimiter]) fgets(file_pointer, length) fgetss(file_pointer, length [, allowable_tags]) file(filename [, use_include_path]) file_exists(filename) fileatime(filename)

ERROR HANDLING AND LOGGING FUNCTIONS

filectime(filename) filegroup(filename)

Function
error_log(message, message_type [, destination [, extra_headers]]) error_reporting([level]) restore_error_handler() set_error_handler (error_handler) trigger_error(error_msg [, error_type]) user_error(error_msg [, error_type])

Description Sends an error message. Sets which PHP errors are reported. Restores the previous error handler function. Sets a user-defined error handler function. Generates a user-level error message. Generates a user-level error message.

Returns Integer Integer Void String Void Void

fileinode(filename) filemtime(filename) fileowner(filename) fileperms(filename) filesize(filename) filetype(filename) flock(file_pointer, operation [, wouldblock]) fopen(filename, mode [, use_include_path]) fpassthru(file_pointer)

FILESYSTEM FUNCTIONS

fputs(file_pointer, string [, length]) fread(file_pointer, length)

Function
basename(path) chgrp(filename, group) chmod(filename, mode) chown(filename, user) clearstatcache() copy(source, destination) dirname(path) diskfreespace(directory)

Description Returns the filename from a path. Assigns a file to a group. Changes the mode of a file. Changes the owner of a file. Clears the file stat cache. Copies a file. Returns the directory from a path. Returns the available space in a directory.

Returns String Integer Integer Integer Void Integer String Float

fscanf(handle, format [, var1...]) fseek(file_pointer, offset [, whence]) fstat(file_pointer) ftell(file_pointer) ftruncate(file_pointer, size) fwrite(file_pointer, string [, length]) is_dir(filename)

240

241

PHP
FORMS DATA FORMAT FUNCTIONS

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
FILESYSTEM FUNCTIONS (CONTINUED)

Function
fdf_close(fdf_document) fdf_create() fdf_get_file(fdf_document) fdf_get_status(fdf_document)

Description Closes an FDF document. Creates an FDF document. Returns the value of the /F key in an FDF document. Returns the value of the /STATUS key in an FDF document. Returns the value of a field in an FDF document. Returns the name of the next field in an FDF document. Opens an FDF document. Saves an FDF document. Sets the appearance of a field in an FDF document. Sets the value of the /F key in an FDF document. Sets flags of a field in an FDF document. Sets a JavaScript action for a field in an FDF document. Sets an option of a field in an FDF document. Sets the value of the /STATUS key in an FDF document. Sets a submit form action for a field in an FDF document. Sets the value of a field in an FDF document.

Returns Boolean Integer String String String String Integer Integer Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean

Function
is_executable(filename) is_file(filename) is_link(filename) is_readable(filename) is_uploaded_file(filename) is_writable(filename) is_writeable(filename) link(target, link) linkinfo(path) lstat(filename) mkdir(pathname, mode) move_uploaded_file(filename, destination) pclose(file_pointer) popen(command, mode) readfile(filename [, use_include_path]) readlink(path) realpath(path) rename(oldname, newname) rewind(file_pointer) rmdir(directory) set_file_buffer (file_pointer, buffer) stat(filename) symlink(target, link) tempnam(directory, prefix) tmpfile() touch(filename [, time]) umask(mask) unlink(filename)

Description Indicates whether a file is executable. Indicates whether a file is a regular file. Indicates whether a file is a symbolic link. Indicates whether a file is readable. Indicates whether a file was uploaded via HTTP POST. Indicates whether a file can be written to. Indicates whether a file can be written to. Creates a hard link. Returns information about a link. Returns information about a file or a symbolic link. Creates a directory. Moves an uploaded file to a new location. Closes a process file pointer. Opens a process file pointer. Reads and outputs a file. Returns the target of a symbolic link. Returns the canonicalized absolute pathname. Renames a file. Rewinds the pointer to the beginning of a file. Removes a directory. Sets the size of the buffer for a file. Returns information about a file. Creates a symbolic link. Creates a unique temporary file name. Creates a temporary file. Sets the modification time of a file. Changes the current umask. Deletes a file.

Returns Boolean Boolean Boolean Boolean Boolean Boolean Boolean Integer Integer Array Integer Boolean Integer Integer Integer String String Integer Integer Integer Integer Array Integer String Integer Integer Integer Integer

fdf_get_value(fdf_document, fieldname) fdf_next_field_name (fdf_document, fieldname) fdf_open(filename) fdf_save(filename) fdf_set_ap(fdf_document, fieldname, face, filename, pagenumber) fdf_set_file(fdf_document, filename) fdf_set_flags(fdf_document, fieldname, whichFlags, newFlags) fdf_set_javascript_action (fdf_document, fieldname, trigger, script) fdf_set_opt(fdf_document, fieldname, element, string1, string2) fdf_set_status(fdf_document, status) fdf_set_submit_form_action (fdf_document, fieldname, trigger, script, flags) fdf_set_value(fdf_document, fieldname, value, isname)

FTP FUNCTIONS

Function
ftp_cdup(ftp_stream) ftp_chdir(ftp_stream, directory) ftp_connect(host [, port]) ftp_delete(ftp_stream, path) ftp_fget(ftp_stream, fp, remote_file, mode)

Description Changes to the parent directory on an FTP server. Changes to another directory on an FTP server. Opens a connection to an FTP server. Deletes a file on an FTP server. Downloads a file from an FTP server and saves it to a file.

Returns Integer Integer Integer Integer Integer

242

243

PHP

PHP FUNCTIONS QUICK REFERENCE

12

FUNCTION HANDLING FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE
FTP FUNCTIONS (CONTINUED)

Function
func_get_arg(arg_num) func_get_args() func_num_args()

Description Returns an item from the argument list. Returns a function's argument list. Returns the number of arguments passed to a function. Checks if a function has been defined. Returns all defined functions. Registers a function to be executed when the script finishes processing.

Returns Mixed Array Integer Boolean Array Integer

Function

Description

ftp_fput(ftp_stream, Uploads data from a file to an FTP server. remote_file, fp, mode) ftp_get(ftp_stream, Downloads a file from an FTP server. local_file, remote_file, mode) ftp_login(ftp_stream, username, password) ftp_mdtm(ftp_stream, remote_file) ftp_mkdir(ftp_stream, directory) ftp_nlist(ftp_stream, directory) ftp_pasv(ftp_stream, pasv)

Returns Integer Integer Integer

function_exists(function_name) get_defined_functions() register_shutdown_function (function)

Logs in an FTP connection. Returns the time a file was last modified on an FTP server. Creates a directory on an FTP server. Returns a list of files in a directory on an FTP server. Turns passive mode on or off for an FTP server.

HTTP FUNCTIONS

Integer Function String Array Integer Integer String Integer Array Integer Integer Integer Integer String
IMAGE FUNCTIONS header(string) headers_sent() setcookie(name [, value [, expire [, path [, domain [, secure]]]]])

Description Sends an HTTP header. Checks if headers have been sent. Sends a cookie.

Returns Integer Boolean Integer

ftp_put(ftp_stream, Uploads a file to an FTP server. remote_file, local_file, mode) ftp_pwd(ftp_stream) ftp_quit(ftp_stream) ftp_rawlist(ftp_stream, directory) ftp_rename(ftp_stream, from, to) ftp_rmdir(ftp_stream, directory) ftp_site(ftp_stream, cmd) ftp_size(ftp_stream, remote_file) ftp_systype(ftp_stream)

Returns the name of the current directory on an FTP server. Closes a connection to an FTP server. Returns a detailed list of files in a directory on an FTP server. Renames a file on an FTP server. Removes a directory on an FTP server. Sends a SITE command to an FTP server. Returns the size of a file on an FTP server. Returns the system type identifier of a remote FTP server.

Function
getimagesize(filename [, image_info]) imagearc(im, cx, cy, width, height, start, end, col) imagechar(im, font, x, y, c, col) imagecharup(im, font, x, y, c, col) imagecolorallocate(im, red, green, blue) imagecolorat(im, x, y)

Description Returns the size of an image. Draws a partial ellipse. Draws a character horizontally. Draws a character vertically. Allocates a color for an image. Returns the index of the color of a pixel. Returns the index of the closest color to the specified color. De-allocates a color for an image. Returns the index of a color. Returns the index of a color or its closest possible alternative. Sets the color for a palette index.

Returns Array Integer Integer Integer Integer Integer Integer Integer Integer Integer Boolean

FUNCTION HANDLING FUNCTIONS

imagecolorclosest(im, red, green, blue)

Function
call_user_func(function_name [, parameter [, ...]]) call_user_func_array (function_name [, parameters_array]) create_function(args, code)

Description Calls a user function. Calls a user function using an array of parameters. Creates an anonymous function.

Returns Mixed Mixed String

imagecolordeallocate (im,index) imagecolorexact(im, red, green, blue) imagecolorresolve(im, red, green, blue) imagecolorset(im, index, red, green, blue)

244

245

PHP
IMAGE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

Function

PHP FUNCTIONS QUICK REFERENCE
IMAGE FUNCTIONS (CONTINUED)

imageloadfont(filename) imagepng(im [, filename]) imagepolygon(im, points, num_points, col) imagepsbbox(text, font, size [, space [, tightness [, angle]]]) imagepsencodefont (font_index, encodingfile) imagepsextendfont (font_index, extend) imagepsfreefont(fontindex)

Description Loads a new bitmap font. Outputs a PNG image to a browser or file. Draws a polygon. Returns the bounding box of text using a PostScript Type1 font. Changes the character-encoding vector of a PostScript Type1 font. Extends or condenses a font. Frees memory used by a PostScript Type1 font. Loads a PostScript Type1 font from a file. Slants a PostScript Type1 font. Draws a text string on an image using a PostScript Type1 font.

Returns Integer Integer Integer Array Integer Boolean Void Integer Boolean Array

Function

Description

imagecolorsforindex(im, index) Returns the color values for an index. imagecolorstotal(im) Returns the number of colors in an image's palette. imagecolortransparent(im [, col]) imagecopy(dst_im, src_im, dstX, dstY, srcX, srcY, srcW, srcH)

Returns Array Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer

Defines a color as transparent. Copies part of an image.

imagepsloadfont(filename) imagepsslantfont(font_index, slant) imagepstext(im, text, font, size, foreground, background, x, y [, space [, tightness [, angle [,antialias_steps]]]]) imagerectangle(im, x1, y1, x2, y2, col) imagesetpixel(im, x, y, col) imagestring(im, font, x, y, s, col) imagestringup(im, font, x, y, s, col) imagesx(im) imagesy(im) imagettfbbox(size, angle, fontfile, text) imagettftext(im, size, angle, x, y, col, fontfile, text) imagetypes() imagewbmp(im [, filename])

Copies and resizes part of an image. imagecopyresized(dst_im, src_im, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH)
imagecreate(width, height) imagecreatefromgif(filename) imagecreatefromjpeg(filename) imagecreatefrompng(filename) imagecreatefromstring(image) imagecreatefromwbmp(filename) imagedashedline(im, x1, y1, x2, y2, col) imagedestroy(im) imagefill(im, x, y, col) imagefilledpolygon(im, points, num_points, col) imagefilledrectangle(im, x1, y1, x2, y2, col) imagefilltoborder(im, x, y, border, col) imagefontheight(font) imagefontwidth(font) imagegammacorrect(im, inputgamma, outputgamma) imagegif(im [, filename]) imageinterlace(im [, interlace]) imagejpeg(im [, filename [, quality]]) imageline(im, x1, y1, x2, y2, col)

Creates an image. Creates an image from a GIF file. Creates an image from a JPEG file. Creates an image from a PNG file. Creates an image from the image stream in a string. Creates an image from a WBMP file. Draws a dashed line. Destroys an image. Flood fills an image. Draws a filled polygon. Draws a filled rectangle. Flood fills an image with a specified border color. Returns the height of a font. Returns the width of a font. Applies a gamma correction to a GD image. Outputs a GIF image to a browser or file. Turns interlacing on or off for an image. Outputs a JPEG image to a browser or file. Draws a line.

Draws a rectangle. Draws a pixel. Draws a string horizontally. Draws a string vertically. Returns the width of an image. Returns the height of an image. Returns the bounding box of text using a TrueType font. Writes text to an image using a TrueType font. Returns the image types supported by this PHP build. Outputs a WBMP image to a browser or file. Returns the EXIF headers from a JPEG image.

Integer Integer Integer Integer Integer Integer Array Array Integer Integer Array

read_exif_data(filename)

IMAP, POP3 AND NNTP FUNCTIONS

Function
imap_8bit(string) imap_alerts() imap_append(imap_stream, mbox, message [, flags])

Description Converts an 8-bit string to a quoted-printable string. Returns all IMAP alert messages for this page request. Appends a string message to a mailbox.

Returns String Array Integer

246

247

PHP

PHP FUNCTIONS QUICK REFERENCE
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED)

12

PHP FUNCTIONS QUICK REFERENCE
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED)

Function
imap_headers(imap_stream) imap_last_error()

Description Returns the headers for all messages in a mailbox. Returns the last IMAP error for this page request. Returns a list of mailboxes. Returns a list of all the subscribed mailboxes. Sends an e-mail message. Creates a MIME message using the provided envelope and body. Copies messages to a mailbox. Moves messages to a mailbox. Returns information about the current mailbox. Decodes MIME header elements. Returns the message sequence number for a UID. Returns the number of messages in the current mailbox. Opens an IMAP stream to a mailbox. Checks if an IMAP stream is still active. Converts a quoted-printable string to an 8-bit string. Renames a mailbox. Re-opens an IMAP stream to a new mailbox. Parses an address string. Parses mail headers from a string. Returns a formatted e-mail address from the provided mailbox, host and personal information. Searches the names of mailboxes for a specified string. Returns messages matching the provided criteria. Sets a quota for a mailbox. Sets flags on messages.

Returns Array String Array Array String String Integer Integer Object Array Integer Integer Integer Integer String Integer Integer Array Object String Array Array Integer String

Function
imap_base64(text) imap_binary(string) imap_body(imap_stream, msg_number [, flags]) imap_check(imap_stream) imap_clearflag_full(stream, sequence, flag, options) imap_close(imap_stream [, flags]) imap_createmailbox (imap_stream, mbox) imap_delete(imap_stream, msg_number [, flags]) imap_deletemailbox (imap_stream, mbox) imap_errors() imap_expunge(imap_stream) imap_fetch_overview (imap_stream, sequence [, flags]) imap_fetchbody(imap_stream, msg_number, part_number [, flags]) imap_fetchheader(imap_stream, msg_number, flags) imap_fetchstructure (imap_stream, msg_number [, flags]) imap_get_quota(imap_stream, quota_root) imap_getmailboxes (imap_stream, ref, pattern) imap_getsubscribed (imap_stream, ref, pattern) imap_header(imap_stream, msg_number [, fromlength [, subjectlength [, defaulthost]]]) imap_headerinfo(imap_stream, msg_number [, fromlength [, subjectlength [, defaulthost]]])

Description Decodes base64 encoded text. Converts an 8-bit string to a base64 string. Returns a message body. Checks the current mailbox. Clears message flags. Closes an IMAP stream. Creates a new mailbox. Marks a message for deletion from the current mailbox. Deletes a mailbox. Returns all IMAP errors for this page request. Deletes all messages marked for deletion. Returns an overview of header information for a message. Fetches a section of the body of a message. Returns the header for a message. Returns the structure of a message. Returns the quota level settings and usage statistics for a mailbox. Returns detailed information about each mailbox. Returns a list of all the subscribed mailboxes. Returns the header of a message.

Returns String String String Object String Integer Integer Integer Integer Array Integer Array String String Object Array Array Array Object

imap_listmailbox (imap_stream, ref, pattern) imap_listsubscribed (imap_stream, ref, pattern) imap_mail(to, subject, message [,additional_headers [, cc [, bcc [, rpath]]]]) imap_mail_compose(envelope, body) imap_mail_copy(imap_stream, msglist, mbox [, flags]) imap_mail_move(imap_stream, msglist, mbox [, flags]) imap_mailboxmsginfo (imap_stream) imap_mime_header_decode(text) imap_msgno(imap_stream, uid) imap_num_msg(imap_stream) imap_num_recent(imap_stream) imap_open(mbox, username, password [, flags]) imap_ping(imap_stream) imap_qprint(string) imap_renamemailbox (imap_stream, old_mbox, new_mbox) imap_reopen(imap_stream, mbox [, flags]) imap_rfc822_parse_adrlist (address, default_host) imap_rfc822_parse_headers (headers [, defaulthost]) imap_rfc822_write_address (mbox, host, personal) imap_scanmailbox(imap_stream, ref, pattern, content) imap_search(imap_stream, criteria, flags)

Returns the number of recent messages in the current mailbox. Integer

Returns the header of a message.

Object

imap_set_quota(imap_stream, quota_root, quota_limit) imap_setflag_full(stream, sequence, flag, options)

248

249

PHP

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED) MATHEMATICAL FUNCTIONS (CONTINUED)

Function
imap_sort(stream, criteria, reverse, options) imap_status(imap_stream, mbox, options) imap_subscribe(imap_stream, mbox) imap_uid(imap_stream, msg_number) imap_undelete(imap_stream, msg_number) imap_unsubscribe (imap_stream, mbox) imap_utf7_decode(text) imap_utf7_encode(data) imap_utf8(text)

Description Sorts message headers. Returns status information on a mailbox other than the current mailbox. Subscribes to a mailbox. Returns the UID for a message sequence number. Unmarks a message for deletion. Unsubscribes from a mailbox. Decodes a modified UTF-7 encoded string. Converts 8-bit data to modified UTF-7 text. Converts text to UTF8.

Returns Array Object Integer Integer Integer Integer String String String

Function
bindec(binary_string) ceil(number) cos(arg) decbin(number) dechex(number) decoct(number) deg2rad(number) exp(arg) floor(number) getrandmax() hexdec(hex_string) lcg_value() log(arg) log10(arg) max(arg1, arg2, ...)

Description Converts a binary value to decimal. Rounds fractions up to the next highest integer. Returns the cosine of an argument in radians. Converts a decimal number to binary. Converts a decimal number to hexadecimal. Converts a decimal number to octal. Converts the number in degrees to the radian equivalent. Returns e to the power of an argument. Rounds fractions down to the next lowest integer. Returns the largest possible random value. Converts a hexadecimal value to decimal. Returns a pseudo random number between 0 and 1. Returns the natural logarithm of an argument. Returns the base-10 logarithm of an argument. Finds the highest value of the specified arguments. Finds the lowest value of the specified arguments. Returns the largest possible random value that can be returned by mt_rand(). Returns a Mersenne Twister random value. Seeds the Mersenne Twister random number generator. Formats a number to a specified number of decimal places using the provided decimal point and thousands separator. Converts an octal value to decimal. Returns the value of pi. Returns a base to the power of an exponent. Converts a radian number to degrees. Generates a random value. Rounds a float number to the nearest integer. Returns the sine of an argument in radians. Returns the square root of an argument. Seeds the random number generator. Returns the tangent of an argument in radians.

Returns Integer Integer Float String String String Double Float Integer Integer Integer Double Float Float Mixed Mixed Integer Integer Void String Integer Double Float Double Integer Double Float Float Void Float

MAIL FUNCTIONS

min(arg1, arg2, ...)

Function
ezmlm_hash(addr) mail(to, subject, message [, additional_headers [, additional_parameters]])

Description Calculates the hash value required by EZMLM mailing lists. Sends mail.

Returns Integer Boolean

mt_getrandmax() mt_rand([min [, max]]) mt_srand(seed) number_format(number, decimals, dec_point, thousands_sep) octdec(octal_string)

MATHEMATICAL FUNCTIONS

pi()

Function
abs(number) acos(arg) asin(arg) atan(arg) atan2(y, x) base_convert(number, frombase, tobase)

Description Returns the absolute value of a number. Returns the arc cosine of an argument in radians. Returns the arc sine of an argument in radians. Returns the arc tangent of an argument in radians. Returns the arc tangent of two variables. Converts a number between bases.

Returns Mixed Float Float Float Float String

pow(base, exp) rad2deg(number) rand([min [, max]]) round(number [, precision]) sin(arg) sqrt(arg) srand(seed) tan(arg)

250

251

PHP

PHP FUNCTIONS QUICK REFERENCE
NETWORK FUNCTIONS (CONTINUED)

12

PHP FUNCTIONS QUICK REFERENCE
MISCELLANEOUS FUNCTIONS

Function
fsockopen([udp://]hostname, port [, errno [, errstr [, timeout]]])

Description Opens a socket connection. Finds the host name corresponding to an IP address. Finds the IP address corresponding to a host name. Returns a list of IP addresses corresponding to a host name. Finds the MX records corresponding to a host name. Finds the protocol number associated with a protocol name. Finds the protocol name associated with a protocol number. Finds the port number associated with a service and protocol. Finds the Internet service associated with a port and protocol. Converts an IP address into the name of a computer. Converts the name of a computer into an IP address. Opens a connection to the system logger. Opens a persistent socket connection. Returns information about a socket resource. Sets the blocking mode for a socket. Sets the timeout period on a socket. Writes a message to the system log.

Returns Integer String String Array Integer Integer String Integer String Integer String Integer Integer Array Integer Boolean Integer

Function
connection_aborted() connection_status() connection_timeout() constant(name) define(name, value [, case_insensitive]) defined(name) die(message) eval(string) exit() get_browser([user_agent]) highlight_file(filename) highlight_string(string) ignore_user_abort([setting]) iptcparse(iptcblock) leak(bytes) pack(format [, args...]) show_source(filename) sleep(seconds) uniqid(prefix [, lcg]) unpack(format, data) usleep(microseconds)

Description Indicates whether a client has disconnected. Returns the status of a connection. Indicates whether a script has timed out. Returns the value of a constant. Defines a named constant. Checks whether a named constant exists. Outputs a message and terminates the current script. Evaluates a string as PHP code. Terminates the current script. Determines the capabilities of a user's browser. Prints a syntax highlighted version of a file. Prints a syntax highlighted version of a string. Sets whether a client disconnecting will terminate the execution of a script. Parses an IPTC block into its single tags. Leaks a specified amount of memory. Packs arguments into a binary string using a specified format. Prints a syntax highlighted version of a file. Generates a prefixed unique ID based on the current time in microseconds. Unpacks data from a binary string using a specified format. Delays execution of a script for a specified number of microseconds.

Returns Integer Integer Integer Mixed Integer Integer Void Mixed Void Object Boolean Boolean Integer Array Void String Boolean Integer Array Void

gethostbyaddr(ip_address) gethostbyname(hostname) gethostbynamel(hostname) getmxrr(hostname, mxhosts [, weight]) getprotobyname(name) getprotobynumber(number) getservbyname(service, protocol) getservbyport(port, protocol) ip2long(ip_address) long2ip(proper_address) openlog(ident, option, facility) pfsockopen(hostname, port [, errno [, errstr [, timeout]]]) socket_get_status (socket_get_status) socket_set_blocking (socket_descriptor, mode) socket_set_timeout (socket_descriptor, seconds, microseconds) syslog(priority, message)

Delays execution of a script for a specified number of seconds. Void

OUTPUT CONTROL FUNCTIONS

Function
flush() ob_end_clean()

NETWORK FUNCTIONS

Description Flushes an output buffer. Erases the contents of an output buffer and turns off output buffering. Sends the contents of an output buffer and turns off output buffering. Returns the contents of an output buffer. Returns the length of the contents of an output buffer. Facilitates sending gz-encoded data to Web browsers. Turns implicit flushing on or off. Turns on output buffering.

Returns Void Void Void String String String Void Void

Function
checkdnsrr(host [, type]) closelog() debugger_off() debugger_on(address) define_syslog_variables()

Description Searches the DNS for records of a specified type corresponding to a host. Closes a connection to the system logger. Disables the internal PHP debugger. Enables the internal PHP debugger and connects it to an address. Initializes all syslog related constants.

Returns Integer Integer Integer Integer Void

ob_end_flush() ob_get_contents() ob_get_length() ob_gzhandler(buffer) ob_implicit_flush([flag]) ob_start([output_callback])

252

253

PHP

PHP FUNCTIONS QUICK REFERENCE
PHP OPTIONS AND INFORMATION (CONTINUED)

12

PHP FUNCTIONS QUICK REFERENCE
PHP OPTIONS AND INFORMATION

Function
set_magic_quotes_runtime (new_setting) set_time_limit(seconds)

Description Sets the current configuration setting of magic_quotes_runtime. Sets the number of seconds a script can take to execute. Returns the Zend GUID. Returns the version of the current Zend engine.

Returns Long Void String String

Function
assert(assertion)

Description Checks if an assertion is false. Loads a PHP extension library at runtime. Indicates whether an extension is loaded. Returns the value of a PHP configuration option. Returns the name of the owner of the current PHP script. Returns the names of the functions of a module. Returns the names of all the files that have been loaded into a script using include_once(). Returns the names of all compiled and loaded modules. Returns the current setting for magic_quotes_gpc. Returns the current setting for magic_quotes_runtime. Returns the names of all the files that have been loaded into a script using require_once(). Returns the value of an environment variable. Returns the time the current page was last modified. Returns the inode of the current script. Returns the current PHP process ID. Returns the user ID for the current script's owner. Returns the current resource usages. Changes the value of a configuration option. Returns the value of a configuration option. Restores the value of a configuration option. Sets the value of a configuration option. Returns the logo GUID. Returns the type of interface between a Web server and PHP. Returns information about the operating system PHP is built on. Prints the credits for PHP. Outputs information about the current state and configuration of PHP. Returns the current version of PHP. Sets the value of an environment variable by adding a setting to the server environment.

Returns Integer Mixed Integer Boolean String String Array Array Array Long Long Array String Integer Integer Integer Integer Array String String String String String String String Void Integer String Void

zend_logo_guid() zend_version()

assert_options(what [, value]) Gets or sets assert control options. dl(library) extension_loaded(name) get_cfg_var(varname) get_current_user() get_extension_funcs (module_name) get_included_files() get_loaded_extensions() get_magic_quotes_gpc() get_magic_quotes_runtime() get_required_files() getenv(varname) getlastmod() getmyinode() getmypid() getmyuid() getrusage([who]) ini_alter(varname, newvalue) ini_get(varname) ini_restore(varname) ini_set(varname, newvalue) php_logo_guid() php_sapi_name() php_uname() phpcredits(flag) phpinfo([what]) phpversion() putenv(setting)

POSIX FUNCTIONS

Function
posix_ctermid() posix_getcwd() posix_getegid() posix_geteuid() posix_getgid() posix_getgrgid(gid) posix_getgrnam(name) posix_getgroups() posix_getlogin() posix_getpgid(pid) posix_getpgrp() posix_getpid() posix_getppid() posix_getpwnam(username) posix_getpwuid(uid) posix_getrlimit() posix_getsid(pid) posix_getuid() posix_isatty(fd) posix_kill(pid, sig) posix_mkfifo(pathname, mode) posix_setgid(gid) posix_setpgid(pid, pgid) posix_setsid() posix_setuid(uid) posix_times() posix_ttyname(fd) posix_uname()

Description Returns the path name of the controlling terminal. Returns the pathname of the current directory. Returns the effective group ID of the current process. Returns the effective user ID of the current process. Returns the real group ID of the current process. Returns information about a group by group ID. Returns information about a group by name. Returns the group set of the current process. Returns the login name of the user owning the current process. Returns the process group identifier for a process. Returns the current process group identifier. Returns the process identifier of the current process. Returns the parent process identifier of the current process. Returns information about a user by username. Returns information about a user by user ID. Returns information about system resource limits. Returns the sid of a process. Returns the real user ID of the current process. Indicates whether a file descriptor is an interactive terminal. Sends a signal to a process. Creates a fifo special file. Sets the effective group ID of the current process. Lets a process join a process group. Makes the current process a session leader. Sets the effective user ID of the current process. Returns process times. Returns the terminal device name. Returns system information.

Returns String String Integer Integer Integer Array Array Array String Integer Integer Integer Integer Array Array Array Integer Integer Boolean Boolean Boolean Boolean Integer Integer Boolean Array String Array

254

255

PHP

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
PROGRAM EXECUTION FUNCTIONS

PSPELL FUNCTIONS (CONTINUED)

Function
pspell_save_wordlist (dictionary_link)

Description Saves a personal wordlist to a file. Stores a replacement pair for a word. Suggests spellings for a word.

Returns Integer Integer Array

Function
escapeshellarg(arg) escapeshellcmd(command) exec(command [, array [, return_var]]) passthru(command [, return_var])

Description Escapes a string to be used as a shell argument. Escapes shell metacharacters in a command. Executes a command and returns the last line from the result. Executes a command and displays the raw output.

Returns String String String Void String

pspell_store_replacement (dictionary_link, misspelled, correct) pspell_suggest (dictionary_link, word)

system(command [, return_var]) Executes a command and displays any output.

REGULAR EXPRESSION FUNCTIONS

Perl-Compatible
PSPELL FUNCTIONS

Function
preg_grep(pattern, input)

Function
pspell_add_to_personal (dictionary_link, word) pspell_add_to_session (dictionary_link, word) pspell_check(dictionary_link, word) pspell_clear_session (dictionary_link) pspell_config_create(language [, spelling [, jargon [, encoding]]]) pspell_config_ignore (dictionary_link, n) pspell_config_mode (dictionary_link, mode) pspell_config_personal (dictionary_link, file) pspell_config_repl (dictionary_link, file) pspell_config_runtogether (dictionary_link, flag) pspell_config_save_repl (dictionary_link, flag) pspell_new(language [, spelling [, jargon [, encoding [, mode]]]]) pspell_new_config(config)

Description Adds a word to a personal wordlist. Adds a word to a wordlist in the current session. Checks the spelling of a word. Clears the current session and makes the current wordlist blank. Creates a config used to open a dictionary. Ignores words shorter than a specified length. Changes the mode number of suggestions returned. Sets a file that contains a personal wordlist. Sets a file that contains replacement pairs. Considers run-together words as valid compounds. Determines whether to save a replacement pairs list with a wordlist. Loads a new dictionary. Loads a new dictionary with settings based on a specified config.

Returns Integer Integer Boolean Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer Integer

Description Returns the entries from an input array that match a regular expression. Searches for a match to a regular expression. Searches for all matches to a regular expression, putting the results in matches. Puts a backslash in front of every regular expression character in a string. Replaces matches to a regular expression. Replaces matches to a regular expression using a callback. Splits a string using a regular expression.

Returns Array Integer Integer String Mixed Mixed Array

preg_match(pattern, subject [, matches]) preg_match_all(pattern, subject, matches [, order]) preg_quote(string [, delimiter]) preg_replace(pattern, replacement, subject [, limit]) preg_replace_callback(pattern, callback, subject [, limit]) preg_split(pattern, subject [, limit [, flags]])

POSIX Extended Function
ereg_replace(pattern, replacement, string) eregi(pattern, string [, regs]) eregi_replace(pattern, replacement, string) split(pattern, string [, limit]) spliti(pattern, string [, limit]) sql_regcase(string)

Description Replaces matches to a regular expression. Performs a case-insensitive search for matches to a regular expression. Performs a case-insensitive search and replaces matches to a regular expression. Splits a string into an array using a regular expression. Splits a string into an array using a regular expression and is case-insensitive. Returns a regular expression for a case-insensitive match.

ereg(pattern, string [, regs]) Searches for matches to a regular expression.

Returns Integer String Integer String Array Array String

pspell_new_personal(personal, Loads a new dictionary with a personal wordlist. language [, spelling [, jargon [, encoding [, mode]]]])

256

257

PHP
STRING FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
SESSION HANDLING FUNCTIONS

Function
convert_cyr_string (string, from, to) count_chars(string [, mode]) crc32(string)

Description Converts a string from one Cyrillic character set to another. Returns information about characters used in a string. Calculates the crc32 polynomial of 32-bit lengths of a string. Encrypts a string using the DES encryption method. Splits a string into smaller strings. Returns the translation table used by htmlspecialchars() and htmlentities(). Returns all the <meta> tag content attributes from a file. Converts logical Hebrew text to visual text. Converts logical Hebrew text to visual text with newline conversion. Converts all applicable characters in a string to HTML entities. Converts any special characters in a string to HTML entities. Joins array elements into a single string. Joins array elements into a single string. Calculates the Levenshtein distance between two strings. Returns numeric formatting information based on the current locale. Removes whitespace from the beginning of a string. Calculates the MD5 hash of a string. Calculates the metaphone key of a string. Inserts <br> before all line breaks in a string. Returns the ASCII value of the first character of a string. Parses a string into variables as if it were a query string. Outputs a string. Outputs a formatted string. Converts a quoted-printable string to an 8-bit string. Escapes metacharacters in a string. Removes trailing whitespace from a string. Sets locale information for functions of a category. Calculates the similarity between two strings. Calculates the soundex key of a string.

Returns String Mixed Integer String Array String Array String String String String String String Integer Array String String String String Integer Void Boolean Integer String String String String Integer String

Function
session_cache_limiter ([cache_limiter]) session_decode(string) session_destroy() session_encode() session_get_cookie_params() session_id([id]) session_is_registered(name) session_module_name([module]) session_name([name])

Description Returns or sets the current cache limiter. Decodes session data. Destroys all registered session data. Encodes the data for the current session as a string. Returns the current session cookie information. Returns or sets the current session ID. Indicates whether a session variable is registered with the current session. Returns or sets the name of the current session module. Returns or sets the name of the current session. Returns or sets the path where data for the current session is saved.

Returns String Boolean Boolean String Array String Boolean String String Boolean String Void Void Boolean Boolean Void

crypt(string [, salt]) explode(separator, string [, limit]) get_html_translation_ table(table [, quote_style]) get_meta_tags(filename [, use_include_path]) hebrev(hebrew_text [, max_chars_per_line]) hebrevc(hebrew_text [, max_chars_per_line]) htmlentities(string [, quote_style]) htmlspecialchars(string [, quote_style]) implode(glue, pieces) join(glue, pieces) levenshtein(string1, string2) localeconv() ltrim(string) md5(string) metaphone(string) nl2br(string) ord(string)

session_register(name [, ...]) Registers one or more variables with the current session. session_save_path([path])

session_set_cookie_params Sets the session cookie parameters. (lifetime [, path [, domain]]) session_set_save_handler (open, close, read, write, destroy, gc) session_start() session_unregister(name) session_unset()

Sets user-level session storage functions. Initializes a session. Unregisters a session variable. Frees all registered session variables.

STRING FUNCTIONS

parse_str(string [, arr]) print(string)

Function
addcslashes(string, charlist) addslashes(string) bin2hex(string) chop(string) chr(ascii) chunk_split(string [, chunklen [, end]])

Description Adds C style backslashes before characters in a string. Adds backslashes before characters in a string that need to be quoted in database queries. Converts binary data into hexadecimal representation. Removes trailing whitespace from a string. Returns the character for an ASCII value. Splits a string into smaller pieces.

Returns String String String String String String

printf(format [, args...]) quoted_printable_decode (string) quotemeta(string) rtrim(string) setlocale(category, locale) similar_text(string1, string2 [, percent]) soundex(string)

258

259

PHP

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
STRING FUNCTIONS (CONTINUED)

STRING FUNCTIONS (CONTINUED)

Function
strrpos(string, character)

Description Finds the numeric position of the last occurrence of a specified character in a string. Finds the number of characters at the beginning of one string that match another string. Returns a string from the first occurrence of a specified character to the end. Breaks down a string into segments separated by another string. Converts a string to lowercase. Converts a string to uppercase. Changes all occurrences of a character to another character. Extracts a substring from a string. Returns the number of times a substring occurs in a string.

Returns Integer Integer String String String String String String Integer String String String String String

Function
sprintf(format [, args...]) sscanf(string, format [, var1...]) str_pad(input, pad_length [, pad_string [, pad_type]]) str_repeat(input, multiplier) str_replace(string, replacement, subject) strcasecmp(string1, string2) strchr(string, character) strcmp(string1, string2) strcoll(string1, string2) strcspn(string1, string2) strip_tags(string [, allowable_tags]) stripcslashes(string) stripslashes(string) stristr(string, character) strlen(string) strnatcasecmp(string1, string2) strnatcmp(string1, string2) strncasecmp(string1, string2, length) strncmp(string1, string2, length) strpos(string, character [, offset]) strrchr(string, character) strrev(string)

Description Formats a string. Parses input from a string using a specified format. Pads a string to a specified length with another string. Repeats a string. Replaces all occurrences of a string in a subject. Performs a binary safe case-insensitive string comparison. Returns a string from the first occurrence of a specified character to the end. Performs a binary safe case-sensitive string comparison. Performs a locale-based comparison of two strings. Finds the number of characters at the beginning of one string that do not match another string. Removes HTML and PHP tags from a string. Removes C style backslashes from a string. Removes backslashes from a string. Returns a string from the first occurrence of a specified character to the end, in a case-insensitive manner. Finds the length of a string. Performs a case-insensitive string comparison using a "natural order." Performs a case-sensitive string comparison using a "natural order." Performs a binary safe case-insensitive comparison of a specified number of characters. Performs a binary safe case-sensitive comparison of a specified number of characters. Returns the numeric position of the first occurrence of a specified character in a string. Returns a string from the last occurrence of a specified character to the end. Returns a string in reverse order.

Returns String Mixed String String String Integer String Integer Integer Integer String String String String Integer Integer Integer Integer Integer Integer String String

strspn(string1, string2) strstr(string, character) strtok(string1, string2) strtolower(string) strtoupper(string) strtr(string, from, to) substr(string, start [, length]) substr_count(string, substr)

substr_replace(string, Replaces text within a specific portion of a string. replacement, start [, length]) trim(string) ucfirst(string) ucwords(string) wordwrap(string [, width [, break [, cut]]]) URL FUNCTIONS

Strips whitespace from the beginning and end of a string. Converts the first character of a string to uppercase. Converts the first character of each word in a string to uppercase. Wraps a string to a specified number of characters using a string break character.

Function
base64_decode(string) base64_encode(string) parse_url(url) rawurldecode(string) rawurlencode(string)

Description Decodes a MIME base64 encoded string. Encodes a string with MIME base64. Parses a URL into its components. Decodes a URL-encoded string. URL-encodes a string, replacing all alphanumeric characters except - _ and . with a % symbol and the hex code for the character. Decodes a URL-encoded string. URL-encodes a string, replacing all alphanumeric characters except - _ and . with a % symbol and the hex code for the character and replacing all spaces with a + symbol.

Returns String String Array String String String String

urldecode(string) urlencode(string)

260

261

PHP

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
VARIABLE FUNCTIONS WDDX FUNCTIONS

Function
doubleval(variable) empty(variable) get_defined_vars() get_resource_type($handle) gettype(variable) intval(variable [, base]) is_array(variable) is_bool(variable) is_double(variable) is_float(variable) is_int(variable) is_integer(variable) is_long(variable) is_null(variable) is_numeric(variable) is_object(variable) is_real(variable) is_resource(variable) is_scalar(variable) is_string(variable) isset(variable) print_r(expression) serialize(value) settype(variable, type) strval(variable) unserialize(string) unset(variable [, variable [, ...]]) var_dump(expression)

Description Returns the double value of a variable. Indicates whether a variable has been set and has a non-zero value. Returns all defined variables. Finds the type of a resource. Finds the data type of a variable. Returns the integer value of a variable using a specified base. Indicates whether a variable is an array. Indicates whether a variable is a boolean. Indicates whether a variable is a double. Indicates whether a variable is a floating-point number. Indicates whether a variable is an integer. Indicates whether a variable is an integer. Indicates whether a variable is an integer. Indicates whether a variable is null. Indicates whether a variable is a number or a numeric string. Indicates whether a variable is an object. Indicates whether a variable is a real number. Indicates whether a variable is a resource. Indicates whether a variable is a scalar. Indicates whether a variable is a string. Indicates whether a value has already been assigned to a variable. Prints human-readable information about a variable. Generates a storable representation of a value. Converts a variable to a specified data type. Returns the string value of a variable. Creates a PHP value from a stored representation. Destroys a variable. Dumps information about an expression.

Returns Double Integer Array String String Integer Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Integer Void String Integer String Mixed Integer Void

Function
wddx_add_vars(packet_id, variable [, ...]) wddx_deserialize(packet) wddx_packet_end(packet_id) wddx_packet_start([comment]) wddx_serialize_value(var [, comment]) wddx_serialize_vars(var_name [, ...])

Description Adds a variable to a WDDX packet. Deserializes a WDDX packet. Ends a WDDX packet. Starts a new WDDX packet. Serializes a single value into a WDDX packet. Serializes multiple variables into a WDDX packet.

Returns Void Mixed String Integer String String

XML PARSER FUNCTIONS

Function
utf8_decode(string) utf8_encode(string) xml_error_string(code) xml_get_current_byte_index (parser) xml_get_current_column_number (parser) xml_get_current_line_number (parser) xml_get_error_code(parser) xml_parse(parser, data [, is_final]) xml_parse_into_struct(parser, data, values, index) xml_parser_create([encoding]) xml_parser_free(parser) xml_parser_get_option(parser, option) xml_parser_set_option(parser, option, value)

Description Converts a UTF-8 encoded string to ISO-8859-1. Encodes an ISO-8859-1 string to UTF-8. Returns the error message associated with an error code. Returns the current byte index for an XML parser. Returns the current column number for an XML parser. Returns the current line number for an XML parser. Returns the error code for the last occurring XML parser error. Parses specified XML data. Parses XML data into two arrays. Creates an XML parser. Frees an XML parser. Returns the value of an option for an XML parser. Sets an option for an XML parser to a specified value.

Returns String String String Integer Integer Integer Integer Integer Integer Integer String Mixed Integer

262

263

PHP

PHP FUNCTIONS QUICK REFERENCE

12

PHP FUNCTIONS QUICK REFERENCE
XML PARSER FUNCTIONS (CONTINUED) ZLIB FUNCTIONS (CONTINUED)

Function
xml_set_character_data_handler (parser, handler) xml_set_default_handler (parser, handler) xml_set_element_handler (parser, startElementHandler, endElementHandler) xml_set_external_entity_ref_ handler(parser, handler) xml_set_notation_decl_handler (parser, handler)

Description Sets a character data handler function for an XML parser. Sets a default handler function for an XML parser. Sets the start and end element handler functions for an XML parser. Sets an external entity reference handler function for an XML parser.

Returns Integer Integer Integer Integer

Function
gzgetss(zp, length [, allowable_tags]) gzinflate(data [, length]) gzopen(filename, mode [, use_include_path]) gzpassthru(zp) gzputs(zp, string [, length]) gzread(zp, length) gzrewind(zp)

Description Returns a line of a specified length from a gz-file pointer and strips any HTML and PHP tags. Uncompresses data compressed using the DEFLATE data format. Opens a gz-file pointer. Outputs all remaining data on a gz-file pointer. Writes a string to a gz-file pointer. Reads a specified number of bytes from a gz-file pointer. Rewinds the position of a gz-file pointer to the beginning of a file stream. Seeks on a gz-file pointer. Determines the position of a gz-file pointer. Uncompresses gz-compressed data. Writes a string to a gz-file pointer. Outputs a gz-file.

Returns String String Integer Integer Integer String Integer Integer Integer String Integer Integer

Sets a notation declaration handler function for an XML parser. Integer Void Integer Integer

xml_set_object(parser, object) Allows the use of an XML parser inside an object. xml_set_processing_ instruction_handler(parser, handler) xml_set_unparsed_entity_decl_ handler(parser, handler)

Sets a processing instruction handler function for an XML parser. Sets an unparsed entity declaration handler function for an XML parser.

gzseek(zp, offset) gztell(zp) gzuncompress(data [, length]) gzwrite(zp, string [, length]) readgzfile(filename [, use_include_path])

ZLIB FUNCTIONS

Function
gzclose(zp) gzcompress(data [, level]) gzdeflate(data [, level]) gzencode(data [, level]) gzeof(zp) gzfile(filename [, use_include_path]) gzgetc(zp) gzgets(zp, length)

Description Closes a gz-file pointer. Returns a gzip-compressed version of data. Returns a compressed version of data using the DEFLATE data format. Creates a gzip-compressed string. Tests for end-of-file on a gz-file pointer. Reads a gz-file into an array. Returns a character from a gz-file pointer. Returns a line of a specified length from a gz-file pointer.

Returns Integer String String String Integer Array String String

264

265