You are on page 1of 132

PHP GETTING STARTED WITH PHP 1

INTRODUCTION TO PHP
P
HP is a popular scripting language used to create free of charge. There are also no costs or restrictions
powerful and dynamic Web sites. PHP is currently in related to distributing the PHP scripts you create, whether
use on over five million Web sites around the world. the scripts are for development or commercial use.
PHP is open source software, which means it is available

Versions Interactive Web Sites Server-Side Processing Cross Platform


PHP is constantly evolving and a new version of the Interactive Web sites contain Web pages that A Web server processes all the PHP code in a Web PHP can be installed on computers using different
language is released every few years. Each new version exchange information between the Web site and page and translates the code into simple HTML code. Windows and Unix operating systems. While some
of PHP offers more features than previous versions the user. Using PHP allows Web developers to This means that Web developers do not have to take specialized functions work only on specific platforms,
but is still compatible with the previous versions. easily create Web pages that process information into consideration the types of Web browsers used the vast majority of PHP code will work equally as
This means that scripts you write using the current from a user and then generate content depending by clients. Any browser that can view Web pages well on either platform. Many PHP developers write
version of PHP will be compatible with future versions. on the information submitted by the user. can view pages containing PHP code processed by their code on Windows-based computers and then
PHP 4 is the current version of PHP and is used in the Interactive Web sites allow Web developers to a Web server. use the code on Web servers that run a Unix
examples throughout this book. tailor the content of Web pages to better appeal operating system.
to the user.
Object-Oriented
HTML Although PHP is not a true object-oriented language, Web Servers
HyperText Markup Language (HTML) is the markup Database Manipulation PHP does support object-oriented programming You do not require a dedicated Web server to publish
language used to create Web pages. PHP can be used One of the most important features of PHP is concepts that allow Web developers to write code the Web pages you create using PHP. You can simply
to dynamically generate the HTML code for a Web the ability to work with a number of different in an object-oriented fashion. Object-oriented install Web server software on your own computer.
page. PHP code can also be embedded into the HTML databases, including MySQL, Oracle and Sybase. programming is a type of programming that treats A popular example of Web server software that
code for a Web page. PHP is embedded into HTML PHP pages can be used to access a database and packages of code as distinct modules, or objects. includes support for PHP is Apache. Microsoft's Web
code with the use of special tags, called delimiters. then make the information stored in the database Using objects can make a large Web application server products, Internet Information Server (IIS) and
Using the delimiters, you can add as many sections available to users who visit the Web site. Using easier to manage, especially if there are multiple Personal Web Server (PWS), can also be used to
of PHP code to an HTML document as you need. databases to store information and PHP code to developers working on the same application. store and serve PHP pages. If you cannot install Web
Embedding PHP code in HTML code makes it possible access the information is an efficient method of server software on your computer, you can transfer
to enhance existing Web pages on a Web site. displaying up-to-date information in a Web site. your PHP pages to a Web hosting service on the
Increased Security Internet.
PHP can also allow users to manipulate the data
in a database. For example, a PHP page can be Because PHP code is processed by a Web server,
Dynamic Web Sites a user cannot access the code used to create a
used to add, delete or edit records in a database Development Tools
Dynamic Web sites contain Web pages that display depending on a user's request. PHP page. This makes it safer to work with sensitive
constantly changing content. Using PHP, you can data, such as login names and passwords. If a user You do not require any special development tools
determine the content a Web page displays, depending views the source code of a Web page created using to create and view PHP pages. All you need is a text
on many different factors. For example, you can have PHP within a Web browser, all the user will see is editor and a Web browser. Although there are some
a page automatically present different content to users the HTML code that was generated by the Web programming tools available that make creating PHP
depending on the current date or the user's location. server to create the page, not the PHP code itself. pages easier, these tools are typically used only by
Dynamic Web pages are more useful to each individual Webmasters who generate large amounts of PHP
user than static Web pages. 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 Apache Web server is relatively easy to install and maintain.

B 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
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
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
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
large commercial Web site. Since Apache is the most popular on computers using Windows 95, 98, Me or XP. only the files required to run Apache. This option is program, so you must troubleshoot any
Web server used on the Internet, PHP has been developed to useful when installing Apache on a computer with problems yourself. There are, however, many
work well with Apache to make PHP pages available on the On the Windows platform, Apache is installed using
a standard Windows installation program. The Apache limited hard drive space available. The Custom option Web sites, user groups, newsgroups and books
Web. allows advanced Web site developers to choose the available that can be a source of information
files must be installed in a folder on the computer. The
A recent release of Apache Web server is included on the default installation location is C:\Program Files\Apache Apache Web server files they want to install. for Apache users. The Apache FAQ located at
CD-ROM disc that accompanies this book, but you should Group\Apache. You can specify another destination folder, http://httpd.apache.org/docs/misc/FAQ.html
make sure you install the latest release of the server. The but it is recommended that you accept the default folder. If you are installing a more recent version of Apache is a good starting point when looking for help
latest version of Apache is available at the www.apache.org Web server than the one included on the CD-ROM information.
Web site. Apache includes several parts, such as documentation, disc that accompanies this book, you should carefully
modules that increase Web server efficiency and the source read the Web server documentation, especially the
Before you can install Apache, you must install the TCP/IP code of the application program itself. You may not need to areas that relate to PHP. Later versions of Apache may
protocol on your computer. For information about installing install all the available components in order to use Apache. work differently with PHP than the version used in
network protocols, refer to your operating system The setup program allows you to choose the type of this book.
documentation. installation you want to perform.

INSTALL APACHE WEB SERVER ON WINDOWS

C:\Program Files\Apache Group\Apache

⁄ Double-click the icon ■ This area displays ■ This area displays the ■ An information ■ This area displays the › Click Next to continue. ˇ Click the type of Á Click Next to continue.
for the Apache Web server information about the license agreement you dialog box may appear, folder where Apache Web installation you want
installation program to start Apache Web server program. must read and accept providing information server files will be installed. to perform.
installing the program. before continuing. about this version of the
¤ Click Next to continue. Web server software. ■ You can click Browse to Note: If you choose Custom,
■ A welcome dialog box ‹ Click Yes to accept the Click Next to continue. specify a different folder in the following steps will be CONTINUED
appears. agreement and continue. which to install the files. different for your installation.

4 5
PHP GETTING STARTED WITH PHP 1

INSTALL APACHE WEB SERVER ON WINDOWS After installing Apache Web server as a service, If you are removing Apache Web server from
you can stop or restart Apache manually using your computer, you may want to first uninstall

W
hen installing Apache Web server on a computer system. When you install Apache as a service, the program
Start menu commands. To stop or restart Apache Apache as a service to ensure that the program
running a Windows operating system, a folder will start automatically and run in the background each time
on most Windows systems, click Start, select is removed correctly. To uninstall Apache as a
containing shortcut commands for Apache Web the computer is started. Once the Web server has been
Programs and choose Apache Web Server. Then service, click Start, select Programs and choose
server is added to the Programs folder on the Start menu. installed as a service, you should restart the computer.
click Apache as a service and select Stop Service Apache Web Server. Then click Apache as a
This folder allows you to quickly access commands that let
To confirm that Apache Web server has been installed and or Restart Service. service and select Uninstall service.
you work with Apache from the Start menu.
started properly, you can have the server display a page in
The installation program allows you to choose whether a Web browser. After starting the Web browser you want to
you want to view a README file that contains information use, you enter the name or IP number of your computer as You can also start and stop Apache Web server The Apache Web server program is written by a
about the release of Apache you installed. If you choose the URL in the Web browser. The IP number indicates the from within a command prompt window. In the group of dedicated and talented volunteers who
to display the file, it will open when the installation is computer that is running the Web server software. If you command prompt window, change to the directory do not receive any payment for their work with
complete. You should carefully review the README file do not know the IP number of your computer, you can use that contains the Apache program files, usually Apache. Apache Web server is completely free
for any new release of Apache you install. 127.0.0.1, which is the IP number that computers running C:\Program Files\Apache Group\Apache, and type to download, install and use. Unlike many free
TCP/IP use to refer to themselves. If the Apache installation apache at the prompt to start the Web server. You programs that require a fee to be paid if the
Once Apache Web server is installed, you should install was successful, a default Web page will be displayed. can use the same method to stop Apache, except software is used for business purposes, there
the Web server as a service. A service is a term used type apache -k shutdown at the prompt. are no restrictions on the use of Apache.
on Windows computers to describe a program that is
automatically executed and managed by the operating

INSTALL APACHE WEB SERVER ON WINDOWS (CONTINUED)

My Documents Online
Services

My Computer Outlook
Express

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

Jack Smith...

■ This area displays the ‡ Click Next to install ■ A dialog box appears, · Click Finish to close INSTALL APACHE AS A SERVICE ˇ Click Install service. TEST APACHE ‹ Type the IP number of
folder where program Apache on your computer. indicating that the the dialog box. ⁄ Click Start. ⁄ Start the Web browser your computer or 127.0.0.1
icons for Apache will be installation is complete. Á Restart the computer. and then press Enter.
Apache Web server will you want to use to test
installed. ¤ Click Programs.
° If you do not want to start automatically each Apache Web server. ■ The Web browser
display the README file ‹ Click Apache Web Server. time the computer is ¤ Click this area to displays a Web page
after the dialog box closes, started. highlight the current Web generated by Apache
click the box beside this › Click Apache as a service. Web server.
page address and then
6 option ( changes to ). type http://. 7
PHP GETTING STARTED WITH PHP 1
INSTALL APACHE WEB SERVER ON UNIX
pache Web server was originally developed and The configure command allows you to set up some

A 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
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 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
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
on a Unix computer. To specify a directory where you want Apache program
a test page generated by Apache, type lynx http:// you to quickly install, update and remove
files to be installed, you use the --prefix parameter
A recent release of Apache is available on the CD-ROM followed by the IP number or name of your computer applications from your computer. More
with the configure command, specifying the name
disc that accompanies this book, but you can check the at the prompt. You can also use 127.0.0.1, which is information about RPM is available at the
and location of the directory as the value of the --prefix
www.apache.org Web site for the latest release of the the IP number computers using TCP/IP commonly www.rpm.org Web site.
parameter.
server. The steps for installing Apache will depend on use to refer to themselves.
the UNIX operating system and the version of Apache After you run the configure command, you must execute
The tar command can be used to combine
you are using. You should carefully read the installation the make command to prepare Apache Web server for
You can restart or stop Apache using the same multiple files into a single, more manageable
instructions included with the software. installation. You then use the make install command
method you use to start the server. To restart file. The letters xvf indicate settings you can
to install the Apache files on the computer.
The Apache program files are usually stored in a compressed Apache, type /user/local/apache/bin/apachectl restart specify for the tar command. To display
file with the .Z extension. To access the Apache files, Once the Apache software has been installed, you can at the prompt. To stop Apache, type information about the settings you can use
you must first uncompress the compressed file using the use the start command to start the Web server. /usr/local/apache/bin/apachectl stop. with the tar command, type man tar at the
gunzip command. The files are then archived into a single prompt. When you finish reviewing the
file with the .tar extension. You must extract the files from settings, press q to quit.
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

⁄ At the command ¤ To retrieve the unzipped ‹ To work in the directory › To specify a directory where Á To install the Apache ■ This message appears START APACHE
prompt, type gunzip files from the archive, type that contains the Apache you want to install the Apache files on the computer, type when Apache has been ‡ To start Apache, type
followed by the name tar xvf followed by the name files, type cd followed by files, type ./configure – –prefix=. make install and then press successfully installed. the name and location of the
of the file you want to of the tar file that contains the the name of the directory. Then type the name and Enter. directory you specified in
unzip. Then press Enter. Apache files. Then press Enter. Then press Enter. location of the directory and the --prefix parameter in
press Enter. step 4, immediately followed
Note: A directory with the same name
as the tar file is automatically created ˇ To prepare Apache for by /bin/apachectl start. Then
to store the files retrieved from the installation, type make and press Enter.
8 archive. then press Enter. 9
PHP GETTING STARTED WITH PHP 1
CONFIGURE APACHE WEB
SERVER TO WORK WITH PHP
The name and location of the Apache configuration To set up PHP as an Apache module, you should

W
hen you configure Apache Web server to work To ensure that Apache Web server processes PHP files file depends on the operating system the computer first move the php4ts.dll file, which is located in
with PHP, you can set up PHP as a CGI binary correctly, you use the AddType directive to specify the uses. The name of the configuration file is usually the main PHP directory, to your system directory.
or as an Apache module. Setting up PHP as an Multimedia Internet Mail Extensions (MIME) type used httpd.conf. On Windows operating systems, the file The name of the system directory depends on your
Apache module allows you to access additional capabilities for PHP files. MIME types are a set of accepted file types is typically located in the conf subdirectory of the operating system. On computers running Windows
of the PHP program, but for most installations it is sufficient typically used by Internet applications. PHP files use main Apache program directory. On Unix-based NT or 2000, you can move the file to the WINNT
to set up PHP as a CGI binary. To set up PHP as a CGI application/x-httpd-php as the MIME type. When using computers, the file is usually found in the /etc directory. To indicate that you want to use PHP
binary, you need to specify certain settings, or directives, the AddType directive, you also indicate the file extensions directory. as an Apache module, you must then add the
in the Apache configuration file. you want to associate with PHP. PHP files commonly use following code to the Apache configuration file:
the .php extension, but may also use other extensions, When you specify a file path in the Apache LoadModule php4_module c:/php/sapi/php4apache.dll
Initially, Apache Web server cannot access PHP program such as .phtml and .php3. configuration file, you should use slashes (/) instead AddType application/x-httpd-php .php .phtml
files because the files are stored in a location outside the
server's directory structure. The ScriptAlias directive The Action directive allows you to specify that Apache of backslashes (\) in the path name. For example,
allows you to create a virtual path Apache can use to access should pass PHP files to the PHP program for processing the filename c:\php\php.exe should be typed as
the directory that stores PHP program files. For example, before displaying the files in a Web browser. When using c:/php/php.exe.
on Windows computers, you can create the virtual path the Action directive, you specify the MIME type of the
/php/ to allow you to access files in the C:\PHP directory. files you want to pass to PHP as well as the name and
location of the program that will process the files.

CONFIGURE APACHE WEB SERVER TO WORK WITH PHP

Save

⁄ Open the Apache ‹ Type the virtual path ˇ To specify which file ‡ Type the extensions ° To specify that Apache should ‚ Type the name and — Save the Apache ■ You can now use
configuration file in a text you want to use. extensions Apache should you want to use for pass files to the PHP program location of the PHP configuration file. Apache Web server
editor. process as PHP files, type PHP files. before displaying the files in a program file that will to process and display
› Type the actual location AddType. Web browser, type Action. process the files, enclosed PHP pages you create.
¤ To create a virtual path of the PHP files, enclosed in quotation marks.
that will allow Apache to in quotation marks. Á Type application/x-httpd-php · Type application/x-httpd-php
access PHP program files, to specify the MIME type used to specify the MIME type of the
type ScriptAlias. for PHP files. files you want to pass to PHP.

10 11
PHP GETTING STARTED WITH PHP 1

INSTALL INTERNET INFORMATION SERVER Before installing IIS, you should log on to the
computer using the administrator account,
After IIS is installed, the Internet
Information Services window provides
icrosoft Internet Information Server (IIS) 5.0 Internet Information Services Snap-In, which provides an since a user account may not have permission tools that allow you to administer your

M is Web server software that allows you to


host multiple Web sites on the Internet or
on a network, such as a corporate intranet.
interface you can use to administer your Web sites; and
World Wide Web Server, which allows users to access
your Web sites.
to install all the components that IIS requires.
Logging on to the computer as administrator
will ensure that you have all the necessary
Web sites. Display the Control Panel and
double-click Administrative Tools. In the
Administrative Tools window, double-click
permissions to install IIS. Internet Services Manager to display the
IIS 5.0 is designed for use with the Windows 2000 IIS may affect the performance of an existing or new service Internet Information Services window.
operating system and is available on the Windows 2000 pack you install on the computer. If you need to install a
Professional CD-ROM disc. IIS 5.0 offers many advanced service pack, you should check the support.microsoft.com The Internet Information Services component
features that allow you to effectively host and manage Web site to determine whether the service pack should be includes several optional parts you can install. You can remove IIS from a computer.
even the busiest Web sites. Although IIS 5.0 is powerful installed before or after IIS is installed. Documentation provides help files regarding Perform steps 2 to 9 below, except select
server software, it can still be used to learn about Web the use of IIS and should be installed. File each part of the Internet Information
servers and PHP. IIS 5.0 can be used to perform all the After IIS has been installed, you may have to restart the
computer. IIS starts automatically each time the computer Transfer Protocol (FTP) Server allows IIS to host Services component you want to remove
examples in this book. FTP sites. Personal Web Manager provides a in step 6 ( changes to ). Removing
is started.
To install IIS on a computer, you must add parts of the graphical interface you can use to administer IIS from a computer does not remove the
Internet Information Services component to the computer. PHP can be installed either before or after installing IIS. your Web sites. SMTP Service allows IIS to Inetpub\wwwroot directory and the files
The parts of the component that must be added are You can have multiple installations of IIS on a computer, send e-mail messages. it stores from the computer.
Common Files, which are the files required to run IIS; but you can have only one installation of PHP.

INSTALL INTERNET INFORMATION SERVER

My Do My Do My Do My Do
Change or Change or Change or Change or
Remove Remove Remove Remove
Programs Programs Programs Programs

My C My C My C My C

Add New Add New Add New Add New


Programs Programs Programs Programs

My N My N My N My N
P P Internet Information Services (IIS) 18.3 MB P P
World Wide Web Server 1.9 MB
Add/Remove Add/Remov Add/Remov Add/Remov
Windows Windows Windows Windows
Components Component Component Component
Recy Recy Recy Recy
5.6

Int Int Int Int


Ex Ex Ex Ex

⁄ Insert the Windows 2000 ¤ In the Control Panel, › Click Internet Information ˇ Click Details to display Á Click the box ( ) beside each ‡ Click OK to confirm ■ When the installation is ■ You should restart the
Professional CD-ROM disc double-click Add/Remove Services (IIS). the Internet Information part of the Internet Information your selections. complete, a message indicates computer before using
into a drive. Programs to display the Services (IIS) dialog box. Services component you want to that you have successfully Internet Information
Add/Remove Programs ■ This area displays a install ( changes to ). ° Click Next to install completed the Windows Server.
Note: If the Microsoft Windows 2000 window. description of the Internet the parts of the Internet Components Wizard.
CD dialog box appears, click to Information Services ■ In this example, Common Files, Information Services
close the dialog box. ‹ Click Add/Remove component. Internet Information Services component you selected. · Click Finish to close the
Windows Components Snap-In and World Wide Web wizard.
to display the Windows Server are selected.
12 Components Wizard. 13
PHP GETTING STARTED WITH PHP 1
ADD A VIRTUAL DIRECTORY TO
INTERNET INFORMATION SERVER
You can also use Windows Explorer to add a You can easily remove a virtual directory

W
hen Internet Information Server (IIS) is installed, alias is often used to shorten a long directory name. For virtual directory to IIS. Start Windows Explorer you no longer need from IIS. Perform
a number of directories are created that can example, a directory named '2001_marketing_information' and then select the directory you want to add steps 1 and 2 below to display the Internet
be used to store Web pages and PHP pages. could be assigned the alias 'marketing'. Short directory as a virtual directory. Click the File menu and Information Services window and then
By default, these directories are stored in the document names can help make a Web site easier for users to then choose Properties. In the Properties select the virtual directory you want to
root directory C:\Inetpub\wwwroot. Only pages stored navigate. dialog box, click the Web Sharing tab and then remove. Click the Delete button ( )
in the document root directory or its subdirectories can select the Share this folder option. In the Edit and then click Yes in the dialog box that
be displayed by users. You can create a virtual directory Virtual directories allow IIS to make a directory accessible Alias dialog box that appears, type an alias for appears. Removing a virtual directory
to make pages that are not stored in the document root to users of a Web site regardless of the location of the the virtual directory and then select the access prevents users from accessing pages
directory or its subdirectories available for viewing. directory. For example, the directory C:\datapages can be and application permissions you want to use stored in the directory but does not
added to the abccorp.com Web site as a virtual directory for the directory. Then click OK. Click OK in remove the directory and its contents
In order for PHP pages stored in a virtual directory to be with the alias 'data'. Users can then use the address the Properties dialog box to add the virtual from the computer.
processed by the Web server, the virtual directory must be www.abccorp.com/data/ to access pages in the virtual directory to IIS.
properly configured. The Virtual Directory Creation Wizard directory. Users accessing a virtual directory you have
can help you add and configure a virtual directory. added to IIS will not be able to determine the actual
location of the directory on the computer.
You must give the virtual directory an alias, which is a
name users will use to access pages in the directory. An

ADD A VIRTUAL DIRECTORY TO INTERNET INFORMATION SERVER

Default Web Site Site

New Virtual Directory

⁄ In the Control Panel, ‹ Click to display ˇ Click Action. ‡ Click Virtual Directory. ■ The Virtual Directory ° Click Next to continue. · Type an alias for the ‚ Click Next to continue.
double-click Administrative a list of Web sites on the Creation Wizard appears. virtual directory.
Tools to display the Web server ( changes Á Click New.
Administrative Tools window. to ).
¤ Double-click Internet › Click the Web site
Services Manager to display you want to add a virtual
the Internet Information directory to. CONTINUED
Services window.

14 15
PHP GETTING STARTED WITH PHP 1
ADD A VIRTUAL DIRECTORY TO
INTERNET INFORMATION SERVER
ou must specify the location of the directory you The Browse permission allows users to view a list of all

Y 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
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
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
After adding a virtual directory to
Internet Information Server, you can
enable or disable the logging function
for the directory. Display the Internet
pages and other files in the directory can be utilized. a page, including a PHP page, from the list.
you want to change. Click the Properties Information Services window and then
The Read permission allows users to access Web or After a virtual directory is created, all the pages and files in button ( ) to display the Properties dialog select the virtual directory you want to
PHP pages and must be turned on for a virtual directory the directory will be available to users accessing the Web box and then click the Virtual Directory tab. change. Click the Properties button ( )
containing content you want to be displayed. The Read site. You should be careful to store only files and Web or Click in the Execute Permissions area and to display the Properties dialog box
permission is turned on by default. PHP pages you want users to be able to view in the virtual select the option you want to use. The Scripts and then click the Virtual Directory
directory. and Executables option allows all file types to tab. Click the Log visits option to
The Run scripts permission allows scripts to run in the be accessed or executed in the directory. The enable ( ) or disable ( ) the
directory and must be turned on for virtual directories A virtual directory you add to IIS may be affected by folder Scripts only option allows only scripts, such as recording of visits to the directory
that contain PHP pages. The Run scripts permission is permissions set by the Windows operating system. Folder PHP files, to be run. The None option allows in a log file.
turned on by default. permissions restrict who can access the folder and how the access to only static files, such as HTML or
files in the folder can be used. For more information about image files.
The Execute permission allows applications to run in folder permissions, see page 132.
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.

ADD A VIRTUAL DIRECTORY TO INTERNET INFORMATION SERVER (CONTINUED)

sales

— Type the path of the ■ You can also click the ¡ Click an access ™ Click Next to continue. ■ A message appears, £ Click Finish. ■ The virtual directory is ¢ Click to close
directory you want to Browse button to locate the permission in this area indicating that you have added to Internet Information the Internet Information
add as a virtual directory. directory on the computer. to turn the permission successfully completed Server and appears in this area. Services window.
on ( ) or off ( ). the Virtual Directory
± Click Next to continue. Creation Wizard.
16 17
PHP GETTING STARTED WITH PHP 1

SET WINDOWS FILE AND Great care must be taken when setting file and If you no longer wish a user or group to
FOLDER PERMISSIONS folder permissions on a Web server. To gain a full
understanding of file and folder permissions and the
have permission to access a file or folder,
you can remove the user or group. Perform
consequences of changing these permissions, you steps 1 to 4 below to display the Security
ou can change permissions to grant users and groups as change permissions. Modify allows users to modify, add,

Y 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
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.
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
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.
the operating system and file system installed on the Web Read allows users to display files and Write allows users to data deletion to serious security breaches. Incorrect
server. The steps below are for use on a server running the change files. file and folder permissions can also prevent all users
Windows 2000 operating system with the NTFS file system. from accessing the Web server.
Windows file and folder permissions work with the access
When IIS is installed, a user account is created called permissions set in IIS. Access permissions set for a folder in
IUSR_ followed by the name of the computer, such as IIS apply to all users who access the folder. Windows folder If you develop your PHP pages on a different Web
IUSR_WEBSRV. This user account is part of the Everyone permissions apply only to the users and groups you specify. server than you publish the pages on, you must
group. If you deny the Everyone group access to a file or When Windows file and folder permissions and IIS access ensure that the appropriate file and folder permissions
folder, you can use the IUSR account to allow users to permissions are set differently, the Web server uses the are set on the Web server on which the pages are
access information in the file or folder. most restrictive permissions. For more information about published. The permissions will not be transferred to
IIS access permissions, see page 14. the Web server when you transfer the files for the
You can allow or deny permissions for a user or group
PHP pages.
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 Properties My Network My Network My Network
Places Places Places Places

Recycle Bin Recycle Bin Recycle Bin Recycle Bin

Internet Internet Internet Internet


Explorer Explorer Explorer Explorer

⁄ Click the file or folder ¤ Click File. › Click the Security tab. ˇ Click Add to display the Á Click a user or group in ■ You can repeat steps 6 · Click a user or group ‚ Click an option to allow
you want to change the Select Users, Computers, this area you want to have and 7 for each user or in this area to view their or deny the permission.
permissions for. ‹ Click Properties to ■ This area lists the users or Groups dialog box. access to the file or folder. group you want to be able permissions.
display the Properties and groups that can access to access the file or folder. — Click OK to confirm
dialog box. the file or folder. ‡ Click Add. ■ This area displays the your changes.
° Click OK to confirm permissions granted to
■ The user or group you your selection. the user or group.
selected appears in this area.
18 19
PHP GETTING STARTED WITH PHP 1
INSTALL PERSONAL WEB SERVER
M
icrosoft Personal Web Server (PWS) allows you to The C:\Inetpub\wwwroot directory is automatically set as the
host a single Web site on your own computer to home directory for PWS. The home directory is where you
In addition to Windows 98, PWS can be used on You can double-click the Personal Web
make Web and PHP pages available for viewing. will store all the Web and PHP pages you want to be able to
a computer running the Windows 95 or Windows Server icon ( ) on the taskbar to display
This allows you to test and troubleshoot any problems display. If you do not want to use the C:\Inetpub\wwwroot
NT Workstation operating system. If you do not have the Personal Web Manager window. The
before transferring the pages to a Web hosting service directory as the home directory, you can set another
your Windows 98 CD-ROM installation disc or you Personal Web Manager window allows you
on the Internet. Personal Web Server 4.0 is available on directory as the home directory. This is useful if you already
are using Windows 95 or Windows NT Workstation, to administer your Web site. For example,
the Windows 98 CD-ROM installation disc. have a directory that stores the pages you want users to be
you can obtain Personal Web Server 4.0 at the to stop PWS and make your Web site
able to display and you do not want to copy the pages to the
PWS is not suitable for making information available directly www.microsoft.com Web site. PWS is part of the unavailable to users, click the Stop button.
default home directory.
to users on the Internet, but can be used to share documents Windows NT 4.0 Option Pack. To restart PWS, click the Start button.
on small networks or intranets. After PWS and PHP are installed, you can begin creating and
accessing Web and PHP pages. You can access pages using a You do not have to start PWS manually each time In addition to wwwroot, several other
When installing PWS, you can choose the installation option Web browser installed on the same computer that is running
that best suits your needs. The Minimum option installs only you want to use the software. Once you have directories are created when PWS is
PWS or a Web browser installed on another computer on the installed the Web server software, PWS will start installed. In the Personal Web Manager
the files required to run PWS and is useful when installing same network. To install PHP on a Windows-based computer,
PWS on a computer with limited hard drive space available. automatically each time you start your computer. window, you can click C:\Inetpub\wwwroot
see page 22. to display these directories.
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

C:\Inetpub\wwwroot

⁄ Locate and double-click ■ The Microsoft Personal ‹ Click the type of Note: If you choose Custom, ■ This area displays the ■ If you want to use ■ When the installation is ˇ Click Finish to exit
the setup.exe file for the Web Server Setup dialog installation you want the following steps will be location of the Personal a different directory as complete, a message appears the setup program.
Personal Web Server setup box appears, displaying to perform. different for your installation. Web Server home directory. the home directory, click thanking you for choosing
program. information about Personal Browse to specify the Microsoft software. ■ A message will appear
Web Server. directory you want to use. asking you to restart your
Note: On the Windows 98 CD-ROM ■ The Personal Web Server computer. Click Yes to
disc, the setup.exe file is located in ¤ Click Next to continue. › Click Next to continue. icon appears on the taskbar. restart your computer.
the add-ons directory in the pws
subdirectory.

20 21
PHP GETTING STARTED WITH PHP 1
INSTALL PHP ON A The most recent release of PHP is available If you wish to install the expanded

WINDOWS-BASED COMPUTER 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
version of PHP, you will need a
program capable of unzipping files,
such as WinZip. WinZip is available
n order to create and process PHP pages, you need to computer that has Web server software and the PHP program accompanies this book, you should carefully at www.winzip.com. You can find

I install PHP on your computer. Recent Windows versions


of PHP can be used with Microsoft Windows 95, 98, NT,
2000, ME and XP.
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
review the documentation included with the
software. Newer releases of PHP may work
differently than the version used in this book.
complete installation instructions for
the expanded version in the install.txt
and README.txt files, which are
pages can use any type of operating system, such as UNIX. included with the PHP Zip file. You
A recent release of PHP is included on the CD-ROM disc that should carefully review each of these
accompanies this book. You can install PHP directly from the When you start installing PHP, you must first accept a license Older versions of PHP are still available following files before installing PHP.
CD-ROM disc. The PHP program is available in a standard agreement before the installation will continue. The setup the release of a new version. This is useful for
package, which includes a Windows installation program that program then allows you to choose the type of installation system administrators who have standardized a
allows you to easily install the software. PHP is also available you want to perform. The Standard option is recommended particular version of PHP for use on their Web
in an expanded package that includes additional capabilities, for most users. The Advanced option allows experienced servers. Many Web and network administrators
such as database support for different operating systems. The Web site developers to specify additional options for will not immediately upgrade to the latest
standard package consists of a single executable file, while installing PHP. available version of PHP unless they wish to take
the expanded package is compressed into a Zip file. For advantage of a specific feature of the new version.
Windows installations, it is usually sufficient to install the You must also choose the directory where you want the Administrators often decide to wait until a recent
standard package using the Windows installation program. main PHP files to be stored. The default installation location version of PHP has been widely used so they are
is C:\PHP. You can specify another destination folder, but it aware of any errors or compatibility problems
The computer on which you install PHP does not need to is recommended that you accept the default folder. before installing the new version.
be connected to the Internet. You can use a stand-alone

INSTALL PHP ON A WINDOWS-BASED COMPUTER

My Documents My Documents My Documents My Documents

⁄ Double-click the icon for ■ This area displays ■ This area displays a ‹ Click I Agree to accept › Click the type of installation ˇ Click Next to continue. ■ This area displays the Á Click Next to continue.
the PHP installation program information about the license agreement you the agreement and continue. you want to perform. folder where PHP files
to start installing the program. PHP program. must read and accept will be installed.
before continuing. Note: If you choose Advanced, the
■ A welcome dialog box ¤ Click Next to continue. following steps will be different for ■ You can click Browse
appears. to specify a different CONTINUED
your installation.
folder in which to install
22 the files. 23
PHP GETTING STARTED WITH PHP 1
INSTALL PHP ON A
WINDOWS-BASED COMPUTER PHP should be installed only on the hard drive If the computer stops responding before the
of the Web server. You should not install PHP PHP installation is complete, there may be a

W
hen installing PHP, the setup program allows correctly with some types of Web servers, such as Internet
you to specify the name of the mail server the Information Server (IIS). The setup program allows you on a network drive or on removable media, problem with the installation program or with
computer will use to send e-mail messages. to select the type of Web server you will use with PHP. such as a Zip drive. While it is technically the disk drive where PHP is being installed.
Specifying e-mail information is important if you intend to Depending on the Web server you select, PHP may possible to install PHP on these types of media, You should close all open programs and restart
create PHP scripts that will send e-mail messages. Mail automatically configure the server to work with PHP. the performance of the program will deteriorate the computer before attempting to re-install
servers used to send e-mail messages use the Simple Mail as the Web site is accessed more often. the program. If the installation program stops
Transfer Protocol (SMTP) and are often referred to as SMTP When you have specified all the installation options, you responding again, you can download another
servers. The network administrator or ISP should be able to can install PHP on your computer. The program should When specifying the e-mail address you want copy of the installation files from the main
tell you the name of the mail server used to send messages. take only a few minutes to install. to display on outgoing e-mail messages, you PHP Web site. You should also check the
If you do not have access to an SMTP server, you can type may want to use an e-mail address set up computer's hard drive for possible errors.
After PHP has been installed, you can configure PHP to suit
"localhost" as the mail server name. your needs using the php.ini file included with the program. especially for the Webmaster, instead of the
For more information about configuring PHP, see page 26. personal e-mail account of the person who
You should also specify the e-mail address you want to holds the Webmaster position. This lets you
display on outgoing e-mail messages. You would usually You may also need to configure the Web server you want
to use with PHP. To configure Apache Web server, see avoid having to reconfigure the PHP settings
specify the address of the Web server administrator, usually if the Webmaster changes in the future.
referred to as the Webmaster. page 10. For information about configuring another type
of Web server, refer to the server's documentation.
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)

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 ° Double-click this area ‚ Select the type of Web Note: PHP may not be able to ■ A dialog box appears, ± Click Next to install ■ A dialog box appears ¡ Click OK to close
and type the name of the and type the e-mail address server you want to be automatically configure the Web indicating that you are PHP on the computer. when the installation is the dialog box and then
outgoing mail server. you want to display on configured for use with PHP. server you select. ready to install PHP. complete. restart the computer.
outgoing mail.
■ If you do not know the ■ If your Web server does — Click Next to continue. ■ You can click Back to
name of the mail server, · Click Next to continue. not appear in the list, you return to a previous screen
you can type localhost. can select None to configure and change the information
the server manually. you entered.
24 25
PHP GETTING STARTED WITH PHP 1

CONFIGURE PHP On computers running the Windows


operating system, the php.ini file should be
stored in the main Windows directory, such
When you enable extensions in the php.ini
configuration file, you may have to specify
where the files for the extensions are stored.
ou can use the php.ini file to configure PHP to suit directive name followed by an equal sign (=) and a value.

Y
as C:\WINNT or C:\WINDOWS. On Unix All extension files are stored in a directory
your needs. The php.ini file is a text file that controls For example, the directive used to turn off error logging systems, the location of the php.ini file can called extensions. By default, the extensions
how PHP processes scripts and is read by the Web is log_errors = Off. You can change the value of a vary, but the file can often be found in the directory is a subdirectory of the main PHP
server when PHP is started. directive to change the way PHP operates. For example, /usr/local/lib/ directory. directory. If the extensions directory is
you can change how long a script can execute or how stored in another location, you can use the
You can edit the php.ini file using a simple text editor, much memory a script can use. Each directive appears PHP is comprised of many modules that are extension_dir directive in the php.ini
such as Notepad on a Windows computer, or vi, a text on its own line in the file. used to perform different tasks, such as the file to specify the location of the directory.
editor available on most Unix computers.
MySQL module, which is used to work with The extension_dir directive can be found
A semicolon precedes some of the directives in the
The format of the php.ini file is very simple. The file MySQL databases. The php.ini file can be under the Paths and Directories
php.ini file, such as the directives that implement
contains new lines and whitespace, which make the file used to change and specify module settings. comment. In the following example, the
extensions. These directives are commonly used directives
easy to read. The new lines and whitespace are ignored Typically, each module has its own section extensions directory is a subdirectory of
that can be enabled simply by deleting the semicolon.
and so do not affect the speed at which PHP operates. heading, such as [MySQL] or [Sybase]. the C:\webfiles directory.
For example, you can remove the semicolon that precedes
The php.ini file also contains comments, denoted by a the extension=php_gd.dll directive to allow PHP Any text enclosed in brackets [] is ignored. Example:
semicolon. All the information from a semicolon to the to generate images on the fly. Enabling an extension extension_dir = c:\webfiles
end of the line is ignored. allows you to add extra functionality to PHP. You can view more detailed information
about configuring PHP at the
The php.ini file is comprised of many directives that www.php.net/manual/en/configuration.php
control the behavior of PHP. A directive consists of a Web site.

CONFIGURE PHP

⁄ Locate and open the CHANGE RESOURCE LIMITS ‹ To change the maximum › Delete the current ˇ To change the maximum Á Delete the current ENABLE AN EXTENSION · Delete the semicolon
php.ini file in a text editor. ¤ Locate the Resource amount of time a script value and then type the amount of memory a value and then type the ‡ To enable an extension, that precedes the
Limits comment. can execute, locate the value you want to use. script can use, locate the value you want to use. locate the Dynamic extension directive.
max_execution_time memory_limit directive. Extensions comment.
directive. ‚ Save the changes you
° Locate the extension made to the php.ini file.
directive you want to enable.
26 27
PHP GETTING STARTED WITH PHP 1
If the Web server and PHP information The name and location of a Web server's
does not appear when you view the test file, document root directory depends on the
VERIFY THAT PHP IS INSTALLED CORRECTLY you should review the topics in this book
concerning the installation and configuration
operating system installed, the type of Web
server and the installation choices made
nce the Web server software and PHP have been To display the test file in a Web browser, you must specify of the Web server and PHP. You should also when the Web server software was installed.

O 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
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
review the documentation that came with
the Web server and your version of PHP.

You can use any text editor to create the PHP


On Windows-based computers running
Internet Information Server (IIS) or Personal
Web Server (PWS), the document root
directory is typically C:\Inetpub\wwwroot.
create a simple PHP test file and save the file on the Web
server. You can then display the file in a Web browser. on the same computer as the Web server, you can use the test file. When saving the file, ensure that On Windows-based computers running
computer name 'localhost' or the IP number 127.0.0.1. This the file is saved in a text-only format. the Apache Web server, the document root
The test file contains the phpinfo function enclosed is the IP number that computers using the TCP/IP protocol directory is typically C:\Program Files\Apache
between the <?php opening delimiter and the ?> closing use to refer to themselves. If you do not want the phpinfo function to Group\Apache\htdocs. On Unix computers
delimiter. The delimiters tell the Web server where the display all of the available information about running the Apache Web server, the
PHP code begins and ends. A semicolon must follow the If the Web server and PHP are functioning properly, the the Web server and PHP, you can specify document root directory is typically
phpinfo function. Web browser displays information about the Web server the type of information you want to display. /usr/local/apache/htdocs or /home/httpd/html.
and PHP when you display the test file. You can view To display only specific information, you
The phpinfo function is used to display information general information about PHP, such as the version can include one of the following arguments
about the setup and configuration of the Web server and number, server information, such as the name of the in the phpinfo function: INFO_GENERAL,
PHP. Using this function allows you to verify that the Web document root directory, and detailed information about INFO_CREDITS, INFO_CONFIGURATION,
server and PHP are working together properly, as well as PHP extensions and variables. INFO_MODULES, INFO_ENVIRONMENT,
confirm installation and configuration choices. INFO_VARIABLES or INFO_LICENSE.
The test file should be saved in the main, or document Example:
root, directory of the Web server. phpinfo(INFO_VARIABLES)

VERIFY THAT PHP IS INSTALLED CORRECTLY

⁄ Start a text editor. ‹ To display information ˇ Save the test file in the ■ The filename must end Á Start a Web browser. · Type the name or ■ If the Web server
about the Web server and document root directory with the .php extension. IP number of the Web and PHP are functioning
¤ Type the opening PHP, type phpinfo();. of the Web server. You may have to enclose ‡ Click this area to server followed by /. properly, the Web browser
delimiter <?php. the filename in quotation highlight the current displays information about
› Type the closing marks. Web page address. ‚ Type the name of the Web server and the
delimiter ?>. the test file and then current state of PHP.
° Type http://. press Enter.
28 29
PHP GETTING STARTED WITH PHP 1
CHANGE UNIX FILE PERMISSIONS
ach file on a Unix computer includes a set of been assigned read, write and execute permissions and You can use this chart to determine and change You can change the owner of a file using

E 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.
the group and other users have been assigned only read
permission.
New file permissions are usually set using the chmod
the permissions for a file on a Unix computer.
PERMISSIONS: OCTAL VALUE: DESCRIPTION:
the chown command. When using the
chown command, you must specify the
username of the new owner followed by
--- 0 None the name of the file you want to assign
Only the owner of a file or the system administrator command. The chmod command takes two arguments. to a new owner. For example, you can
can change the permissions for a file. The first argument specifies a value that represents the --x 1 Execute only
type chown sandyr index.html to give
file permissions, while the second argument specifies -w- 2 Write only ownership of the index.html file to the
To view the current permissions for a file, you can use the name of the file to which the permissions are to be
the ls -l command to display a list of all the files in -wx 3 Write and execute user sandyr.
assigned.
a directory. The permissions are usually displayed to the r-- 4 Read only
left of each filename. The value that represents file permissions is usually You can use the chgrp command to
r-x 5 Read and execute
specified using octal notation. Octal notation uses a assign a file to a new group. To use the
On Unix systems, files can be assigned read (r), write (w), rw- 6 Read and write chgrp command, specify the name of
base-8 numbering system. The octal value consists of
and execute (x) permissions. The permissions for a file three digits, which represent the permissions for the rwx 7 Read, write and execute the group to which you want to assign the
are typically represented by a dash followed by a series owner, followed by the permissions for the owner's file followed by the name of the file. For
of nine characters. The first three characters represent the group and the permissions for other users. For example, example, you can type chgrp webadmins
permissions for the file's owner. The next three characters the -rwxrw-r-- permissions will have an octal value of 764. index.html to assign the index.html file
represent the permissions for the owner's group and the You should precede the octal value with a zero (0). to the webadmins group.
last three characters represent the permissions for all other
users. For example, -rwxr--r-- indicates that the owner has

CHANGE UNIX FILE PERMISSIONS

⁄ To view a list of files ■ The list of files appears. ¤ To change the permissions › Type the name of the ˇ Repeat steps 2 to 4 Á To view the new file ■ An updated list of files
in the current directory This area displays the for a file, type chmod. file to which you want to for each file for which permissions, type ls –l appears, displaying the
and the permissions for permissions for each file. assign the permissions. you want to change and then press Enter. new file permissions.
each file, type ls –l at the ‹ Type the octal value that Then press Enter. permissions.
prompt. Then press Enter. represents the permissions
you want to assign to the file. Note: To assign the same
The octal value should be permissions to more than one
preceded by a 0. file, you can type the name of
30 each file after the octal value. 31
PHP GETTING STARTED WITH PHP 1
TRANSFER PAGES TO A Web hosting services are companies that You can create a new directory to store and
WEB HOSTING SERVICE make Web pages available on the Web.
When choosing a Web hosting service,
organize your Web server connections. In
the Configured Sites area of the Connection
you should consider several factors. For dialog box, click the directory you want

I
f you do not have a Web server that can make your To set up a connection to a Web server, you must know example, you may want to look for a Web to store the new subdirectory. If you want
Web and PHP pages available on the Web, you must the address of the server, your user ID and your password. hosting service with adequate technical to create a main directory, click the Sites
transfer the pages to a Web hosting service's Web If you do not know this information, contact your Web support services to meet your needs. directory. Then click to create the
server. You need a File Transfer Protocol (FTP) program hosting service. Many FTP programs allow you to save You should also ensure that your hosting directory. In the New Folder dialog box,
to transfer your Web and PHP pages to a Web server. your password, which saves you from having to retype service offers enough storage space for type the name of the new directory and
WS_FTP Pro for Windows is a popular FTP program. your password each time you transfer Web pages to the any multimedia files included in your then click Finish.
In the example below, we use WS_FTP Pro version 6.7. Web server. When you save your password, anyone who pages. A good Web hosting service will
You can obtain the latest version of WS_FTP Pro at the uses your computer will be able to connect to the Web also be able to supply you with statistics FTP programs allow you to set up multiple
www.ipswitch.com Web site. server, so you should not save your password if other about your pages, such as where users connections. This is useful if you want
people have access to your computer. are from and any error messages that
Before you can transfer Web and PHP pages to a Web to use one connection to transfer your
may have been generated. Web and PHP pages to a Web server and
hosting service's Web server, you must set up a connection You need to set up a connection to a Web server only
to the server. FTP programs can connect and transfer files once. After you set up a connection, you can connect another connection to download files from
to different types of Web servers using different types to the server at any time. a different Web server. Perform steps 1 to 9
of operating systems. For example, you can use an FTP starting on page 32 for each connection
program to transfer PHP pages developed on a Windows you want to set up.
computer to a Unix computer.

SET UP A CONNECTION CONNECT TO A WEB SERVER

www.company.com

jsmith

Country Kitchen Web

⁄ Start the FTP program ‹ Type a name for the ■ The name of the ■ The address of the ‡ Click this area and type · Click Save to have ⁄ Click the connection for ¤ Click Connect to
you will use to transfer your connection. connection appears Web server you specified your password. A symbol (x) the program store the the Web server you want to connect to the Web
Web pages to a Web server. in this area. appears in this area. appears for each character information you entered transfer your Web pages to. server.
› Click this area and type you type to prevent others for the connection.
■ The Connection dialog the address of the Web Á Click this area and from seeing your password. ■ If the connection you set
box appears. server you want to transfer type your user ID. up is not displayed, click
your Web pages to. ° To save your password so the plus sign ( ) beside
¤ Click to display the you will not need to retype the the Ipswitch directory
New Site dialog box and set ˇ Click Finish to continue. password again later, click this ( changes to ).
up a new connection to the CONTINUED
option ( changes to ).
Web server.
32 33
PHP GETTING STARTED WITH PHP 1
TRANSFER PAGES TO A
WEB HOSTING SERVICE If you have accidentally transferred a You should check all references to files
nce you have connected to a Web hosting service's If your connection to the Web server is idle for an extended file to the Web server, you should delete on your Web and PHP pages before

O 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.
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.
the file from the server. This helps save
storage space and prevents clutter on the
Web server. To delete a file from the Web
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
server, select the file in the right pane of sure you specified only the name of the
Before transferring your Web or PHP pages to a Web If you later make changes to the Web or PHP pages stored the WS_FTP Pro window and then click image (example: banner.gif). If the image
server, you should make sure the filenames all have the on your computer, you must transfer the updated pages the Delete button. To confirm the deletion, is stored in a subdirectory, make sure you
.html, .htm or .php extension and do not include spaces to the Web server. The updated Web or PHP pages will click Yes in the dialog box that appears. specified the location and name of the
or special characters, such as * or &. You should also replace the old pages on the server. When you transfer image (example: images/banner.gif).
check with your Web hosting service to ensure that you updated pages, a message may appear, indicating that the You can delete a connection you no
have used the correct name for your home page. updated pages will replace the old pages. longer need. Click the connection in the If you use a Macintosh computer to create
Configured Sites area of the Connection your PHP pages, you can use the Fetch
You must also locate the directory on the Web server you Many Web and PHP pages work together and require other dialog box and then click to delete
want to transfer your files and directories to. This directory pages in order to work correctly. When transferring files, FTP program to transfer your pages to a
the connection. To confirm the deletion, Web hosting service. Fetch is available at
is often named "public." If you do not know the name of you should ensure that you also transfer any needed click Yes in the dialog box that appears.
the directory, contact your Web hosting service. Your Web support files. the www.fetchsoftworks.com Web site.
hosting service may also stipulate where you can place
PHP files on the Web server.

TRANSFER PAGES TO A WEB HOSTING SERVICE

www.company.com www.company.com www.company.com www.company.com

public
My Webs

recipes . htm

■ The WS_FTP Pro ⁄ Locate the directory you ■ This area displays the Note: You can double-click ˇ Click the file or directory Á Click to transfer ■ The file or directory ° Click Close to end
window appears. want to transfer your Web directories and files stored to move up one level in the you want to transfer to the the file or directory to appears on the Web server. the connection to the
pages to. In many cases, the on your computer. directory structure. Web server. the Web server. Web server.
■ This area displays the directory is named "public." ‡ Repeat steps 3 to 6 for
directories and files stored ‹ Locate the directory › Double-click the each file and directory you · Click Exit to exit
on the Web server. ¤ Double-click the that contains the Web or directory to display the want to transfer. the program.
directory to display the PHP page(s) you want to contents of the directory.
contents of the directory. transfer to the Web server.
34 35
PHP LANGUAGE BASICS 2

INSERT PHP CODE INTO A WEB PAGE In addition to the <?php and ?> delimiters,
there are other delimiters you can use to
Instead of the print function, you can use
the echo command to generate output.
insert PHP code into a Web page. If you have

A
dding PHP code to an HTML document allows you information generated by the PHP code is inserted into the Example:
to create dynamic, interactive Web pages. You can the short_open_tag setting enabled in
Web page before the page is sent to a user's Web browser. echo "Thank you. Please visit again.";
add PHP code to an existing Web page or to a new your PHP configuration file, you can use
Users who visit the page will not be able to see the PHP
HTML document you create. the <? and ?> delimiters. You can also use
code, even if they display the source code for the page.
the ASP-style delimiters <% and %>. To use
PHP code is inserted into HTML code using the <?php When saving a PHP page you have created, you must add ASP-style delimiters, you need to enable the
You can use the <?= and ?> delimiters to
opening delimiter and the ?> closing delimiter. The the .php extension to the filename of the page. Some text asp_tags setting in the PHP configuration
insert a single print statement into an HTML
delimiters tell the Web server where the PHP code begins editors do not recognize the .php extension, so you may file.
document. Using the <?= and ?> delimiters
and ends. You can add multiple sections of PHP code to have to enclose the filename in quotation marks, such as reduces the amount of code you have to type
an HTML document. You must use an opening and closing "index.php". The PHP page must be saved in the appropriate You can use the <script> tag to insert PHP and can make your script easier to read.
delimiter for each section of code. location on your Web server before the page can be code into a Web page. Using the <script>
displayed. tag does not require any changes to the Example:
If the PHP code will generate output for display in a user's <?php
Web browser, you can use HTML tags to format the output. If you do not want to use the .php extension for your PHP settings in the PHP configuration file.
print $message;
PHP code used to generate output must be inserted pages, you can configure your Web server to use another Example: ?>
between the <body> and </body> tags. extension, such as .phtml, .htm or .html. For more <script language="php">
information, see page 10. print "Thank you. Please visit again."; Can be typed as:
When a Web server receives a request for a Web page </script> <?= $message ?>
containing PHP code, the Web server processes all the
code found between the <?php and ?> delimiters. The

INSERT PHP CODE INTO A WEB PAGE


Insert PHP Code - Microsoft Internet Explorer

⁄ Type <?php where ¤ Type ?> where you ‹ Between the opening ■ In this example, we SAVE AND DISPLAY ■ The filename must end Á Display the PHP ■ The Web browser
you want to insert PHP want to end the PHP code. and closing delimiters use the print function A PHP PAGE with the .php extension. page in a Web browser. displays the result of
code into a Web page. (<?php and ?>), type the to generate output. ˇ Save the page in the You may have to enclose inserting PHP code
PHP code you want to appropriate location on the filename in quotation into a Web page.
insert into the Web page. › Repeat steps 1 to 3 marks.
for each section of PHP your Web server.
code you want to insert
36 into the Web page. 37
PHP LANGUAGE BASICS 2
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.
Example:

ADD A COMMENT TO A PHP PAGE <?php


// Display a welcome message
print "Welcome to my Web page.<br>";
# Display my name

A
dding comments to your PHP code is a good To add a comment that spans multiple lines, use /* print "My name is Martine.";
programming practice and can help explain before the first line and */ at the end of the last line. ?>
important or difficult sections of code. Web servers While comments can be any size, very lengthy comments
ignore comments in PHP code, so adding comments to a may make your code difficult to read. The most effective
When creating multi-line comments, you should be careful not to
PHP page will not slow down the processing of the page. comments are descriptive and concise.
place one comment inside another comment. Nested comments
Even relatively simple code may be difficult to understand In addition to creating multi-line comments, you can use will generate an error when the PHP page is processed.
without comments. For example, you may use a variable /* and */ to help troubleshoot a PHP page. For example,
TYPE THIS:
named $totalCost in your code. You could use a comment if your PHP code is generating an error, you can use /*
to explain whether the variable stores the total cost of all and */ to comment out the suspect lines. If you confirm <?php
the products or only some of the products. that the error lies somewhere else in the PHP code, you /* Name: comments.php
Purpose: To show how not to use delimiters
can simple remove /* and */ to restore the lines of code.
Besides describing the purpose of code, comments can Commenting out the lines saves you from having to erase
Author: Martine Edwards <martine@abccorp.com>
contain information such as the name of the author and the lines and type them again later. This technique is very
the author's contact information. /* Display a welcome message */
effective for debugging large, complex sections of code. print "Welcome to my Web page.";
A single-line comment is preceded by // and can be For more information about troubleshooting PHP code,
see pages 208 to 219. PHP will try to process these lines of comments
included at the end of a line of code. A single-line
and generate an error */
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.
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 ¤ Type the comment. ■ Repeat steps 1 and 2 for ■ A single-line comment ‹ To add a multi-line ˇ Type */ to complete Á Display the PHP page ■ The comments do not
comment, type //. each single-line comment can be on its own line or comment, type /*. the multi-line comment. in a Web browser. appear on the PHP page.
you want to add. at the end of a line of code.
› Type the comment.
38 39
PHP LANGUAGE BASICS 2
Unlike other languages, such as C++ and Java, When working with numbers, PHP assumes
CREATE A NUMERIC VARIABLE PHP is not a strongly typed language. In PHP,
you do not need to explicitly declare the type
you are working in base 10, or decimal
notation. PHP also supports base 8, or
of variable you want to create. For example, the octal notation, and base 16, or hexadecimal
variable is a name that represents a value. For A variable name can consist of multiple words. You can

A 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
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.
same variable can be used to represent first an
integer and then a floating-point number with
no data type declarations.
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
of a calculation or data retrieved from a database. The underscore character (_) can also be used to separate Example:
a hexadecimal number. When you display
the words in a name, such as $my_age. You should choose $a = 1;
an octal or hexadecimal number, the result
To create a numeric variable, you use the assignment one format and use it consistently to make your script $a = $a + 1.5;
operator (=) to assign an initial value to a variable name. is shown in decimal notation.
easier for other people to understand.
A numeric variable can store an integer, such as 1 or 3452, Example:
or a floating-point number, such as 9.3 or 0.0054. A Variable names are case sensitive. For example, the
You can use exponential notation to specify a $a = 020;
numeric variable can also store a negative value or no variable $myAge is different than the variable $MYAGE. print $a;
very large or very small number as the value
value at all. To specify a negative value, you simply place print "<br>";
Several sections of PHP code can be inserted into one of a variable. In this following example, $a is
a minus sign (-) directly in front of a number. A numeric $b = 0x10;
HTML document. The value of a variable created in one equal to 123000 and $b is equal to
variable with no value has a null value, which is not the print $b;
section of PHP code will be accessible in subsequent 0.0000123.
same as a value of zero (0).
sections of the code. Example: Result:
In PHP, a variable name must start with a dollar sign ($). $a = 1.23e5; 16
The next character must be a letter or the underscore $b = 1.23e-5; 16
character (_) followed by any combination of letters
and numbers.

CREATE A NUMERIC VARIABLE

⁄ To create a numeric ■ The dollar sign ($) ¤ Type = followed by ■ The value can be an ‹ Type the code that ■ In this example, we › Display the PHP page ■ The Web browser
variable, type $ followed must be followed by a the value you want to integer or a floating-point uses the numeric variable use the print function in a Web browser. displays the value of
by a name for the variable. letter or an underscore assign to the variable. number. you created. to display the value of the numeric variable.
character (_). the variable.

40 41
PHP LANGUAGE BASICS 2
The following is a list of several common escape sequences
that can be enclosed in double-quoted strings.
ESCAPE SEQUENCE: DESCRIPTION:
\n Start a new line.

CREATE A STRING VARIABLE \r


\t
Insert a carriage return.
Insert a tab.
ou can create a variable that stores a string value. the string. For example, a variable in a double-quoted string \\ Insert a backslash.

Y 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
will be replaced with the value assigned to the variable
when the string is processed.
When including a character required by the PHP
\"
\$
\012
Insert a double quotation mark.
Insert a dollar sign.
Use an octal ASCII value (example: 12).
information. The quotation marks identify the beginning
and end of a string and allow PHP to work with the string programming language in a double-quoted string, you \x0A Use a hexadecimal ASCII value (example: 0A).
as one piece of information. must precede the character with a backslash if you do
not want the character to be evaluated. For example, when
Strings can be joined together using the concatenation operator (.).
To create a string variable, you use the assignment a dollar sign ($) is placed in a string, PHP will evaluate the
The concatenation operator can be used to join two strings, such as
operator (=) to assign a string value to a variable name. dollar sign as the beginning of a variable name unless you
"Tom" . "Smith", or a combination of strings and variables, such
A variable name must begin with a dollar sign ($) followed use a backslash to escape the symbol.
as $myString = "I am " . $myAge . " years old".
by a letter or the underscore character (_). Variable names
can consist of multiple words and are case sensitive. When a string is enclosed in single quotation marks, PHP
does not evaluate variables or escape sequences in the PHP is often used to output HTML code. When assigning an HTML tag,
Escape sequences allow you to include special characters, string, except for the \\ and \' escape sequences. You can such as <IMG SRC="my_image.gif" WIDTH="100" HEIGHT="100">
such as tabs, newlines and carriage returns in a string and use the \\ escape sequence to display a backslash and to a string variable, you must use escape sequences to include any special
are often used to format text that will be displayed on a the \' escape sequence to display a single quotation mark characters, such as quotation marks, within the tag. The HTML code within
screen or stored in a file. When a string you assign to a in a single-quoted string. the string will be processed by the Web server and applied to the output
variable is enclosed in double quotation marks, PHP will for a client's Web browser.
evaluate any escape sequences and variables included in Example:
$myImageTag = "<IMG SRC=\"my_image.gif\" WIDTH=\"100\" HEIGHT=\"100\">";

CREATE A STRING VARIABLE

My Web Site

⁄ To create a string variable ‹ Between the quotation › To create a string variable Á Between the quotation ‡ Type the code that ■ In this example, we ° Display the PHP ■ The Web browser
using double quotation marks, type the information using single quotation marks, type the information uses the string variables use the print function page in a Web browser. displays the values of
marks, type $ followed by you want the string to contain. marks, type $ followed by you want the string to you created. to display the values of string variables.
a name for the variable. a name for the variable. contain. variables.
■ PHP will evaluate any
¤ Type = "". variables and escape sequences ˇ Type = ''. ■ PHP will not evaluate
you include in the string. information you include
42 in the string. 43
PHP LANGUAGE BASICS 2

It is good programming practice to define all You can use the defined function to verify

CREATE A CONSTANT 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
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
constant is a name that represents a value you Once a constant has been created, it can be used within

A
constants. exist, the defined function will return a
want to remain the same throughout a PHP script. calculations in the same way you use a variable. Attempting value of 0. Using the defined function is
Regardless of where a constant is created in a PHP to change the value of a constant when using the constant In addition to a string or number, you can use useful for quickly determining if a constant
script, the constant can be accessed anywhere in the script. will generate an error. an expression as the value for a constant. This exists in a long script that uses a large number
is useful when you want to display a different of constants.
You use the define function to create a constant in your Unlike variables, constants do not start with a dollar symbol,
script. You must first specify the name of the constant you so PHP cannot determine when a constant is being used in value for the constant depending on the value Example:
want to create. Constant names must start with a letter or a string. For example, in the string "This page was created of a variable. For example, you can create a <?php
an underscore (_) character. To help distinguish constants by AUTHOR", PHP will interpret the constant AUTHOR not constant that stores a personalized greeting if (defined("AUTHOR"))
from variables, you should use all uppercase letters in a as a value, but as the word AUTHOR. You must separate a based on the user name of the person visiting {
constant name. The name of the constant must be enclosed constant you are using from the rest of the string to allow your Web site. print "Page created by: ";
print AUTHOR;
in quotation marks when specified in the define function. the constant to be evaluated correctly. Example: }
After naming a constant, you must specify the value you PHP also allows you to access predefined constants from <?php else
$userName = Lindsay; {
want to assign to the constant. A constant can store any within PHP code. For information about predefined print "Author unknown";
define("GREETING", "Hello " . $userName);
string, integer or floating point value. constants, see page 80. print GREETING; }
?> ?>

CREATE A CONSTANT

⁄ Type define() where ¤ Between the parentheses, ‹ Type a comma followed › Type the code that ■ If you are using the ˇ Display the PHP page ■ The Web browser
you want to create a type the name of the constant by the value you want to uses the value of the constant with a string, in a Web browser. displays the result of
constant. you want to create, enclosed assign to the constant. constant. make sure the constant using a constant.
in quotation marks. is not enclosed within
■ If the value for the the quotation marks for
constant is a string, you the string.
must enclose the text in
44 quotation marks. 45
PHP LANGUAGE BASICS 2
TYPES OF OPERATORS
INTRODUCTION TO OPERATORS ARITHMETIC OPERATORS

You can use arithmetic operators to perform

P
HP provides numerous operators that can be used to or more arguments, called operands. A sequence of
assign values to variables, perform calculations, make operands separated by one or more operators that produces mathematical calculations.
comparisons and much more. An operator takes one a result in a PHP script is referred to as an expression.
+ (Addition) * (Multiplication) % (Modulus)
Finds the sum of two values. Multiplies two values. Divides one value by
print 3 + 3; print 2 * 3; another value and returns
Displays 6 Displays 6 only the remainder in the
Associativity Order of Precedence
result.
When an expression contains multiple operators that have When an expression contains several operators, print 7 % 5;
the same precedence, the associativity of the operators PHP processes the operators in a specific order, - (Subtraction) / (Division)
Displays 2
determines which part of the expression PHP evaluates known as the order of precedence. The order of Finds the difference between two Divides one value by another value.
first. Operators can have left associativity, right associativity precedence ranks operators from highest to lowest values. print 9 / 3;
or can be non-associative. precedence. Operators with higher precedence are print 6 - 3; Displays 3
evaluated before operators with lower precedence. Displays 3
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. Parentheses CONCATENATION OPERATOR
Regardless of the precedence and associativity of
Some operators have neither left nor right associativity operators, you can use parentheses to dictate the You can use the concatenation
and are known as non-associative. When a non-associative order in which PHP should process operators. In an operator (.) to combine values into a . (Concatenation)
operator is used beside others with the same precedence, expression, PHP processes operators and operands string. This is useful when you want
you must surround the operator and its operands with enclosed in parentheses first. to combine text with a variable that
$temp = "hot";
parentheses to ensure that it will return the desired result. has text value. $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 Operators Associativity Operators
Increment and decrement
Non-associative new Left | operators are useful for ++value (Pre-increment) --value (Pre-decrement)
Right [ Left && creating counters in your Adds 1 to a value before the expression Subtracts 1 from a value before the
script. These operators that uses the value is processed. expression that uses the value is processed.
Right ! ~ ++ -- (int) (double) Left || increase or decrease the $a = 5; $a = 5;
(string) (array) (object) @ Left ? : value of an expression print ++$a; print --$a;
Left * / % by one. Displays 6 Displays 4
Left = += -= *= /= .= %= &= |=
Left + - . ^= ~= <<= >>=
value++ (Post-increment) value-- (Post-decrement)
Left << >> Right print
Adds 1 to a value after the expression Subtracts 1 from a value after the expression
Non-associative < <= > >= Left and that uses the value is processed. that uses the value is processed.
$a = 5; $a = 5;
Non-associative == != === !== Left xor
print $a++; print $a--;
Left & Left or print "<br>"; print "<br>";
print $a; print $a;
Left ^ Left , Displays 5 Displays 5
6 4

46 47
PHP LANGUAGE BASICS 2
INTRODUCTION TO OPERATORS
TYPES OF OPERATORS (CONTINUED) BITWISE OPERATORS

ASSIGNMENT OPERATORS Bitwise operators, such as &(AND) and |(OR), are used to compare
and manipulate values at the binary level. This can be very useful
The assignment operator (=) can be used to set one value can be written as $b += 12. Combining operators reduces when dealing with binary files such as image and sound files.
to another value. You can also combine the assignment the amount of code you need to type and can make your You can find more information about bitwise operators at the
operator with arithmetic operators to more easily perform scripts easier to read. www.php.net/manual/en/language.operators.bitwise.php Web site.
calculations. For example, the expression $b = $b + 12
COMPARISON OPERATORS
= (Assignment) += -= *= /= .=
Sets one value Adds one value Subtracts one Multiplies one Divides one Combines two values. You can use comparison operators
to another to another value from value by another value by another $a = "This is "; to compare values in your script.
value. value. another value. value. value. $a .= "a test.";
$a = 3; $a = 3; $a = 3; $a = 3; $a = 6; print $a; == (Equal to) < (Less than)
print $a; $a += 3; $a -= 1; $a *= 2; $a /= 2; Displays This is a test.
Displays 3 print $a; print $a; print $a; print $a; Checks if one value is equal to another value. Checks if one value is less than another value.
Displays 6 Displays 2 Displays 6 Displays 3 $x = 7; $x = 5;
$y = "7"; $y = 9;
if ($x == $y) print $x . " is equal to " . $y; if ($x < $y) print $x . " is less than " . $y;
Displays 7 is equal to 7 Displays 5 is less than 9
LOGICAL OPERATORS

You can use logical operators to check === (Identical to) > (Greater than)
if a statement in your script is true.
Checks if one value is equal to and of the same type as Checks if one value is greater than another value.
another value. $x = 9;
And ! $x = 7; $y = 5;
Checks if two or more statements are true. Checks if a statement is not true. $y = 7; if ($x > $y) print $x . " is greater than " . $y;
$x = 7; $y = 5; if ($x === $y) print $x . " is identical to " . $y; Displays 9 is greater than 5
$y = 5; if (! ($y == 10)) print "True"; Displays 7 is identical to 7
if (($x == 7) and ($y == 5)) print "True"; Displays True
Displays True <= (Less than or equal to)
!= (Not equal to) Checks if one value is less than or equal to another
&&
Or Checks if one value is not equal to another value. value.
Checks if two or more statements are both true. $x = 8; $x = 5;
Checks if at least one of two statements is true. $x = 7; $y = 4; $y = 5;
$x = 7; $y = 5; if ($x != $y) print $x . " is not equal to " . $y; if ($x <= $y) print $x;
$y = 5; if (($x == 7) && ($y == 5)) print "True"; Displays 8 is not equal to 4 Displays 5
if (($x == 7) or ($y == 8)) print "True"; Displays True
Displays True
!== (Not Identical to) >= (Greater than or equal to)
||
Xor Checks if two values are not equal or not of the same type. Checks if one value is greater than or equal to another
Checks if at least one of two statements is true.
$x = 8; value.
Checks if only one of two statements is true. $x = 7;
$y = 9; $x = 7;
$x = 7; $y = 5;
if ($x !== $y) print $x . " is not identical to " . $y; $y = 5;
$y = 5; if (($x == 7) || ($y == 5)) print "True";
Displays 8 is not identical to 9 if ($x >= $y) print $x;
if (($x == 7) xor ($y == 8)) print "True"; Displays True
Displays 7
Displays True

48 49
PHP LANGUAGE BASICS 2
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
PERFORM A NUMERIC CALCULATION dictate the order in which PHP should process operators. PHP will
process operators and operands enclosed in parentheses first.
ou can perform calculations to manipulate numeric You can use the assignment operator (=) to assign a

Y 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.
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
Example:
$fahrenheit = 100;
$celsius = ((($fahrenheit - 32) / 9) * 5);

will only be available within the PHP page. Once the


Calculations consist of operators and operands. Operators processing of the PHP page is complete, the variable
determine the type of calculation that will be performed. Dividing a number by zero is a mistake commonly made when
ceases to exist. performing numeric calculations. If you divide a number by zero in
Operands are the values that are manipulated in a
calculation. For example, the calculation 4 + 5 contains When a calculation contains an operand that is a variable, PHP, a Division by zero error will result. The most common
the operands 4 and 5 and the + (addition) operator. the calculation will use the value of the variable at the cause of this type of error is misspelling or mistyping a variable
time the calculation is performed. If the value of the name in a calculation. When you misspell or mistype a variable
The + operator is an example of an arithmetic operator. variable later changes, the change will not affect the name in a calculation, the variable will have a value of zero.
Arithmetic operators are commonly used when performing result of the calculation.
numeric calculations and also include the - (subtraction), TYPE THIS:
* (multiplication), / (division) and % (modulus) operators. $myNumber = 10;
Other types of operators that can be used when print 1000 / $myNumbeR;
performing numeric calculations include comparison,
logical, incrementing and decrementing operators.
For more information about operators, see page 46. 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 ¤ Type the operator for ‹ Type the second › To assign the calculation ˇ Type the code that ■ In this example, we use Á Display the PHP page ■ The Web browser
you want to use in a the type of calculation operand you want to to a variable, type $ followed uses the result of the the print function to in a Web browser. displays the result of
calculation. you want to perform. use in the calculation. by a name for the variable. calculation. display the result of the performing a numeric
Then type =. calculation. calculation.

50 51
PHP LANGUAGE BASICS 2
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)
{

USING THE IF STATEMENT }


print "It's hot.";

Can be typed as:


sing an if statement allows you to test a condition A section of code you want to be executed must be if ($currentTemp > $hot) print "It's hot.";

U 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
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
To test multiple conditions, you include elseif statements after
the if statement. An elseif statement contains a condition that
example, you can create a PHP page that displays a a statement block. can be tested. If the condition specified in the if statement is false,
Good Morning message if a user views the page between PHP will test each elseif statement until a condition is true. PHP
5:00 AM and 11:59 AM. If the condition is false, no code If you want an if statement to execute a statement block
when the condition is false, you must include an else will then execute the block for the true elseif statement. If there
from the if statement is executed. A condition will are no true elseif statements, the else statement will be executed.
be false if it evaluates to an empty string (" "), a string statement. Using an if statement with an else statement
zero ("0"), an integer zero (0) or a null value. allows you to execute one of two sections of code,
TYPE THIS: RESULT:
depending on the outcome of testing the condition.
The condition you want to test must be enclosed in If the condition is true, the statement block directly $myAge = 32;
if ($myAge < 21) Adult: $5.00
parentheses (). Unlike most PHP statements, the if following the if statement is executed. If the condition {
statement does not end with a semicolon. Ending an if is false, the statement block directly following the else print "Child: \$2.00";
statement with a semicolon is a common programming statement is executed. Using an else statement ensures }
mistake and will generate an error when the PHP page that a section of code is executed regardless of the elseif ($myAge < 65)
{
is processed. outcome of testing the condition. print "Adult: \$5.00";
}
else
{
print "Senior: \$3.00";
}

USING THE IF STATEMENT

⁄ Type the code that ¤ Type if (). › Type the code you want ˇ To use the else Á Type the code you want ‡ Display the PHP page ■ The Web browser
creates the variables and to execute if the condition statement, type else. to execute if the condition in a Web browser. displays the result of
assigns their values. ‹ Between the parentheses, you specified is true. Enclose you specified is false. using the if statement.
type the condition you want the code in braces. Enclose the code in braces.
to test.
52 53
PHP LANGUAGE BASICS 2
The decrement operator (--) can be used in One or more expressions can be omitted
the re-initialization expression to decrease the from a for statement, though this may
value of the iterator by one each time the loop adversely affect the processing of the loop.
is processed. This allows you to create a for For example, if a for statement does not
USING THE FOR STATEMENT loop that counts backwards.
Example:
include a conditional expression, PHP
assumes the condition is always true and
an infinite loop may be created. You should
rogrammers often need to execute the same block beginning of each loop. If the condition is true, the loop for ($i = 5; $i >= 0; $i--)

P 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
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
{

}
print "$i<br>";
be careful not to create an infinite loop.
Example:
for ($i = 1; ; $i++)
create five line breaks on a Web page. Instead of typing the braces {} and is known as the body of the loop. {
code that creates a line break five times, you can create a print "$i<br>";
When creating a re-initialization expression,
loop that executes the code to create a line break and then The third expression in a for statement is the }
you are not limited to using the increment and
repeats the loop until the value of a counter reaches 5. re-initialization expression. This expression is used to
decrement operators to modify the value of
modify the value of the iterator. Typically, the increment
the iterator by 1. An iterator can be modified
A for statement consists of three expressions. The first operator (++) is used in the re-initialization expression
by any increment, including floating point
expression is called the initialization expression and is to increment the value of the iterator by one each time
numbers. For example, an iterator can be
used to specify the initial value of the variable that will the loop is executed. The re-initialization expression
initialized with a value of 0 and then increased
be used to control the processing of the loop. This variable should modify the iterator in a way that will eventually
in increments of 0.5 until a value of 5 is
is referred to as the iterator and is often used as a counter lead to the conditional expression being evaluated as false.
reached.
in a loop. Otherwise, the loop will be processed indefinitely.
Example:
The second expression is known as the conditional
for ($i = 0; $i < 5; $i = $i + 0.5)
expression. This expression allows you to specify a {
condition that evaluates the value of the iterator at the print "$i<br>";
}

USING THE FOR STATEMENT

⁄ Type for (). ‹ Type the initial value › Type the conditional ˇ Type the re-initialization Á Type the code you ‡ Display the PHP page ■ The Web browser
you want to assign to expression you want to expression you want to use want to execute as long in a Web browser. displays the result of
¤ Between the parentheses, the iterator followed by use to evaluate the value to modify the value of the as the specified condition executing the loop.
type the name of the variable a semicolon. of the iterator followed iterator each time the loop is true. Enclose the code
you want to use as the iterator by a semicolon. is executed. in braces.
followed by =.

54 55
PHP LANGUAGE BASICS 2
A while loop may be used to count the number of You can place a loop within another
characters in a string or the number of lines in a file. loop to create a nested loop.
Example: TYPE THIS:
$word = "dynamic";
USING THE WHILE STATEMENT $x = 0;
while ($word[$x] != null)
{
$loopCounter = 0;
do
{
print "This is line number";

T
he while statement allows you to create a conditional code in the loop body is executed again. If the condition is $x++; for ($x = 0; $x < 8; $x++)
loop that will execute a section of code as long as a false, the statement block is not executed and the loop ends. } {
print "The word <b>$word</b> has $x characters.<br>"; print ".";
specified condition is true. Conditions often test the
value of a variable. For example, you may want to process a When creating a conditional loop, you must ensure that the }
pay statement for each of the 100 employees in a company. condition being tested will be evaluated as false at some A do..while statement can be used to test a print "$loopCounter<br>";
time. If the condition is always true, the code in the loop $loopCounter++;
Instead of typing the code that will process a pay statement condition after the body of a loop has been executed. } while ($loopCounter < 3);
100 times, you can create a loop that will repeat the pay body will be executed indefinitely, creating an infinite loop. This is useful if you have a section of code that you
statement for each employee. The condition would check You should also keep in mind that there is typically a want to execute at least once, regardless of how the
how many pay statements have been processed. After the 30-second time limit for the processing of PHP code. condition is evaluated.
You should thoroughly test your PHP code to prevent RESULT:
100th pay statement has been processed, the condition
a PHP page from possibly timing out during processing, TYPE THIS:
would be evaluated as false and the loop would end. This is line number........0
which could result in data loss. For information about $loopCounter = 0; This is line number........1
The body of a while loop is enclosed in braces {} and the timeout settings for a PHP page, see page 219. do This is line number........2
contains the section of code to be executed, called the {
statement block. If the condition tests the value of a variable, print "This is line number ";
the loop body will also contain code to alter the value of the print $loopCounter . "<br>";
$loopCounter++;
variable. When the condition is true, the statement block is } while ($loopCounter < 0);
executed. When PHP reaches the end of the loop body, the
condition is re-evaluated. If the condition is still true, the
RESULT:
This is line number 0
USING THE WHILE STATEMENT
Using The WHILE Statement - Microsoft Internet Explorer

⁄ Type the code that ¤ Type while (). ‹ Between the parentheses, › Type the code you ˇ Within the braces, Á Display the PHP page ■ The Web browser
creates a variable and type the condition you want want to execute as long as type the code that will in a Web browser. displays the result of using
assigns it a value. to evaluate. the condition you specified alter the value of the the while statement.
is true. Enclose the code in variable each time the
braces. loop is executed.
56 57
PHP LANGUAGE BASICS 2

USING 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
You can include a default statement in a
switch statement if you want to execute
specific code when none of the case

T
he switch statement allows you to execute a section The switch statement compares the value of the expression statements by grouping the case statements statements match the specified expression.
of code, depending on the value of an expression. to each case statement in order, from top to bottom. To together and including the code after the last The default statement is placed last in
When a switch statement is executed, the value of make your code more efficient, you should place the case statement in the group. This saves you from the switch statement structure.
the expression is compared to a number of possible choices, statements that are most likely to match the expression first. having to retype the same code for several
Example:
which are specified using case statements. If the value case statements.
of the expression matches a case statement, the section You can use the break statement to prevent the code for switch ($priority)
the remaining case statements from being executed after Example: {
of code following the case statement is executed. For case 1:
example, you can create a switch statement that displays a match has been made. The break statement should be switch ($item)
{ print "Urgent";
a specific message, depending on information entered by the last statement in the section of code that follows each break;
case statement. Although the last case statement does case "hat":
a user. case "shirt": case 2:
not require a break statement, some programmers include case "pants": print "High Priority";
To use the switch statement, you must first specify the it to be consistent. This can help you avoid accidentally print "Clothing Category"; break;
expression you want to use. For example, you can specify leaving out the break statement if you later add another break; default:
a variable whose value you want to check. After specifying case statement to the switch statement. case "fruit": print "Low Priority";
case "vegetables": break;
the expression, you must create the case statements that }
contain the values the expression will be compared to. A print "Food Category";
break;
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


Using the SWITCH Statement - Microsoft Internet Explorer

⁄ Type switch (). ‹ Type a pair of › Type case followed Á Type the code you ‡ Type break to prevent ° Repeat steps 4 to 7 · Display the PHP page ■ The Web browser
braces to hold the by a value the expression want to execute if the value the code for the remaining for each value the in a Web browser. displays the result of using
¤ Between the case statements. may contain. in the case statement case statements from expression may contain. the switch statement.
parentheses, type the matches the expression being executed once a
expression you want the ˇ Type : to complete you specified in step 2. match has been made.
switch statement to use. the case statement.

58 59
PHP LANGUAGE BASICS 2
Creating a loop allows you to access all the elements in an

CREATE AN ARRAY 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.
n array is a variable that stores a set of related values. the name of the array followed by the index number of the

A 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
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
TYPE THIS:
$vegetables = array ("broccoli", "carrot",
"zucchini", "eggplant");
RESULT:

broccoli
carrot
is referred to as an element. for ($x = 0; $x < count($vegetables); $x++)
a variable. The value of an element can be directly displayed { zucchini
The first step in creating an array is to create a variable to a Web browser using the print function or assigned to print $vegetables[$x] . "<br>\n"; eggplant
to store the array. You can then use the array keyword another variable that can then be processed further. }
to assign a set of values, or elements, to the variable. The
elements are enclosed in parentheses and separated by An element can be changed or a new element can be added
commas. String elements in an array must be enclosed to an array without affecting the other elements in the array.
You can use the foreach statement to create a loop that allows you
in quotation marks. For more information about changing or adding elements in
to work with each consecutive element in an array without having to
an array, see page 62.
specify each element's index. In the following example, each element
In PHP, it is possible to store values of different data types
in the $vegetables array is assigned to the $value variable.
in a single array. You may even store other arrays in an
array. PHP's array-handling capabilities make it more flexible TYPE THIS: RESULT:
and intuitive than most other programming languages.
$vegetables = array ("broccoli", "carrot",
The vegetable is: broccoli
Each element in an array is uniquely identified by an index "zucchini", "eggplant");
foreach ($vegetables as $value) The vegetable is: carrot
number, or key. PHP numbers the elements in array starting
{ The vegetable is: zucchini
at zero (0). To access a specific element in an array, you enter
print "The vegetable is: $value<br>\n"; The vegetable is: eggplant
}

CREATE AN ARRAY

⁄ Type a name for the ¤ Between the parentheses, ■ If the value for an ‹ To access an array ˇ Type the code that Á Display the PHP ■ The Web browser
array you want to create type each element you want element is a string, you element, type the name uses the element in page in a Web browser. displays an element
followed by = array (). to add to the array separated must enclose the string of the array followed by []. the array. in the array.
by a comma. in quotation marks.
› Between the brackets,
type the index of the element
you want to access.
60 61
PHP LANGUAGE BASICS 2
You can create an empty array and then later add You can create an array with an index that starts
elements to the array. This is useful when you with a number other than 0. The => operator is
WORK WITH ARRAYS want to filter array elements or dynamically add
elements to an array using data obtained from
used to explicitly assign a starting index to the
first element in the array. The next elements in
a database or a file. To create an empty array, the array will then be indexed accordingly in
nce you have created an array, you can work with need to specify an index number. PHP will assign the new

O the elements in the array. For example, you can


change or add elements in an array.
To change an element in an array, you must first specify
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
use the array keyword without placing any
elements within the parentheses.
Example:
sequence.
TYPE THIS:
$startWithTen = array (10 => "ten", "eleven",
$unfiltered = array ("apple", "orange", "not fruit", "twelve", "thirteen");
the name of the array followed by a set of brackets. You element you add to an array. If you specify an index number "grape", "banana", "not fruit", foreach ($startWithTen as $key => $value)
must then specify the index number of the element you that is more than one greater than the current largest index "not fruit", "cherry"); {
want to change. Keep in mind that PHP usually numbers number, PHP will not create elements to fill the gap between $filtered = array (); print "key: $key, value: $value<br>\n";
the elements in an array starting at zero (0). the index numbers. Any new elements later added to the foreach ($unfiltered as $value) }
{
array will be placed after the new largest index number. if ($value != "not fruit")
PHP allows you to change the value of an element in an
array by assigning the element a new value. When changing If a new element is added to an array that does not yet {
$filtered[] = $value; RESULT:
the value of an element, make sure you do not make exist, a new array will automatically be created. It is better }
unintended changes to the data, such as inserting text programming practice, however, to first create an array } key: 10, value: ten
data into an array you want to contain only numbers. before adding new elements to the array. foreach ($filtered as $value) key: 11, value: eleven
{ key: 12, value: twelve
You use a similar method to add a new element to an print "$value<br>"; key: 13, value: thirteen
existing array. When adding a new element, you do not }

WORK WITH ARRAYS

CHANGE AN ELEMENT ‹ Type = followed by ADD AN ELEMENT Á Type = followed by the ‡ To add an element with a · Type = followed by the — Display the PHP page ■ The Web browser displays
⁄ To change an element in the value you want to ˇ To add an element to value you want to assign specific index number to an value you want to assign in a Web browser. the results of changing and
an array, type the name of assign to the element. an array, type the name of to the new element. array, type the name of the to the element. adding elements in an array.
the array followed by []. the array followed by []. array followed by [].
› Repeat steps 1 to 3 ‚ Type the code that
¤ Between the brackets, for each element you ° Between the brackets, generates the results of
type the index number of the want to change. type the index number you your changes.
element you want to change. want to assign to the new
element.
62 63
PHP LANGUAGE BASICS 2
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:

USING A FUNCTION function WelcomeMessage()


{
print "Welcome to my Web page!<br>";
Welcome to my Web page!
My name is Martine.
function, sometimes referred to as a subroutine, capitalize the first letter of each word to make the name }

A 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
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
function DisplayIntroduction()
{
WelcomeMessage();
print "My name is Martine.<br>";
example, you may have a function that displays a warning to understand. }
message when a client enters invalid data into a form. DisplayIntroduction();
Instead of retyping the section of code that displays the The block of code used in a function is enclosed in
message for each field in the form, you can simply re-use braces {}. The block of code will not be executed until the
the function. function is called in the script. To call a function, you type When creating a function, you should keep in mind that any
the name of the function followed by a set of parentheses variables created within the function can be accessed only within
Functions also allow you to group lines of code into smaller, where you want to execute the code. that function. The function's variables will not be accessible to
more manageable sections. This makes it easier to other functions or other sections of code in the PHP page.
understand and troubleshoot the code. PHP has many useful built-in functions, such as the print
function. To avoid unnecessary work, you should check RESULT:
TYPE THIS:
A function is created using the function keyword followed whether there is an existing function that suits your needs
by the name of the function and a set of parentheses. A before defining your own function. function SetPageTitle()
{
Welcome to
function name must start with a letter or an underscore (_)
$pageTitle = "Martine's Home Page";
character. The name should identify the purpose of the }
function or describe the action the function performs. function DisplayWelcome()
{
It is common to have a function name begin with a capital print "Welcome to $pageTitle<br>";
letter. If the name consists of multiple words, you can }
DisplayWelcome();

USING A FUNCTION

CREATE A FUNCTION ¤ Type a name for the ‹ Type the code you CALL A FUNCTION ˇ Display the PHP ■ The Web browser
⁄ To create a function, function followed by (). want to execute when the › To call a function, page in a Web browser. displays the result of
type function. function is called. Enclose type the function name the function.
the code in braces. followed by ().
64 65
PHP LANGUAGE BASICS 2
A function can have more than one return In PHP, most built-in functions return a boolean
statement. This is commonly found in functions value. This is useful for helping to prevent your
that use conditional statements. Although a PHP scripts from crashing or generating errors.
function can have more than one return For example, the is_numeric function will
RETURN A VALUE FROM A FUNCTION statement, only one return statement will be
executed. When a return statement is processed,
return a value of true if the argument passed
to the function is a number or a numeric string.
the execution of the function is terminated. Otherwise, the function returns a value of false.

A
lthough a function may simply display a value using need to have a function return multiple values, you should
the print function, it may be more useful to have first place the values in an array and then return the array TYPE THIS: Example:
the function return a value to the code that calls using the return keyword. $x = 8;
the function. A value returned from a function may be the function CheckAge() $y = "Hello";
result of a calculation or procedure or may indicate whether When a function that returns a value is called, the value { if (is_numeric($y) == TRUE)
can be directly displayed to a Web browser using the $age = 19; {
a process was successfully completed. For a function to if ($age >= 18)
return a value, you must include a return statement. print function. It may be more useful, however, to print "Answer: " . $x / $y . ".<br>";
{ }
assign the value returned from a function to a variable return "You may vote.<br>";
A return statement consists of the return keyword that can then be processed further by the PHP script. else
} {
followed by the value you want the function to return and else print "Cannot perform division.<br>";
is usually placed at the end of a function, after the code The return keyword may also be used to simply denote {
the end of a function. This is useful for functions that will }
that performs an operation and generates or calculates return "You may not vote.<br>";
the value to be returned. The execution of a function will not return a value. In such cases, the return keyword is }
terminate once the return statement is processed. used alone and is not followed by any value or variable. }
print CheckAge();
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 RESULT:

You may vote.

RETURN A VALUE FROM A FUNCTION

⁄ Create the function ¤ In the body of the ■ In this example, we ‹ Type the code that › Display the PHP ■ The Web browser
you want to return a function, type return return a variable that calls the function and page in a Web browser. displays the result of
value from. followed by the contains the result of uses the value returned returning a value from
information you want a calculation. from the function. a function.
the function to return.

66 67
PHP LANGUAGE BASICS 2
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
PASS ARGUMENTS TO A FUNCTION variables in the function statement.
When you pass arguments to the function, you do not need
assing arguments to a function you have created can and then send the result back to the code used to call the

P make the function more powerful by allowing you


to use one function throughout a script to process
different data.
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.
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.
In the function statement, you define one or more You can pass one or more arguments to a function, but the
variables between the parentheses that follow the function number of arguments you pass must match the number of TYPE THIS:
name. Each variable represents a value, or argument, you variables you created to store the arguments. An argument function MyMessage ($message, $size = 3)
will pass to the function. Each time you call the function you pass can be a variable or any alphanumeric value, but {
in the PHP page, you will specify the arguments you want the argument must be appropriate for the purpose of the print "<font size=\"$size\">$message</font><br>";
to pass to the function. function. For example, you cannot pass a text value to }
a function if the value will be used in a mathematical
You can use the variables you create in the function calculation. Text values passed to a function must be MyMessage ("Welcome to My Web Site");
statement within the body of the function. The variables MyMessage ("Welcome to My Web Site", 5);
enclosed in quotation marks.
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 RESULT:
function from outside the function. The function can use
the values that are passed to it to perform a calculation Welcome to My Web Site
Welcome to My Web Site
PASS ARGUMENTS TO A FUNCTION

⁄ Create and call the ¤ Between the parentheses ‹ Between the parentheses ■ The number of › Display the PHP page ■ The Web browser
function you want to in the code that creates the in the code that calls the arguments you pass in a Web browser. displays the result of
pass arguments to. function, type the names of the function, type the arguments must match the number passing arguments to
variables you want to store the you want to pass to the of variables you created the function.
arguments that will be passed function. Separate each in step 2.
to the function. Separate each argument with a comma.
variable name with a comma.
68 69
PHP LANGUAGE BASICS 2
PASS ARGUMENTS TO A If you want an argument passed to a function to always Unlike variables, whose scope does not
be passed by reference, you can type an ampersand (&) automatically extend to functions, constants
FUNCTION BY REFERENCE in front of the variable you create to store the argument
in the function statement. This saves you from having
you create in a PHP page are automatically
accessible to the functions you create. This
y default, when an argument you pass to a function To pass an argument to a function by reference, you preface to type an ampersand each time you pass an argument means that you do not need to pass a constant

B 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
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
to the function.
TYPE THIS:
function TimesThree(&$number)
to a function before the constant can be used
in the function. Constants are normally created
at the beginning of a script.
variable in the PHP page. If you want to use a function to by reference, but the number of arguments you pass must
{
change the value of a variable in the PHP page, you must match the number of variables you created to store the $number *= 3; It is considered good programming practice to
pass the variable to the function by reference. Passing an arguments. } create all of your functions near the beginning
argument by reference passes an entire variable to the
When the function is called, the arguments you pass by of a script. This can make your code easier to
function, rather than simply passing the value of the $myNumber = 5;
reference are assigned to the variables you created in the understand and maintain. You can then call the
variable.
function statement. When the variables are modified print "The original number is: $myNumber<br>"; functions wherever you want to execute the
Before you can pass arguments to a function, you must within the function, the values of the arguments they TimesThree($myNumber); code in the PHP page.
create one or more variables between the parentheses contain are also modified. The results of the function are print "The new number is: $myNumber<br>";
that follow the function name in the function statement. then sent back to the code used to call the function.
Each variable represents an argument you will pass to the
function. The variables can then be used in the body of the RESULT:
function, allowing the function to work with the arguments The original number is: 5
that are passed to it. The variables you create in the The new number is: 15
function statement exist only within the function
and are not available outside the function.

PASS ARGUMENTS TO A FUNCTION BY REFERENCE

⁄ Create and call the ¤ Between the parentheses ■ If multiple arguments will ‹ Between the parentheses ■ You can repeat step 3 for › Display the PHP page ■ The Web browser
function you want to pass in the code that creates the be passed to the function, in the code that calls the each argument you want to in a Web browser. displays the result of
arguments to by reference. function, type the name of the type the names of all the function, type an ampersand pass by reference, separating passing an argument
variable you want to store the variables you want to store followed by the name of a each argument with a comma. to the function by
argument that will be passed the arguments. Separate each variable you want to pass to The number of arguments you reference.
to the function. variable name with a comma. the function. pass must match the number
of variables you created in
70 step 2. 71
PHP LANGUAGE BASICS 2
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
UNDERSTANDING VARIABLE SCOPE 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.

T
he scope of a variable determines which parts the variable can be used. Declaring a variable as global
of a script can access the variable and use its The value of a static local variable is retained only for
within a function does not create a new variable, but
value. the duration of the script. Once the script is finished
simply allows the function to access and use the value
processing, the value ceases to exist.
of the variable. Any changes made to a global variable
If you create a variable in the body of a function, the inside a function also affect the value of the variable
value of the variable will only be available in the function. TYPE THIS: RESULT:
outside of the function.
Variables created in a function are referred to as local function Multiply($number)
variables. By default, a function can access only local Variables have a limited lifetime in PHP. The lifetime of {
1 times 2 is: 2
variables. This is an important safety feature in PHP a variable refers to the length of time the value of the static $container = 1; ...times 4 is: 8
because it prevents variables created outside a function variable exists in memory. A variable created in a PHP $container *= $number; ...times 3 is: 24
return $container;
from interfering with variables of the same name created script exists only for the duration of the script. When }
within the function. the script is finished processing, the value of the variable $myNumber = Multiply(2);
ceases to exist. A variable created in a function exists only print "1 times 2 is: $myNumber<br>\n";
To allow a function to use a variable that was created while the function is being executed. The value of a local
outside of the function, you must declare the variable as variable ceases to exist when the function terminates. $myNumber = Multiply(4);
global within the function. To declare a variable as global, print "...times 4 is: $myNumber<br>\n";
you use the keyword global followed by the name of
the variable. The global declaration must be made before $myNumber = Multiply(3);
print "...times 3 is: $myNumber<br>\n";

UNDERSTANDING VARIABLE SCOPE

⁄ Type the code that ¤ Type the code that ‹ To create a local › To declare a variable ˇ Type the code that Á Type the code that ‡ Display the PHP ■ The Web browser
creates a variable and creates a function. variable, type the code as global in the body of uses the local variable calls the function. page in a Web browser. displays the result of
assigns it a value. that creates a variable the function, type global and the global variable. using a local variable
and assigns it a value in followed by the name and a global variable.
the body of the function. of the variable.
72 73
PHP LANGUAGE BASICS 2
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
USING DYNAMIC VARIABLES you want to call the function, you can use the variable name
followed by parentheses instead of the function name.

P
HP allows you to use dynamic variables, which are You first create a string variable that has the same name as TYPE THIS: RESULT:
also referred to as variable variables, in your scripts. the dynamic variable you want to use. The string variable
A dynamic variable is a variable whose name is stored
function FontFour($message) Hello there! How are you?
should contain the name of the variable you want to access. {
in another variable. To create the dynamic variable, you type the variable print "<font size=\"4\">$message</font>";
}
operator ($), followed by the string variable you created. function FontFive($message)
A variable consists of two parts––the variable operator ($) The result is a variable that has two variable operators ($), {
and the name of the variable. A regular variable uses a literal such as $$varName. print "<font size=\"5\">$message</font>";
string as the name of the variable. However, you can create }
a dynamic variable by using the name of an existing string A dynamic variable acts as the equivalent of the original function FontSix($message)
{
variable as the name of the dynamic variable. variable that stores the name of the variable you want to print "<font size=\"6\">$message</font>";
access. You can work with the dynamic variable in the }
Dynamic variables are especially useful for accessing the same way you would work with a regular variable. $size = "Four";
values of a series of variables that you have previously if ($size != "")
created dynamically in your script, such as field names in {
$functionName = "Font" . $size;
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 else
begin with "Field_", you can create a dynamic variable that {
$functionName = "FontSix";
will access all the variables named "Field_" in the form. }
$functionName("Hello there! How are you?");

USING DYNAMIC VARIABLES

⁄ To create a string ¤ Type the value or ‹ To create a dynamic › Type the code that ■ In this example, the ˇ Display the PHP page ■ The Web browser
variable that will contain expression the variable variable, type $ followed uses the dynamic variable. dynamic variable is used in a Web browser. displays the result of
the name of the variable will store, including the by the string variable you in a loop that accesses a using a dynamic variable.
you want to access, type $ name of the variable you created in step 1. series of string variables
followed by a name for the want to access. and displays their values.
variable. Then type =.
■ String values must be
74 enclosed in quotation 75
marks.
PHP LANGUAGE BASICS 2
Type casting is another way to explicitly set the create the variable you want to cast. You then
data type of a variable. You can cast a variable create a second variable to store the data type

WORK WITH DATA TYPES OF VARIABLES to the integer, double, string, boolean,
array or object data type. You must first
you want to use, enclosed in parentheses, and
the first variable.
TYPE THIS:

W
hen creating variables in PHP, you do not have You can use the settype function to force PHP to always
to explicitly declare the type of variable you evaluate a variable using a specific data type. The settype $uncasted = 1.2345;
want to create. The data type of a variable is function takes two arguments––the name of the variable $casted = (integer)$uncasted;
print "Data type of the uncasted variable is: " . gettype($uncasted);
determined by the value assigned to the variable. For whose data type you want to set and the data type you print "<br>";
example, if you assign an integer value to the $number want the variable to use. The data types you can specify print "Data type of the casted variable is: " . gettype($casted);
variable, then $number will use the integer data type. include integer, double, string, boolean, array
This distinguishes PHP from other languages, such as and object. The double data type refers to double-
C++ and Java, which require variables to have assigned precision floating-point numbers. RESULT:
data types.
When you use the settype function, PHP will attempt Data type of the uncasted variable is: double
If you are working with different types of data, PHP will to convert the value of the variable to the specified type. Data type of the casted variable is: integer
automatically perform the required data type conversions. If the conversion is successful, the settype function will
For example, if you add the string "3" to the integer 2, return a value of true. A value of false will be returned
PHP will convert the string to an integer and return the if the conversion was not successful. When a value is When you use a string in a numeric calculation, of the string. If the string begins with anything
integer 5 as the result. When PHP automatically converts converted to a new data type, data may be lost. For PHP examines the beginning of the string. If other than numeric data, the value of the
a value to a new data type, it affects only how the value example, if you convert a floating-point number to an the string begins with valid numeric data, PHP string will be zero (0).
is evaluated. The value of the variable is not changed. integer, the fractional part of the number will be lost. will use the numeric data and truncate the rest
The gettype function allows you to determine the TYPE THIS: RESULT:
current data type of a variable. The gettype function $a = "100 US Dollars"; $a = 100
takes the name of the variable whose data type you print "\$a = " . ($a + 0) . "<br>"; $b = 0
want to determine as its argument.
$b = "US Dollars: 100";
print "\$b = " . ($b + 0);

WORK WITH DATA TYPES OF VARIABLES

⁄ Type the code that creates a ‹ Between the ˇ To set the data type of ‡ Type the data type ° Type the code that uses · Display the PHP page ■ The Web browser
variable and assigns it a value. parentheses, type the name a variable, type settype(). you want to set for the the settype function. in a Web browser. displays the results of
of the variable whose data variable, enclosed in working with the data
¤ To determine the data type type you want to determine. Á Between the parentheses, quotation marks. types of variables.
of a variable, type gettype(). type the name of the variable
› Type the code that uses whose data type you want to
76 the gettype function. set followed by a comma. 77
PHP LANGUAGE BASICS 2
You may use the print_r function to view The var_dump function is used to display
information about a variable you specify in a form information about a variable in an easy-to-read
GET INFORMATION ABOUT A VARIABLE that can be easily read. This function is especially
useful for viewing the contents of arrays and
format and shows the data types of all the
values being displayed. You may want to use
objects. When using the print_r function, you the <pre> tag to format the result of the

T
here are a number of functions you may use to test function is used to test whether a variable is an object. You may want to use the <pre> tag to format the result. var_dump function.
whether a variable stores data of a certain type. use the is_resource function to check if a variable is an
Testing the value of data stored in a variable is useful integer that represents a system resource, such as an open TYPE THIS: TYPE THIS:
before using a variable in a calculation. If you attempt a file or an open database connection. $info = array ("Tom", 24, 65.5); $info = array ("Tom", 24, 65.5);
calculation with the wrong type of variable, an error may print "<pre>"; print "<pre>";
occur. The functions that test the type of a variable return a value print_r($info); var_dump($info);
of true if the value stored in the variable is of the indicated print "</pre>"; print "</pre>";
The is_int, is_integer, and is_long functions are type, otherwise, the functions return a value of false.
used to verify if a variable stores an integer. You use the
is_float, is_real and is_double functions to check There are other useful functions you may use to get
RESULT: RESULT:
whether a variable stores a floating-point number. The information about a variable, such as whether a variable
has been assigned a value or whether a variable holds a Array array(3) {
is_numeric function is used to test if a variable stores ( [0]=>
a number or a numeric string. zero (0) value. The isset function returns a value of true
[0] => Tom string(3) "Tom"
if a value has been assigned to a variable. The empty [1] => 24 [1]=>
The is_bool function is used to determine if a variable function returns a value of false if a variable contains a [2] => 65.5 int(24)
is a boolean. To check if a variable stores a string, you use non-zero or non-empty value. ) [2]=>
the is_string function. The is_array function is used float(65.5)
to test if a variable stores an array, and the is_object }

GET INFORMATION ABOUT A VARIABLE

⁄ Type the code that ‹ Between the parentheses, ˇ To check if a value has ‡ Type the code that ° To check if a variable ‚ Type the code that — Display the PHP page ■ The Web browser
creates variables and type the name of the variable been assigned to a variable, uses the isset function. stores an empty or 0 value, uses the empty function. in a Web browser. displays the results of
assigns their values. you want to check. type isset(). type empty(). retrieving information
about the variables.
¤ To check if a variable › Type the code that uses Á Between the parentheses, · Between the parentheses,
stores a value of a specific the function. type the name of the variable type the name of the variable
type, type the function you you want to check. you want to check.
want to use followed by ().

78 79
PHP LANGUAGE BASICS 2

ACCESS SYSTEM CONSTANTS Common PHP System Constants

CONSTANT: DESCRIPTION:
_ _FILE_ _ Returns the filename of the script being processed.

P
HP comes with several built-in system constants so PHP cannot determine when a constant is being used
that you can use in your scripts. A constant is a in a string. To ensure that a constant is evaluated correctly _ _LINE_ _ Returns the number of the line being processed in the script.
name that represents a value that does not change. in a string, you must separate the constant from the rest PHP_VERSION Returns the version number of PHP being used.
Because PHP sets the value of a system constant, these of the string.
constants do not have to be declared and can be used PHP_OS Returns the name of the operating system running PHP.
in every script you create. You should use all uppercase letters when specifying the TRUE Stores a value of true.
name of a system constant. The constants TRUE and FALSE,
You can also create your own constants. This allows you however, are also commonly referenced using all lowercase FALSE Stores a value of false.
to set the value of the constant. For information about letters. TRUE and FALSE are the most frequently used E_ERROR Indicates a fatal error that is not related to parsing.
defining and using constants, see page 44. system constants. You can test the values of the TRUE E_WARNING Indicates that an error has occurred, but PHP will continue processing
or FALSE system constant by assigning the constant to the script.
System constants are usually used to store information a variable and using the variable in an if statement.
about the environment in which a PHP script is running. E_PARSE Indicates a fatal parsing error caused by invalid syntax in the script.
For example, the PHP_VERSION constant stores the version You cannot modify the value of a PHP system constant. E_NOTICE Indicates that an error may have occurred, but PHP will continue
of PHP being used on the computer and the _ _FILE_ _ You also cannot use the name of a system constant as the processing the script.
constant stores the filename of the script being processed. name or value of a constant you create. If you attempt
E_ALL Represents all the E_* constants. If used with the error_reporting
to do either of these tasks in your script, the script will
To access the value of a system constant in a PHP page, function, all problems noticed by PHP will be reported.
generate an error.
you specify the name of the constant in the PHP code. NULL Represents no value.
Unlike variables, constants do not start with a dollar symbol,

ACCESS SYSTEM CONSTANTS

⁄ To access the value of ¤ Type the code that ‹ Repeat steps 1 and 2 › To test the value of a ˇ Type the code that Á Display the PHP page ■ The Web browser
a system constant, type uses the value of the for each system constant system constant, type the uses the value of the in a Web browser. displays the result of
the name of the constant. constant. you want to access. code that assigns the value constant. accessing the values
of the constant to a variable. of system constants.

80 81
PHP LANGUAGE BASICS 2
INCLUDE A FILE
T
he require and include statements allow you to enclosed in quotation marks. The contents of the required
use one file in several different PHP pages. This can or included file can then be used in your script. Using the require and include Some files should be included only once when
save you time when you need to include the same statements allows you to break code into a script is processed. For example, if a file with
information in multiple pages. For example, if you have a The require and include statements differ mainly in manageable sections and then include the a function declaration has been included multiple
copyright notice you want to display on all your PHP pages, the way PHP processes each statement. code in PHP pages as needed. For example, times, an error will occur after the require or
you can create a file that contains the copyright notice and When a script is processed, PHP replaces instances of you can organize constants and functions include statement is processed the first time,
then use a require or include statement to include the the require statement with the contents of the file to be you create into include files that you can because a function can be declared only once
information on all your pages. If you change the code in the included, even if the line containing the require statement then insert into your PHP pages. You can in a script. To ensure that a file is included only
file, all the PHP pages that include the file will be updated. is never executed. Unlike the require statement, the also nest include files within other include once, you can use the require_once or
include statement is processed only when the statement files. This is especially useful for complex include_once statement when you include the
You must first create the file you want to include. The PHP pages that contain long sections of file in a PHP page. After the file has been included
file can contain plain text or HTML code, such as a table, is executed and returns a boolean value of true or false,
depending on whether the statement is executed correctly. code. once, PHP will ignore any new statements that
header or footer. The file can also contain PHP code include the file.
enclosed within the PHP delimiters (<?php and ?>), If you want to include a file based on a condition being
such as variables or functions. You can save the file with true, you should use an include statement instead of Example:
the .inc extension on the Web server. a require statement. <?php
require_once("hello.inc");
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

INCLUDE A FILE

CREATE A FILE TO INCLUDE ¤ Save the file on the INCLUDE A FILE ¤ Type include() or ‹ Between the parentheses, › Display the PHP page ■ The Web browser
⁄ In a text editor, create Web server. ⁄ Display the code for require() where you type the name of the file you in a Web browser. displays the result of
a file you want to include the PHP page in which want to include a file. want to include, enclosed in including a file.
in several PHP pages. you want to include a file. quotation marks.

82 83
PHP WORK WITH ARRAYS 3
You can use the foreach statement to work To change the value of an element in an
with each key-value pair in an associative associative array, you specify the name of
CREATE AN ASSOCIATIVE ARRAY array. You specify another variable to hold the
value of each key after the as keyword in the
the array followed by the key of the element
you want to change. You can then use the
ou can create an associative array, which allows meaningful keys. Arrays containing many elements with very foreach statement. This variable is followed assignment operator (=) to assign a new

Y 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.
long keys require more memory, which makes the script less
efficient.
To access an element in an associative array, you specify the
by the => operator and the variable that will
hold the value of each element.
TYPE THIS:
value.
Example:
$user = array ("name" => "Tom",
"age" => 24,
Creating an associative array is similar to creating a simple name of the array followed by the key enclosed in brackets, $user = array ("name" => "Tom", "gender" => "male");
array. You create a variable to store the array and then use such as $user[name]. If the key contains spaces, it must be "age" => 24, $user[age] = 29;
the array keyword to assign the elements. When assigning enclosed in quotation marks, such as $user["last name"]. "gender" => "male");
an element to an associative array, however, you must first foreach ($user as $key => $value)
type the key. The key is enclosed in quotation marks and You should not access an element with a key that is {
should describe its associated value in the array. The key is enclosed in quotation marks within another string, such as print "$key: $value<br>"; You can later add an element to an
print "Welcome $user["first name"]", since an error will be } associative array. To do so, you specify the
followed by the => operator and the value of the element.
Each key-value pair in an associative array is separated by generated. In such cases, it is better to access the element name of the array followed by the key of
a comma. outside the string and use the concatenation operator (.) to the new element. You can then assign the
combine the strings, such as print "Welcome " . $user["first RESULT: new value.
It is good programming practice to avoid using spaces and name"].
non-alphanumeric characters, such as ? and &, in the keys name: Tom Example:
of an associative array. You should also try to use short but age: 24 $user[status] = "single";
gender: male

CREATE AN ASSOCIATIVE ARRAY

⁄ Type a name for the ¤ To add an element to the ‹ Repeat step 2 for each ˇ Between the brackets, Á Type the code that ‡ Repeat steps 4 to 6 ° Display the PHP page ■ The Web browser
associative array you array, type a key followed by => element you want to add to the type the key of the element uses the element in for each element you in a Web browser. displays the result of
want to create followed and the value you want to assign associative array. Separate each you want to access. the associative array. want to access. accessing elements in
by = array (). to the element. key-value pair with a comma. an associative array.
■ The key and any string values › To access an element in the
must be enclosed in quotation associative array, type the name
84 marks. of the array followed by []. 85
PHP WORK WITH ARRAYS 3
You can neatly display the elements of a multidimensional array in a table
created using HTML. To access all the elements in the multidimensional
CREATE A MULTIDIMENSIONAL ARRAY 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.
multidimensional array is useful for organizing data the first set of brackets. The index of the element within

A 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
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
TYPE THIS:
$users = array (
array ("name" => "Tom", "age" => 24, "gender" => "male"),
RESULT:

or more arrays as elements of another array. element in the second array of a two-dimensional array, array ("name" => "Martine", "age" => 19, "gender" => "female"),
you would type $values[1][2]. array ("name" => "Jason", "age" => 40, "gender" => "male")
When creating a multidimensional array, you should make );
the array symmetrical by ensuring that each array in the Accessing an element of a multidimensional array within a print "<table border=\"1\">\n";
multidimensional array has the same number of elements. string, such as print "Name: $values[2][0]", may not give the print "<tr>\n";
print "<th>#</th>\n";
You can use simple arrays, associative arrays or both types correct result. To avoid problems, you should use braces {} print "<th>Name</th>\n";
as elements of a multidimensional array. when accessing an element of a multidimensional array print "<th>Age</th>\n";
within a string, such as print "Name: {$values[2][0]}". You print "<th>Gender</th>\n";
To access an element in a multidimensional array, you need may want to access the element outside the string and use print "</tr>\n";
to specify the name of the array followed by a set of brackets the concatenation operator (.) to combine the strings foreach ($users as $number => $user)
for each dimension of the array. For example, accessing an {
instead, such as print "Name: " . $values[2][0]. print "<tr><td>$number</td>";
element in a two-dimensional array will require two sets of foreach ($user as $value)
brackets. {
print "<td>$value</td>";
You then specify the indexes of the element you want to }
access in the multidimensional array within the brackets. print "</tr>";
The index of the array you want to access is specified in }
print "</table>";

CREATE A MULTIDIMENSIONAL ARRAY

⁄ Type a name for the ‹ Repeat step 2 for each › To access an element in the Á Between the second ‡ Type the code that ° Repeat steps 4 to 7 · Display the PHP page ■ The Web browser
multidimensional array array you want to assign multidimensional array, type set of brackets, type uses the element in the for each element you in a Web browser. displays the results of
followed by = array (). to the multidimensional the name of the array followed the index or key of the multidimensional array. want to access. accessing elements in a
array. Separate each array by a set of brackets for each element you want to multidimensional array.
¤ To assign an array as an with a comma. dimension in the array. access.
element of a multidimensional
array, type array followed by the Note: In this example, a ˇ Between the first set of ■ If necessary, specify
values or key-value pairs for the two-dimensional array is brackets, type the index of additional indexes or
array enclosed in parentheses. created. the array you want to access. keys within brackets.
86 87
PHP WORK WITH ARRAYS 3
You can create a function that advances the array pointer a specified

MOVE THROUGH ARRAY ELEMENTS 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
ou may access the elements in an array by navigating Once you have set the pointer to the element you want to to advance the pointer. You can also create a function that uses the

Y 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
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
prev function to set the pointer back a specified number of times.
Example:
function AdvancePointer(&$array, $number)
elements that have non-sequential indexes or keys. When key, or index, of the current element, while the current {
an array is created, the pointer is set to the first element function returns the value of the current element. for ($counter = 0; $counter < $number; $counter++)
of the array. You can then move the pointer forward or {
back to an element you want to access. If the internal array pointer is advanced beyond the last next($array);
element in the array or is moved back beyond the first }
The internal array pointer is moved using the next, element, the position of the pointer will be lost. You will }
prev, end and reset functions. The next function not be able to recover the pointer using the next or prev function MoveBackPointer(&$array, $number)
is used to advance the pointer to the next element in functions. To restore the pointer, you must use the reset {
an array. The prev function sets the pointer back to the or end function. for ($counter = 0; $counter < $number; $counter++)
{
previous element. The end function sets the pointer to prev($array);
the last element in an array, while the reset function }
sets the pointer back to the first element in the array. }
$fruits = array ("apple", "avocado", "banana", "grapefruit", "melon");
The next, prev, end and reset functions take the AdvancePointer($fruits, 3);
array you want to move through as an argument and print "Key: " . key($fruits) . ", Value: " . current($fruits) . "<br>";
return the value of the element to which the pointer MoveBackPointer($fruits, 2);
is set. print "Key: " . key($fruits) . ", Value: " . current($fruits) . "<br>";

MOVE THROUGH ARRAY ELEMENTS

⁄ Type the code that ¤ To move through the ‹ To access the index of ˇ Type the code that Á Repeat steps 2 to 5 ‡ Display the PHP page ■ The Web browser displays
creates an array. elements in the array, type the current element, type key uses the index and value for each element you in a Web browser. the result of moving through
the name of the function followed by the name of the of the current element. want to move to and the array elements.
you want to use (next, prev, array enclosed in parentheses. access in the array.
end or reset) followed by the
name of the array enclosed › To access the value of the
in parentheses. current element, type current
followed by the name of the
88 array enclosed in parentheses. 89
PHP WORK WITH ARRAYS 3
When working with arrays in PHP, it is important to You can use the assignment operator (=) to
remember that the position of an element in an array add elements to the end of an array instead
ADD AND REMOVE ELEMENTS IN AN ARRAY does not necessarily correspond to the index number
of the element. The positions of array elements are
of using the array_push function. This is
useful when you want to add only a single
determined by the order in which the elements are element to the end of an array.

P
HP provides several functions that allow you to To remove an element from the beginning of an array, assigned to the array, especially in cases where the
modify an array by adding and removing elements use the array_shift function. The array_pop function Example:
indexes of the elements are set explicitly. For example,
in the array. allows you to remove an element from the end of an array. using the array_pop function will remove the $fruits = array("apple", "grape", "melon");
You can remove only one element from an array at a time $fruits[] = "orange";
To add an element to the beginning of an array, use the element that was set last in the array, not the element foreach($fruits as $value)
using the array_shift or array_pop function. These with the highest index number.
array_unshift function. Use the array_push function functions will return the value of the removed element.
{
to add an element to the end of an array. When using the print "$value ";
Example: }
array_unshift and array_push functions, you must When you use the array_unshift or array_shift $fruits = array();
specify the name of the array you want to modify followed function to add or remove an element from the beginning $fruits[3] = "apple"; Result:
by the value for the element you want to add. In addition of an array, the other elements will shift to accommodate $fruits[2] = "grape";
to individual elements, the array_unshift and the new element. The keys of numerically indexed $fruits[1] = "melon"; apple grape melon orange
array_push functions also accept lists of values. This elements in the array will be re-indexed starting from $fruits[0] = "orange";
allows you to add multiple elements to the beginning or array_pop($fruits);
zero (0). Using the array_push or array_pop foreach($fruits as $value)
end of an array. To add more than one element, you type functions to add or remove an element from the end {
the value for each element, separating each value with of an array will not affect the indexing of the other print "$value ";
a comma. The array_unshift and array_push elements. }
functions will return the number of elements in the
modified array. Result:
apple grape melon

ADD AND REMOVE ELEMENTS IN AN ARRAY

ADD AN ELEMENT ¤ To add an element to ‹ Between the parentheses, ■ String values must be REMOVE AN ELEMENT ‡ Between the parentheses, · Display the PHP page ■ The Web browser
⁄ Type the code that the beginning of the array, type the name of the array enclosed in quotation Á To remove the last type the name of the array in a Web browser. displays the results of
creates an array. type array_unshift(). to which you want to add an marks. element in the array, from which you want to adding and removing
element followed by a comma. remove an element. elements in an array.
■ To add an element to ˇ Type the code that type array_pop().
the end of the array, type › Type the value for the uses the array. ■ To remove the first ° Type the code that uses
array_push(). element you want to add element in the array, the array.
to the array. type array_shift().
90 91
PHP WORK WITH ARRAYS 3
You can use a negative offset number to specify the position of
the first element you want to replace. When a negative number
REPLACE ELEMENTS IN AN ARRAY is used, the array_splice function finds the position of the
elements from the end of the array, starting at 1.

T
he array_splice function allows you to You can then indicate the new elements you want TYPE THIS: RESULT:
replace existing elements in an array with to assign to the array. The array_splice function $fruits = array("apple", "avocado", "banana", "grapefruit", "melon");
new elements. allows you to replace elements in an array with an apple avocado banana peach
array_splice($fruits, -2, 2, "peach");
array of elements or a single element. If new elements foreach($fruits as $value)
To use the array_splice function, you must specify are not specified, the elements selected for replacement {
the name of the array you want to change and the in the array will simply be removed. print "$value ";
offset number of the first element you want to replace. }
The offset number corresponds to the position of the The array_splice function can also be used to add
element in the array, but is not necessarily the index new elements to the end of an array. To add elements
number of the element. The offset number will be the to the end of an array, specify an offset number that If you want to work with only some of the elements in an array,
same as the index number of the element only if the is greater than the highest index number in the array you can extract the elements you want without modifying the
array is indexed in consecutive order starting from and use a length parameter of zero (0). array. To extract elements from an array, use the array_slice
zero (0). function instead of the array_splice function.
When you use the array_splice function to replace
You should also specify a length parameter to indicate or add elements in an array, the keys of numerically TYPE THIS: RESULT:
the number of elements you want to replace in the indexed elements in the array will be re-indexed $fruits = array("apple", "avocado", "banana", "grapefruit", "melon"); avocados bananas grapefruits
array. You can replace one or more elements. If you starting from zero (0). $extracted = array_slice($fruits, 1, 3);
do not specify a length parameter, PHP will replace foreach($extracted as $value)
the element represented by the offset number, When the array_splice function is executed, {
followed by each element to the end of the array. an array containing the replaced array elements is print "$value"."s ";
returned. }

REPLACE ELEMENTS IN AN ARRAY

⁄ Type the code that creates ‹ To replace elements in › Between the parentheses, Á Type the number of ‡ To specify the ■ To replace the array elements · Display the PHP page ■ The Web browser
an array. an array, type array_splice(). type the name of the array that elements you want to elements you want to with just one element, you in a Web browser. displays the result of
contains elements you want to replace followed by a assign to the array, type can type the value for the new replacing elements in
¤ To replace elements in replace followed by a comma. comma. the name of the array element. A string value must be an array.
the array with more than one that contains the new enclosed in quotation marks.
new element, type the code ˇ Type the offset number of elements.
that creates an array that the first element you want to ° Type the code that uses
contains the new elements. replace followed by a comma. the array.

92 93
PHP WORK WITH ARRAYS 3
When PHP sorts strings, values beginning You can arrange the elements in an array in random
with uppercase characters are grouped order. To arrange array elements in random order,
SORT A SIMPLE ARRAY together first, followed by values beginning
with lowercase characters. Using the same
you use the shuffle function. Before using the
shuffle function, you must call the srand function
case for all the array elements will ensure to initialize PHP's random number generator.

T
he sort function allows you to sort a simple array as numbers, you can use the SORT_NUMERIC value. that they are sorted in the correct order.
and place the elements in order from lowest to If you specify the SORT_STRING value, the elements You can use the strtolower function to TYPE THIS:
highest. For example, you could sort an array of will be evaluated as strings. convert the values in an array to all lowercase srand((double) microtime() * 1000000);
numbers into ascending order or sort an array of strings characters before performing a sort. $numbers = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
into alphabetical order. Specifying a sort type argument is useful when you want
shuffle($numbers);
to force PHP to evaluate array elements in a specific way. foreach($numbers as $value)
TYPE THIS:
The sort function takes the name of the array you want to For example, PHP would normally sort an array containing {
sort as its argument. When you sort an array using the sort the numbers 1, 2 and 10 as 1 10 2. To ensure that the $fruits = array("Orange", "apple", "Banana", print "$value ";
function, the keys for numerically indexed elements will be numbers are sorted in correct ascending order, you should "mango", "Grape"); }
foreach($fruits as $key => $value)
re-indexed starting from zero (0). This makes the sort use the SORT_NUMERIC value. {
function unsuitable for sorting an associative array. For $fruits[$key] = strtolower($value);
information about sorting associative arrays, see page 96. The sort function will return a value of true or false
} RESULT:
depending on whether the sort was executed successfully. sort($fruits);
PHP allows you to use an optional second argument with foreach($fruits as $value) 1 2 3 7 0 4 5 6 8 10 9
the sort function to specify how the data values should To sort an array in reverse order, from the highest to the
{
be treated. The SORT_REGULAR value specifies that PHP lowest value, you use the rsort function. The rsort print "$value ";
should evaluate the array elements based on their ASCII function has the same properties and takes the same }
values. By default, PHP will use the SORT_REGULAR value arguments as the sort function.
when sorting an array, unless another sort type is specified.
To specify that you want the array elements to be evaluated RESULT:
apple banana grape mango orange

SORT A SIMPLE ARRAY

⁄ Type the code that creates › To specify the way Á Display the PHP ■ The Web browser SORT AN ARRAY IN REVERSE ORDER › To specify the way you Á Display the PHP ■ The Web browser
an array. you want PHP to evaluate page in a Web browser. displays the results ⁄ Type the code that creates an want PHP to evaluate the page in a Web browser. displays the results of
the elements, type a of sorting the values array. elements, type a comma sorting the values in an
¤ To sort the array, type sort(). comma followed by a in an array. followed by a sort value. array in reverse order.
‹ Between the parentheses, sort value. ¤ To sort the array in reverse
order, type rsort(). ˇ Type the code that
type the name of the array ˇ Type the code that uses the array.
you want to sort. uses the array. ‹ Between the parentheses,
type the name of the array you
94 want to sort in reverse order. 95
PHP WORK WITH ARRAYS 3
The natsort function sorts alphanumeric values The natcasesort function also uses the
using a method called natural ordering, which is natural ordering method to sort values, but
based on how a person would naturally order items. it sorts values in a case-insensitive manner.
The natsort function is based on Martin Pool's Similar to the other functions used to sort
SORT AN ASSOCIATIVE ARRAY Natural Order String Comparison algorithm. You can
find more information about natural ordering at the
associative arrays, the natcasesort
function maintains the relationship between
www.linuxcare.com.au/projects/natsort Web site. The the key and value of the array elements.

T
he asort function is used to sort an associative The asort and ksort functions take the associative array natsort function can be used to sort both simple
array so that the relationship between the key and you want to sort as an argument and will return a value of and associative arrays.
value of the array elements are preserved during true or false depending on whether the sort was executed The arsort function is used to sort the values
the sorting process. When the asort function is used, successfully. TYPE THIS:
of an associative array from highest to lowest.
the values of an associative array are sorted from lowest To sort an associative array based on keys
to highest. Using the asort function to sort the values in PHP allows you to use an optional second argument with $images = array ("img100.gif", "img12.gif", from highest to lowest, the krsort function
the asort and ksort functions to specify how the data "img10.gif", "img2.gif",
an associative array ensures that the array elements will is used. The arsort and krsort functions
values should be treated. The SORT_REGULAR value "img1.gif", "img20.gif");
not be re-indexed starting from 0, which would cause the natsort($images); take the associative array you want to sort as
original keys to be lost. specifies that PHP should evaluate the array elements foreach ($images as $value) an argument. You can also specify the sort type
based on their ASCII values. By default, PHP will use { you wish to use to evaluate the values or keys.
You may also sort an associative array based on the keys the SORT_REGULAR value when sorting an array, unless print "$value &nbsp";
of the array elements rather than the values using the another sort type is specified. To specify that you want }
ksort function. When the ksort function is used, the array elements to be evaluated as numbers, you
the keys will be sorted from lowest to highest while can use the SORT_NUMERIC value. If you specify the
maintaining the relationship between the key and value SORT_STRING value, the elements will be evaluated RESULT:
of the array elements. as strings.
img1.gif img2.gif img10.gif img12.gif img20.gif
img100.gif

SORT AN ASSOCIATIVE ARRAY

SORT BY VALUE ‹ Between the parentheses, Á Display the PHP ■ The Web browser SORT BY KEY ‹ Between the parentheses, Á Display the PHP page ■ The Web browser
⁄ Type the code that type the name of the array page in a Web browser. displays the result of ⁄ Type the code that type the name of the array in a Web browser. displays the result of
creates an associative array. you want to sort. sorting an associative creates an associative array. you want to sort. sorting an associative
array by the value of array by the key of each
¤ To sort the array › To specify the way you each element. ¤ To sort the array › To specify the way you element.
according to the value of want PHP to evaluate the according to the value of want PHP to evaluate the
each element, type asort(). values, type a comma each element, type ksort(). keys, type a comma followed
followed by a sort value. by a sort value.
ˇ Type the code that ˇ Type the code that uses
96 uses the array. the array. 97
PHP WORK WITH ARRAYS 3
The code in the comparison function may contain more than
one conditional structure, depending on how the two values are
SORT AN ARRAY USING being compared. For example, in a comparison function used
to compare two numbers, the code may initially compare the

COMPARISON FUNCTIONS 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.
ou can create a function that compares values in an using the usort function, the array you want to sort is

Y 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
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
TYPE THIS:
function OddEven($firstValue, $secondValue)
{
$firstRem = $firstValue % 2;
RESULT:

3 5 9 69 93 101 14 18 28 58 80
needs before defining your own function. based on the order determined by the comparison function.
When an array is sorted using the usort function, the array $secondRem = $secondValue % 2;
A comparison function takes two arguments representing elements are re-indexed starting from zero (0).
if (($firstRem == 1) && ($secondRem == 0)) return -1;
two adjacent values in an array. The function compares the else if (($firstRem == 0) && ($secondRem == 1)) return 1;
two values and returns a value of -1, 1 or 0. A value of -1 To maintain the association between the key and value of else
{
indicates that the first value will appear first in the sorted the array elements, such as when sorting an associative if ($firstValue < $secondValue) return -1;
array. A value of 1 indicates that the second value will appear array, you should use the uasort or uksort function else if ($firstValue > $secondValue) return 1;
first in the sorted array. If the function returns a value of 0, instead of the usort function. The uasort function else return 0;
the two values are treated equally in the sort order. sorts an array based on the value of the array elements. }
The uksort function sorts an array based on the key of }
The code in the body of a comparison function typically the array elements. The uasort and uksort functions $numbers = array(18, 5, 9, 3, 69, 101, 58, 93, 14, 80, 28);
contains a conditional structure, which is used to compare take the same arguments as the usort function.
usort($numbers, "OddEven");
the two values and determine the value to be returned. foreach ($numbers as $value)
{
Once the comparison function has been defined, you can print "$value ";
use the usort function to sort the values in an array. When }

SORT AN ARRAY USING COMPARISON FUNCTIONS

⁄ To create a comparison ¤ Between the parentheses, ‹ In the body of the ■ In this example, the ˇ Type the name of the Á Between the parentheses, ° Display the PHP page ■ The Web browser
function, type function type the name of two function, type the code that comparison function function you want to use type the name of the array in a Web browser. displays the result of using
followed by a name for variables that represent two compares the two values compares the length of to sort the array (usort, followed by a comma. Then a user-defined comparison
the comparison function adjacent values in an array, and returns a value of -1, two string values and uasort or uksort) followed type name of the comparison function to sort an array.
and (). separated by a comma. 1 or 0, depending on the places the string with by (). function enclosed in quotation
result of the comparison. the shorter length first. marks.
› Type the code that ‡ Type the code that uses
98 creates an array. the sorted array. 99
PHP WORK WITH ARRAYS 3
GET INFORMATION ABOUT AN ARRAY You can use the array_rand function to retrieve random The array_unique function can be used

T
here are several functions available that array_reverse function, the elements in the resulting entries from an array. Before using the array_rand to remove duplicate values from an array
you can use to find information about an array are re-indexed starting from 0. function, you need to use the srand function to initialize by returning an array containing only the
array. PHP's random number generator. When using the unique values. This function is useful for
The array_flip function is used to switch the keys and array_rand function, you must specify the array that removing redundant values that have been
The array_count_values function is used to count values in an array. The array_flip function returns an contains the elements you want to select from. You may inadvertently added to an array.
the number of times a value occurs in an array. This array in which the keys are the values from the initial also specify the number of elements you want to choose.
function returns an array in which each key represents a array and the values are the corresponding keys from the TYPE THIS:
unique value in the initial array. The value associated with initial array. TYPE THIS: $fruits = array ("apple", "banana", "apple",
a key indicates the number of times the value occurred in "banana", "orange");
the initial array. This is useful for calculating subtotals in These functions all take the array you want to work with srand((double)microtime() * 10000000);
$unique = array_unique($fruits);
an array. as an argument. The result of each function is typically $numbers = array ("one", "two", "three", "four",
foreach ($unique as $value)
assigned to a variable that can then be displayed on a "five", "six", "seven", "eight", "nine");
$pickThree = array_rand($numbers, 3); {
The array_sum function is used to calculate the sum of Web browser or further processed. print "$value ";
foreach ($pickThree as $value)
all the values in an array and is typically used on an array { }
of numeric values. The array_sum function returns the The in_array function is also used to find information
about an array. This function allows you to find a specific print "$numbers[$value] ";
sum as an integer or a floating-point number. }
value in an array. The in_array function takes two
You can use the array_keys function to obtain all the RESULT:
arguments––the value you are looking for and the array
keys in an array. The array_keys function returns an to be searched. The in_array function will return a apple banana orange
RESULT:
array containing all the keys. value of true if the specified value is found.
four nine seven
The array_reverse function is used to reverse the
order of the elements in an array. When using the

GET INFORMATION ABOUT AN ARRAY

⁄ Type the code that ■ You can use the ‹ Between the parentheses, › Type the code that USING THE in_array FUNCTION ‡ Type a comma followed · Display the PHP page ■ The Web browser
creates an array. array_count_values, type the name of the array uses the result of the ˇ To determine if a value by the name of the array in a Web browser. displays the results of
array_sum, array_keys, you want to use. function. is found in an array, type you want to search. obtaining information
¤ Type the function array_reverse or about an array.
you want to use to find in_array(). ° Type the code that uses
array_flip function.
information about the Á Between the parentheses, the result of in_array
array followed by (). type the value you want to find, function.
enclosed in quotation marks.
100 101
PHP WORK WITH ARRAYS 3
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,
USING THE LIST STATEMENT is required to access the key and value of each element in an array.

TYPE THIS: RESULT:

P
HP allows you to use the list statement to assign you do not need to assign all the elements to variables.
the values in an array to a list of variables. Using the Instead, you can leave the spaces for the first two elements $user = array("Name" => "Frank", "Age" => "33", "Gender" => "male"); Name: Frank
while (list($key, $value) = each($user)) Age: 33
list statement can make your arrays easier to work empty and specify a variable name for only the third {
with and is especially useful when working with functions element, such as list(, , $day). print "$key: $value<br>\n";
Gender: male
that return an array. Instead of referencing an array element }
by its numeric key, you can assign the element to a variable When using the list statement, you should use only
with a meaningful name. When you want to use the arrays with numerically indexed elements starting from
element, you can use the variable name to access the zero (0). The order of the variables you specify in the
list statement should correspond to the index numbers You can use the next, prev, end and reset functions to move
element. This can also make your code easier to read through the elements in an array. This allows you to move the
and understand. of the values, not the positions of the values in the array.
internal array pointer to a specific element you want to access
The list statement takes as its arguments the names of The list statement cannot access values in an array in an array. You can then use the each function with the list
the variables to which you want to assign the values in an with an associative index. You also cannot use the list statement to assign the value of the element to a variable.
array, separated by commas. You can assign all, some or statement to assign a value that is not part of an array
just one of the values in an array to a variable. For example, to a variable. TYPE THIS: RESULT:
if you want to retrieve only the third element in an array, $user = array("Name" => "Frank", "Age" => "33", "Gender" => "male"); male
next($user);
next($user);
list(, $gender) = each($user);
print "$gender";

USING THE LIST STATEMENT

⁄ Type the code that ¤ To assign the values in the ‹ Between the parentheses for the ■ If you do not want › Type the code that ˇ Display the PHP page ■ The Web browser displays
creates a function that array to a list of variables, type list function, type the name of to assign a value to a uses the variables. in a Web browser. the result of using the list
returns an array. list(). Then type = followed by each variable to which you want to variable, leave a blank statement to assign array
the name of the function that assign a value in the array. Separate space for the value. elements to variables.
returns the array. each variable name with a comma.

102 103
PHP WORK WITH STRINGS 4
CHANGE CASE OF A CHARACTER OR STRING USING ASCII VALUES
P A
HP provides functions that allow you to change the Each function takes the name of the variable that stores the SCII (American Standard Code for Information you can join characters returned by the chr function
case of text in a string. For example, you can use string you want to change as its argument. If the string has Interchange) is a numbering system that assigns together using the concatenation operator (.). Converting
the strtolower function to change all the text in not been assigned to a variable, you can use the string, numerical values to letters, numbers and other ASCII values to characters in a PHP page is useful for
a string to lowercase. To change all the text in a string to enclosed in quotation marks, as the argument. characters. Many programs save, read and exchange data including characters in your PHP page that do not appear
uppercase, use the strtoupper function. Changing all using the ASCII numbering system. Using the ord and chr on your keyboard, such as mathematical symbols.
the text in a string to the same case can make the text The strtolower, strtoupper, ucfirst and ucwords functions allows you to convert between ASCII values and
easier to search and manage. functions can be used together to apply the results of one characters. The standard ASCII characters are numbered from 0 to
case function to another case function. This lets you change 127. When using the extended ASCII character set, the
The ucfirst function allows you to change the first the case of a string in more than one way. For example, The ord function converts a specified character to an ASCII characters are numbered up to 255. You can visit the
character in a string to uppercase. PHP will apply the using the ucwords function will have no apparent effect if value. If multiple characters are specified, the ord function www.asciitable.com Web site to view a complete chart
ucfirst function to the first character in a string, even the string contains all uppercase characters. To ensure that will return the ASCII value of only the first character. You of the extended ASCII character set.
if the first character is not a letter. For example, if the only the first letter of every word is uppercase in the string, may find that you need to convert characters to their ASCII
first character in a string is a number, the string will not you can first apply the strtolower function and then values in order to format and manipulate data. For example, All characters on a computer, including non-displayable
display any changes. apply the ucwords function to the string, such as if you use a PHP page to write data to a file, you may need characters and whitespace characters, such as the tab
ucwords(strtolower($changeCase)). to convert formatting characters such as horizontal tabs to and newline characters, have an ASCII value. To convert a
Use the ucwords function to change the first character their ASCII values before you can write the characters to non-displayable or whitespace character to an ASCII value,
of each word in a string to uppercase. PHP will consider the file. you must provide the escape sequence for the character.
any character or group of characters that directly follows For a list of commonly used escape sequences, see the
a whitespace character, such as a space or carriage return, The chr function converts a specified ASCII value to a top of page 42.
to be a word. For more information about whitespace character. PHP allows you to manipulate the results of the
characters, see page 112. chr function as you would manipulate strings. For example,

CHANGE CASE OF A CHARACTER OR STRING USING ASCII VALUES

⁄ Type the code that creates a ‹ Between the ˇ Display the PHP ■ The Web browser ⁄ To convert a character to ‹ To convert an ASCII value Á Display the PHP ■ The Web browser
variable containing the string you parentheses, type the page in a Web browser. displays the result of an ASCII value, type ord(). to a character, type chr(). page in a Web browser. displays the results of
want to change. name of the variable changing the case of using the ord and chr
that stores the string. characters in a string. ¤ Between the parentheses, › Between the parentheses, functions.
¤ Type the name of the function type the character you want type the ASCII value you
you want to use to change the › Type the code that to convert enclosed in want to convert.
case of characters in the string uses the result of the quotation marks.
(strtolower, strtoupper, ucfirst or function. ˇ Type the code that uses
ucwords) followed by ().
the ord and chr functions.

104 105
PHP WORK WITH STRINGS 4
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.
FORMAT A STRING TYPE THIS: RESULT:
$name = "David"; David's hourly rate is $10.24.

T
he printf function allows you to format strings The result of the printf function is normally right-justified, $rate = 10.2369;
for output. The printf function requires two but you can include the alignment specifier (-) to signify that $info = sprintf("%s's hourly rate is $%.2f.", $name, $rate);
arguments––a format string and a list of values you the result should be left-justified. print "$info<br>";
want to format. A format string contains the formatting rules
that will be applied to the values. Each formatting rule in the You can also include a width specifier to indicate a minimum
format string must have a corresponding value in the list. width. For example, the formatting rule %8s formats a string
so it will have a minimum width of eight characters. You can use the following type specifiers to indicate
Formatting rules are specified using a percentage symbol (%) the type of formatting you want to apply.
and a type specifier that indicates the type of formatting to A precision specifier indicates how many decimal digits
be applied. Before including the type specifier, you may also should be displayed. The precision specifier is represented TYPE SPECIFIER: MEANING:
indicate padding, alignment, width and precision specifiers, by a dot (.) followed by the number of decimal digits. For b Format as a binary number.
in that order, to further format the string. These specifiers example, the formatting rule %.2f formats a floating-point
number with a precision of two decimal places. c Format as a character specified by the ASCII value.
are useful for lining up text and numbers, improving the
appearance of data in text-based Web browsers. d Format as a decimal number.
A format string can also contain characters you do not
want to format. For example, to include text in a string with e Format as a floating-point number, using exponential notation.
The padding specifier indicates the character you want to
use to pad the result. The padding specifier consists of a formatted numbers, type the text in the format string. PHP f Format as a floating-point number.
single quotation mark (') followed by the character you will replace the formatting rules in the format string with the o Format as an octal number.
want to use. By default, spaces are used for padding. formatted numbers and then output the text and formatted
numbers. s Format as a string.
x Format as a hexadecimal number with lowercase letters.
X Format as a hexadecimal number with uppercase letters.

FORMAT A STRING

⁄ To format a string ¤ Between the parentheses, type ‹ Type a comma followed ■ You may specify a value › Repeat step 3 for ˇ Type the code that Á Display the PHP page ■ The Web browser
for output, type printf(). the formatting rules you want to by the name of the variable instead of a variable. String each formatting rule uses the printf function. in a Web browser. displays the result of
use enclosed in quotation marks. you want to use for the values must be enclosed in you specified. formatting a string.
first formatting rule you quotation marks.
Note: You may also include text you do specified.
not want to format within the quotation
106 marks. 107
PHP WORK WITH STRINGS 4
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
FIND THE LENGTH OF A STRING 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.

P
HP's strlen function allows you to determine If the string for which you want to determine the length
the number of characters in a string. The strlen contains spaces or punctuation marks, the strlen TYPE THIS: RESULT:
function is often used to find the length of a string function will count the spaces and punctuation marks $amount = "\$259 dollars for hotel expenses."; 4
stored in a variable. The strlen function is especially as characters. PHP evaluates any escape sequences in a $mask = "1234567890\$";
useful for finding the length of a string before it is string, such as tabs (\t) or newlines (\n), before counting print strspn($amount, $mask);
processed. For example, you can use the strlen function the number of characters, so each escape sequence is
to check whether a password provided by a user has the counted as one character. For example, the strlen
required minimum number of characters or whether the function would count six characters in the string "hello\n".
data entered by a user is within a specific character limit The strcspn function is similar to the strspn function, except
before allowing the user to continue using your Web site. If you use the strlen function with a numeric value, the strcspn function works in reverse by returning the length
PHP will evaluate the number as if it were a string. of the portion of a string which does not contain the characters
Determining the length of a string is also useful if you If the number includes a decimal point, the decimal specified in a mask. When the strcspn function encounters a
want to iterate through each character in a string using point will also be counted as a character. For example, character specified in the mask, the function will stop executing.
a loop. You would determine the length of the string and the strlen function would count nine characters in the
use the length as the condition for ending the loop. number 123456.78. TYPE THIS: RESULT:
$filename = "\n\n \r \t\t ##my_webpage.html"; 10
$mask = "abcdefghijklmnopqrstuvwxyz_.";
print strcspn($filename, $mask);

FIND THE LENGTH OF A STRING

⁄ Type the code that ¤ To determine the ‹ Between the parentheses, ■ You can also type a string › Type the code that uses ˇ Display the PHP page ■ The Web browser
creates a string variable length of the string, type the name of the variable between the parentheses. the strlen function. in a Web browser. displays the result of
and assigns it a value. type strlen(). that stores the string for Strings must be enclosed in finding the length of
which you want to determine quotation marks. a string.
the length.

108 109
PHP WORK WITH STRINGS 4
When using a while loop to execute the strtok The implode function may be used to join the
function, if two tokens are adjacent in the string, elements in an array into one string. When calling
the function will return an empty string and the this function, you need to specify a string, which
while loop may end before the rest of the string will be used to join the array elements, and the
DIVIDE A STRING is processed. To avoid this type of problem, you
should use a strict comparison for FALSE.
array containing the elements to be joined.
TYPE THIS:
ou can use the strtok function to divide a string The remaining string will then be processed and the

Y
Example:
based on one or more characters, called tokens, you strtok function will return a segment of the string from $fruitsArray = array ("apple", "orange", "peach",
while (($word = strtok(" .")) !== FALSE) "grape", "melon");
specify. This process is also referred to as tokenizing the last token found to the next token in the string. { $fruitsString = implode(" and ", $fruitsArray);
a string. When the strtok function is first called, it print $word . "<br>"; print $fruitsString;
requires two arguments––the string you want to divide If you want to access every segment of a string, you may }
and the tokens you want to use to divide the string. The want to call the strtok function once and then use a
strtok function then returns a segment of the string from while loop to execute subsequent calls to the strtok
function. The while loop should be set to terminate when The explode function may be used to divide a
the beginning of the string to the position of the first token. string and return an array of strings. This function
the strtok function returns an empty string. RESULT:
You may specify one or more characters to be used as typically requires two arguments––a string to be
tokens. If you specify an empty string as a token, the The strtok function works well for processing strings used as a separator and the string to be divided. apple and orange and peach and grape and melon
strtok function will simply return the entire string. The with simple structures. For example, the strtok function You may also specify an optional third argument
strtok function will also return the entire string if the is useful for counting the number of words in a sentence or that indicates the maximum number of elements
string does not contain any of the tokens you specified. for processing a database file in which the data is separated you want returned.
by tab characters.
After the first time the strtok function is called in a PHP TYPE THIS: RESULT:
page, PHP will keep track of the remaining string that has $fruitsString = "apple orange peach grape melon"; apple : orange : peach : grape : melon :
not yet been divided. When the strtok function is called $fruitsArray = explode(" ", $fruitsString, 5);
again in the page, you need to indicate only the tokens. You foreach ($fruitsArray as $value)
do not need to specify the string you want to divide again. {
print "$value : ";
}

DIVIDE A STRING

⁄ Create a variable that ‹ Between the parentheses, ˇ Type the code that Á Type the code that ‡ To access the ■ After the first call to the ° Display the PHP page ■ The Web browser
contains a string you want type the name of the variable assigns the result of the uses the result of the subsequent segments of strtok function, you do in a Web browser. displays the result of
to divide. that contains the string, strtok function to a strtok function. the string, type the code not need to specify the using the strtok
followed by a comma. variable. that creates a while loop variable that contains the function to divide a
¤ To divide the string, ■ The strtok function and uses the results of string you want to divide. sentence.
type strtok(). › Type the characters you returns a segment of the the strtok function.
want to use to divide the string, string up to the first token.
110 enclosed in quotation marks. 111
PHP WORK WITH STRINGS 4
If you want to verify that the whitespace characters have
been removed from a string, you may use the strlen
TRIM A STRING function to count the number of characters in the original
string and the number of characters in the resulting string.

T
here are several functions used for trimming These functions are useful for cleaning up user input from a TYPE THIS: RESULT:
whitespace characters from strings before the strings form, since the data received from forms can sometimes be $original = "Welcome to my Web page!\0\t \r\n"; Length of original string: 28
are used or processed. Whitespace characters, which unpredictable. For example, when a user is asked to enter $trimmed = rtrim($original); Length of trimmed string: 23
include spaces, carriage returns (\r), newlines (\n), data into a form, a user may inadvertently type extra spaces. print "Length of original string: " . strlen($original);
tabs (\t), vertical tabs (\013) and null characters (\0), Trimming the extra spaces from the beginning and end of print "<br>Length of trimmed string: " . strlen($trimmed);
are normally invisible when displayed on a Web page, but the string may help ensure that the data is processed
may cause problems when included in data to be processed. properly. PHP does not have a function that removes requires three arguments––a pattern containing
To remove whitespace characters from the end of a string, You may also use these functions to remove formatting whitespace characters from the middle of a the characters to be matched and replaced, a
you can use the rtrim function. The ltrim function is from text that is read from a file or will be written to a file. string, but you can use the eregi_replace replacement character or string and a string
used to remove whitespace characters from the beginning For example, text files that come from different operating function to replace adjacent whitespace that contains characters to be replaced. The
of a string. To remove whitespace characters from the systems, such as UNIX or Windows, may be formatted characters in a string with a specified character eregi_replace function cannot be used
beginning and the end of a string, you can use the trim differently. Removing whitespace characters from a line or string. The eregi_replace function to replace null characters (\0) in a string.
function. of text before it is processed or written to a file can help
avoid potential errors. TYPE THIS: RESULT:
The rtrim, ltrim and trim functions all take the string
to be trimmed as an argument and return the string with $original = " This \t is\n\n a string . . ."; Before:
$replaced = eregi_replace("[\n\t\013\r ]+", " ", $original);
the appropriate whitespace characters removed. The print "<b>Before:</b><pre>$original</pre>"; This is
returned string can be directly displayed to a Web browser print "<b>After:</b><pre>$replaced</pre>"; a string . . .
or assigned to a variable, which can then be further
processed in the script. After:
This is a string . . .

TRIM A STRING

⁄ Type the code that ‹ Between the parentheses, ˇ To remove whitespace ‡ Type the code that ° To remove whitespace ‚ Type the code that — Display the PHP page ■ The Web browser
creates variables that contain type the name of the variable characters from the beginning uses the result of the characters from the beginning uses the result of the in a Web browser. displays the results of
strings you want to trim. that contains the string you of a string, type ltrim(). ltrim function. and end of a string, type trim(). trim function. trimming strings.
want to trim.
¤ To remove whitespace Á Between the parentheses, · Between the parentheses,
characters from the end of › Type the code that uses type the name of the variable type the name of the variable
a string, type rtrim(). the result of the rtrim that contains the string you that contains the string you
function. want to trim. want to trim.
112 113
PHP WORK WITH STRINGS 4
The strncmp function can be used to compare a specific The strcasecmp and strncasecmp
number of characters at the beginning of two strings. This functions can be used to perform
function takes three arguments––the names of the two variables case-insensitive string comparisons.
COMPARE STRINGS storing the strings you want to compare and the number of
characters to be compared. The strncmp function, similar to
When these functions are used, the case
of characters in the strings being compared
the strcmp function, performs a case-sensitive comparison is ignored. To use the strncasecmp
ou can use the strcmp function to compare two function returns a value greater than zero, typically 1. If the

Y strings based on the ASCII (American Standard Code


for Information Interchange) values of the characters
in each string. For more information about ASCII values,
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.
and returns an integer indicating which of the strings has a
greater value or indicating that the strings have the same value.

TYPE THIS:
function, you must indicate the number
of characters you want to compare at the
beginning of the strings.
see page 105. TYPE THIS:
If one entire string exactly matches the beginning of the $word1 = "banana";
Comparing the values of strings can be useful if you want other string, the strcmp function returns the number $word2 = "bandit"; $firstWord = "hello";
to sort the strings into a specific order. For example, you of additional characters found in the longer string. If you $secondWord = "HELLO";
can compare the strings "cap" and "cat" and then put the compare an empty string to a non-empty string, the $result = strncmp($word1, $word2, 3); $result = strcasecmp($firstWord, $secondWord);
if ($result == 0)
strings in order. Based on a comparison of the ASCII values number of characters in the non-empty string is returned. {
of each character in the strings, the string "cap" would Whether the number is positive or negative depends on if ($result == 0)
print "The beginning of the word <b>$word1</b> is the same"; {
come before the string "cat". It is important to remember which of the two strings is longer. If the first string is print " as the beginning of the word <b>$word2</b>."; print "The words are the same.";
that uppercase characters have different ASCII values than longer, a positive number is returned. If the second string } }
lowercase characters. is longer, a negative number is returned. else else
{ {
The strcmp function takes the strings you want to The strcmp function is often used with an if statement print "The words are different."; print "The words are different.";
compare or the names of the variables storing the strings to test which string has the greater value and then perform } }
as its arguments. After performing a case-sensitive an action.
comparison, the strcmp function returns an integer value
indicating which of the strings has a greater value. If the RESULT: RESULT:
first string has a greater value than the second string, the The beginning of the word banana is the same as the The words are the same.
beginning of the word bandit.

COMPARE STRINGS

⁄ Type the code that ¤ Type the code that › Between the parentheses, ˇ Type the name of the Á Type the code that ‡ Display the PHP page ■ The Web browser
creates the first string creates the second string type the name of the first second string variable. uses the strcmp function. in a Web browser. displays the result of
variable you want to use variable you want to use string variable followed by comparing strings.
in a comparison. in a comparison. a comma.
‹ To compare the strings,
114 type strcmp(). 115
PHP WORK WITH STRINGS 4
If you do not want to extract a substring from the offset to the The strrchr function can be used to extract
end of the string, you can include an argument in the substr a substring from the last occurrence of a
function to specify the number of characters you want to specified character to the end of a string. To
EXTRACT OR REPLACE A SUBSTRING extract. If a negative number is specified, PHP removes that
number of characters from the end of the substring.
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

T
he substr function allows you to access the string. When counting characters from the end TYPE THIS: matched.
a specific part of a string, called a of a string, PHP starts the count at 1, not zero (0).
$file = "my_webpage.htm";
substring. TYPE THIS:
The substr_replace function allows you to print "Filename: " . substr($file, 0, 10);
You must specify the name of the variable containing specify replacement text for a substring and return $url = "http://www.abccorp.com/Sales2000";
the string from which you want to extract a substring. the modified string. You must specify the name of $directory = strrchr($url, "/");
RESULT: print $directory;
The offset, or position, of the substring within the the string variable in which you want to replace
string must also be specified. If the offset value is a text. The new text you want to use and a positive Filename: my_webpage
positive number, PHP finds the starting position of or negative offset of the substring must also be
the substring by counting the number of characters specified. RESULT:
from the beginning of the string. Characters in a The strstr function can be used to extract a substring from /Sales2000
string are numbered starting at zero (0). The substr You can also specify the length of the substring the first occurrence of a specified character to the end of a
function will return a substring that begins at the you want to replace. If a positive number is used string. To use this function, you must specify the name of the
position you specified and ends at the end of the to specify the length, PHP replaces that number of string variable from which you want to extract a substring
string. characters with the replacement text. If a negative and the character to be matched.
number is used, PHP stops replacing text that
If the offset value you specify is a negative number, number of characters from the end of the string. TYPE THIS: RESULT:
PHP finds the starting position of the substring by The replacement text does not have to be the $email = "martine@maran.com"; @maran.com
counting the number of characters from the end of same length as the substring. $domain = strstr($email, "@");
print $domain;

EXTRACT OR REPLACE A SUBSTRING

⁄ Type the code that ‹ Between the parentheses, REPLACE A SUBSTRING ° Type a comma followed · Type a comma followed — Type the code that uses ± Display the PHP page ■ The Web browser displays
creates a string variable type the name of the string Á To replace a substring in by the replacement text by the offset of the substring the substr_replace in a Web browser. the results of extracting and
and assigns it a value. variable from which you want a string, type substr_replace(). enclosed in quotation marks. you want to replace. function. replacing substrings.
to extract a substring.
¤ To extract a ‡ Between the parentheses, ‚ Type a comma followed
substring, type substr(). › Type a comma followed type the name of the string by the length of the substring
by the offset of the substring variable in which you want you want to replace.
you want to extract. to replace text.
ˇ Type the code that uses
116 the substr function. 117
PHP WORK WITH STRINGS 4
You may want to use the substr function to extract The strrpos function is used to find the last
a substring that is a specific number of characters occurrence of a dot (.) in the string. The return
SEARCH FOR A SUBSTRING OR CHARACTER from a substring or character you find using the
strpos or strrpos function. In the example
value is then increased by 1 and the new value
is used as the offset where the substr function
below, the extension is extracted from a filename. will extract the extension.

T he strpos and strrpos functions allow you to


search a string to find a substring or character you
specify.
The strpos function allows you to search a string for
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.
TYPE THIS:
$file = "my_webpage.php";
$offset = strrpos($file, ".") + 1;
print "The file type is: " . substr($file, $offset);
RESULT:
The file type is: php

the first occurrence of a substring and return the offset, The strrpos function takes two arguments––the name
or position, of the substring. If the substring cannot be of the variable containing the string you want to search and
found in the string, a value of false is returned. the character you want to search for, enclosed in quotation You can use the strpos function in a while statement
marks. If you specify more than one character, only the first to find all the instances of a substring in a string. In the
To use the strpos function, you must specify the name character will be used in the search. example below, the offset is advanced by one position
of the variable containing the string you want to search every time the while loop is iterated.
and the substring you want to search for. The substring The strpos and strrpos functions are often used with
must be enclosed in quotation marks. an if statement to test whether the specified substring or TYPE THIS: RESULT:
character was found and then perform an action. When
Although not required, PHP allows you to specify a starting using an if statement, PHP could confuse the zero (0)
$users = "Barry Pruett, Mary Corder, Ted Cains, Mary Bednarek, Mary Hicks"; Mary found at position: 14
offset when searching for a substring. When determining $offset = 0; Mary found at position: 38
position in a string with a value of false. To prevent this
the starting offset, keep in mind that the characters in a type of problem in your code, you should use the Identical Mary found at position: 53
while ($position !== false)
string are numbered starting at zero (0). It is important to to comparison operator (===) in the if statement. {
note that even if you specify a starting offset, the position $position = strpos($users, "Mary", $offset);
of the substring returned by the function will still be relative if ($position === false) break;
to the beginning of the string. print "Mary found at position: $position<br>";
$offset = $position + 1;
}

SEARCH FOR A SUBSTRING OR CHARACTER

⁄ Type the code that creates ‹ Between the parentheses, ˇ To specify a starting Á Type the code that SEARCH FOR A CHARACTER · Type the character — Display the PHP page ■ The Web browser
a variable that stores the type the name of the string position for the search, uses the strpos function. ‡ To search for the last occurrence you want to search for, in a Web browser. displays the results of
string you want to search. variable you want to search type a comma followed of a character in a string, type enclosed in quotation searching for a substring
followed by a comma. by the offset in the string strrpos(). marks. and a character in a string.
¤ To search for the first where you want to start
occurrence of a substring › Type the substring you the search. ° Between the parentheses, type ‚ Type the code that
in a string, type strpos(). want to search for, enclosed the name of the string variable you uses the strrpos
in quotation marks. want to search followed by a comma. function.
118 119
PHP WORK WITH STRINGS 4
The str_replace function is case-sensitive and will only
replace portions of the string that perfectly match the data
REPLACE DATA IN A STRING 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.
ou can use the str_replace function to replace have the same number of characters. If the two parameters

Y 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
do not match in length, the longer parameter will be
truncated to match the number of characters in the shorter
parameter.
TYPE THIS:
$text = "Mary had a little Lamb, little lamB, little LaMb.";
print eregi_replace("lamb", "sheep", $text);
RESULT:
Mary had a little sheep, little sheep,
and the string that contains the data to be replaced. The little sheep.
result of the str_replace function can be directly The strtr function is useful for correcting data received
displayed to a Web browser or assigned to a variable from a form or a text file. For example, if a user enters
that can be further processed. data containing accented letters into a form, you may want The strtr function may also be used to replace multiple
to replace the accented letters with regular letters before words in a string. Instead of specifying the sets of characters
The str_replace function is useful for editing data that is processing the data. to be searched and replaced, you can specify an associative
read from a text file or will be written to a file. For example, array as the second argument of the strtr function. The
you may want to correct the spelling of a name or update an When the strtr function is used, each character in the
string is examined in sequence and replaced accordingly. instances of the array keys found in the string are replaced
e-mail address before processing the information. by the corresponding array values.
After the string has been completely processed, no further
You may want to replace specific characters in a string with replacements are performed.
another set of characters. This can be accomplished using TYPE THIS: RESULT:
the strtr function. To use the strtr function, you must You may also use the substr_replace function to $oldList = "apple, banana, melon, grape"; Old list: apple, banana, melon, grape
first specify the string to be modified. You then specify replace data in a string. For information about the $replacement = array("apple" => "melon", "melon" => "mango"); New list: melon, banana, mango, grape
the set of characters that you want to replace and the substr_replace function, see page 116. $newList = strtr($oldList, $replacement);
print "Old list: $oldList<br>";
replacement characters. The last two parameters should print "New list: $newList<br>";

REPLACE DATA IN A STRING

USING THE str_replace ¤ To replace data in a ‹ Between the parentheses, ˇ Type a comma USING THE strtr FUNCTION · Type a comma followed by ± Display the PHP page ■ The Web browser displays
FUNCTION string, type str_replace(). type the data you want followed the name of the the characters you want to in a Web browser. the results of replacing data
‡ To replace characters in
⁄ Type the code that to replace, enclosed in string variable in which a string, type strtr(). replace, enclosed in quotation and characters in a string.
creates variables that quotation marks. you want to replace data. marks.
contain strings in which ° Between the parentheses,
› Type a comma followed Á Type the code that type the name of the string ‚ Type a comma followed by
you want to replace data. by the replacement string, uses the result of the the replacement characters,
variable in which you want
enclosed in quotation marks. str_replace function. to replace characters. enclosed in quotation marks.
— Type the code that uses the
120 result of the strtr function. 121
PHP WORK WITH STRINGS 4
You can use the strip_tags function to remove all HTML
WORK WITH HTML TEXT 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

T
he htmlspecialchars and htmlentities You can use the get_html_translation_table as plain text that can be easily processed or manipulated.
functions allow you to convert special characters in a function to display a list of the characters that the
string to their character entity reference. The character htmlspecialchars or htmlentities function TYPE THIS: RESULT:
entity reference consists of an ampersand, the name of the will convert. As an argument, you specify either
character and a semicolon. You can convert characters in HTML_SPECIALCHARS or HTML_ENTITIES. The function
$htmlSource = "<html><head><title>ABC Corporation</title></head><body> ABC Corporation Welcome to Our Web Site.
<h1>Welcome to Our Web Site.</h1></body></html>";
order to force a Web browser to display HTML code as plain returns an associative array that has the actual character $rawText = strip_tags($htmlSource);
text on a PHP page instead of processing the code. This is to be converted as the key and the character entity print $rawText;
useful when you want to block HTML code a user enters in a reference as the value for each element.
form that might interfere with the processing of a Web page.
PHP allows you to use an optional second argument The nl2br function allows you to convert newline characters (\n)
The htmlspecialchars function converts only the most with the htmlspecialchars, htmlentities and in a string to HTML <br> tags. For example, you can use the
common HTML characters to their character entity reference get_html_translation_table functions to specify nl2br function to convert a newline character a user types in a
values. The htmlentities function is similar to the how quotation marks should be handled. By default, text area on a form to a <br> tag that a Web browser can process
htmlspecialchars function, except the htmlentities PHP will use the ENT_COMPAT value, which converts only and display as a line break on a Web page. The nl2br function
function converts all the characters that have an equivalent double quotation marks to their HTML entity reference. takes as its argument the string that contains the newline character
character entity reference in HTML. To convert both double and single quotation marks, use to be converted or a variable that stores the string.
the ENT_QUOTES value. If you specify the ENT_NOQUOTES
To use the htmlspecialchars and htmlentities value, neither double nor single quotation marks will be
functions, you specify the string to be converted or a variable TYPE THIS: RESULT:
converted.
that stores the string. Each function will return a string with $userInput = "Hello!\nMy name is Tom!"; Hello!
the corresponding character entity references for the HTML $formattedText = nl2br($userInput); My name is Tom!
characters. print $formattedText;

WORK WITH HTML TEXT

CONVERT HTML ¤ To convert HTML › To specify how you DISPLAY THE TRANSLATION TABLE ° To display the character ‚ Type the code — Display the PHP page ■ The Web browser displays
CHARACTERS characters to their want the function to convert entity reference values that formats the result in a Web browser. the result of converting HTML
Á To view the characters
⁄ Type the code that character entity reference, quotes, type a comma that will be converted, type in a translation table, type of the get_html_ characters and displays a
creates a variable that type htmlspecialchars() followed by the value you get_html_translation_table(). a variable name followed translation_table translation table for the
contains HTML code. or htmlentities(). want to use (ENT_NOQUOTES, by = htmlspecialchars(). function in a table. function you specified.
ENT_COMPAT or ENT_QUOTES). ‡ Between the parentheses,
‹ Between the parentheses, type the value for the · Between the parentheses,
type the name of the variable ˇ Type the code that uses the translation table you want to type the name of the variable
that contains HTML code. results of the conversions. display (HTML_SPECIALCHARS that stores the characters that
122 or HTML_ENTITIES). will be converted. 123
PHP WORK WITH FILES 5
WRITE TO A FILE 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.

I
t is often necessary to access text files stored on You can use the fputs function to write a line of
the Web server from within a PHP page. Writing information to the file. The fputs function usually takes
ACCESS MODE: DESCRIPTION:
data to text files allows you to store data, such as two arguments––a file pointer and the information to be
configuration settings and application information. written to the file. You may also specify the maximum r Open a file for reading only. Place the file position indicator
length of the line to be written, in bytes. After the at the start of the file.
Before you can write to a file, you must establish a maximum length has been reached, any extra information
connection to the file by using the fopen function to r+ Open a file for reading and writing. Place the file position
at the end of a line will not be written to the file.
open a file and create a file pointer. A file pointer indicates indicator at the start of the file.
the file you want to work with. The fopen function takes Once all the information has been written to a file, the
two arguments––the name of the file to be opened and w Open a file for writing only. Place the file position indicator
fclose function should be used to close the connection
the access mode you want to use. at the start of the file. Create the file if it does not exist.
to the file.
To open a file for writing, the w access mode can be w+ Open a file for reading and writing. Place the file position
As with other operations involving accessing a file, the
specified. This access mode creates a new file if the file indicator at the start of the file. Create the file if it does
proper permissions that allow the file to be written to
does not already exist. Using the w access mode will also not exist.
must be in place. For information about permissions, you
overwrite any information already in an existing file. should consult your operating system's documentation. a Open a file for writing only. Place the file position indicator
When a file is opened for writing, the file position at the end of the file. Create the file if it does not exist.
indicator is placed at the start of a file. The file position a+ Open a file for reading and writing. Place the file position
indicator indicates where the next operation will be indicator at the end of the file. Create the file if it does
performed in the file. not exist.

WRITE TO A FILE
data - Notepad

⁄ To open a file and ¤ Between the parentheses, › To write a line of Á Type a line of ‡ Repeat steps 4 to 6 ° To close the file, ■ When the PHP page ‚ You can use your text
create a file pointer, type the name of the file you information to the file, information you want until you have specified type fclose(). is displayed in a Web editor to open the file and
type a variable name for want to open followed by a type fputs(). to write to the file. all the information you browser, the information view its contents or use a
the file pointer followed comma. want to write to the file. · Between the will be written to the file. PHP page to read the file.
by = fopen(). ˇ Between the parentheses, ■ You may also specify parentheses, type For information about
‹ To specify the access type the name of the file the maximum length of the name of the file reading a file using a PHP
mode that allows you to pointer followed by a comma. the line of information, pointer. page, see page 126.
124 write to the file, type "w". in bytes. 125
PHP WORK WITH FILES 5

READ A FILE
Most computers that use Web server software The file function may be used to

A
fter creating a file pointer and opening a file for The fgets function will read a line of text up to the
reading, you can access the contents of the file. maximum length specified or until it reaches a newline and PHP have sophisticated username and automatically open, read and close a file.
This allows you to display the data in a Web browser character. A line will be truncated if it is longer than the password-based security features. When using The file function takes the name of a
or compare the data in the file to other data. When opening maximum length specified. When the fgets function PHP to read a file, the correct permissions that file as an argument and returns the entire
the file, you must specify an access mode that allows reading is used again, it will read the next line in the file and not allow the PHP script to read the file must be contents of the file as an array. Each
from the file. The r access mode is typically used. the remainder of the previous line that was truncated. enabled on the Web server that stores the file. element in the array will correspond to
Web servers are typically configured to use a line of information in the file. You do
When a file is initially opened for reading, the file position The feof function can be used to determine if the end a special user account, such as web or http, not need to create a file pointer when
indicator is placed at the beginning of the file. The fgets of a file has been reached. The feof function takes the to allow access to files. This user account using the file function.
function is used to read the line of text indicated by the file file pointer as an argument and is usually used with the must have read permissions for the files to
Example:
position indicator and must have two arguments––the file Not operator (!) as the condition tested in a while loop. be opened because when PHP attempts to
$lines = file("data.txt");
pointer and the maximum length of the line to be read, read a file, the operating system interprets it foreach ($lines as $value)
in bytes. After a line of text is read from the file, the file Once all the lines from a file have been read, the fclose as an attempt to read the file by the username
function should be used to close the connection to the file. {
position indicator automatically moves to the next line assigned to the Web server. The special user print $value . "<br>";
of text in the file. account on the Web server must be set up }
before files can be accessed using PHP.
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.

READ A FILE

⁄ Perform steps 1 and 2 ¤ To specify the access ‹ To read a line of ˇ Type the maximum Á Create a while loop ‡ To close the file, type · Display the PHP page ■ The Web browser
on page 124 to enter the mode that allows you to information from the length of the line of that will read and display fclose(). in a Web browser. displays the result of
code that opens a file and read information from file, type fgets(). information to be read, each line of information reading a file.
creates a file pointer. the file, type "r". in bytes. from the file. ° Between the
› Between the parentheses, type the
parentheses, type the name of the file pointer.
name of the file pointer
126 followed by a comma. 127
PHP WORK WITH FILES 5

COPY OR DELETE A FILE In order to successfully copy and delete files, you
must have the appropriate file and operating system
You can use the filesize function
to determine the size of a file in bytes.
permissions on the computer where the files are Determining the size of a file is useful

P
HP provides functions that allow you to manage files The unlink function derives its name from the command stored. For example, you cannot delete a file that when you want to delete large files in
from within a PHP page. For example, the copy used to delete files on Unix computers. The unlink function has read-only permissions set. For information order to free up storage space.
function creates a copy of a file, while the unlink takes the filename or path of the file you want to delete as its about the permissions for an operating system,
function deletes a file. Copying a file is useful for creating argument. refer to the operating system's documentation. TYPE THIS:
a backup copy of a file. Deleting a file lets you remove a file
that is no longer needed by the PHP page. When specifying arguments for the copy and unlink print "The size of the file is: ";
functions, if the file you want to copy or delete is located in The copy function is also useful for moving a file print filesize("formdata.txt") . " bytes";
It is good programming practice to verify whether a file exists the current directory, you can specify just the name of the from one directory to another. To move a file, you
before attempting to copy or delete the file. You can use the file. If the file is located in a different directory, you must use the copy function to create a copy of the file
file_exists function to determine whether a file exists. specify the full path to the file. You may want to store the in the directory you want to move the file to. You RESULT:
The file_exists function returns a value of true if a file name or path of a file in a variable and then use the variable can then use the unlink function to remove the
you specify exists and a value of false if the file does not with the copy or unlink function. original file from the directory you no longer want The size of the file is: 1867 bytes
exist. to store the file.
When the copy and unlink functions are successful, they
The copy function takes two arguments––the filename or return an integer value other than 0. If the functions are not Example:
path of the file to be copied and the filename or path of the successful, they return a value of 0. copy("formdata.txt", "backup/webfile/formdata.txt");
copy you want to create. When the file is copied, the copy unlink("formdata.txt");
function duplicates the file without removing the original file.

COPY A FILE DELETE A FILE

⁄ To copy the file, type copy(). ‹ Type a comma and › Display the PHP page ■ The file has been ⁄ To delete a file, type ¤ Between the parentheses, ‹ Display the PHP page ■ The file has been
then type the name or in a Web browser. copied. unlink(). type the name or path of in a Web browser. deleted.
¤ Between the parentheses, path of the copy you the file you want to remove
type the name or path of the want to create enclosed enclosed in quotation marks.
file you want to copy enclosed in quotation marks.
in quotation marks.

128 129
PHP WORK WITH FILES 5
DETERMINE THE STATUS OF A FILE Determining the status of a file can improve You can use the is_dir function to determine
the efficiency of a PHP script. For example, whether an item is a directory. The is_dir

W
hen working with files, it is often necessary To determine whether a file can be written to by a PHP before performing a complex process, such function returns a value of true if the directory
to determine information about a file before page, you use the is_writable function. If the file as retrieving information from a database you specify exists and is a directory.
performing an action. For example, you should exists and can be written to, the function returns a value and appending the information to a file, a
verify that a file can be written to by a PHP page before of true. The is_writable function is commonly used to check can be made to ensure the data can TYPE THIS:
opening the file for writing. check the status of files that can be written to by multiple be written to the file.
users, since such files are frequently temporarily if (is_dir("c:\data\webinfo"))
The is_file function allows you to determine if a file unavailable for writing while in use by another user.
{
you specify is a file. This is useful when you want to The is_file, is_readable and print "c:\data\webinfo is a directory.";
ensure that an item is a file rather than a directory or a The is_file, is_readable and is_writable is_writable functions may be affected by }
the operating system you are running and the else
link to another file. The is_file function is commonly functions all take a single argument that indicates the {
used to verify that an item is a file before attempting to file you want to check. The argument can be the file file system used by the computer that stores print "This is not a directory.";
open the file. The function returns a value of true if the name or path of the file, such as c:\webfiles\form.dat, the files. While the is_file, is_readable }
item you specify is a file. or a variable that stores the filename or path, such as and is_writable functions should perform
$filename. If the file you want to check is in the current as expected on Unix systems, there may
Before opening a file you want to read, it is common directory, you can specify just the name of the file. If the be incompatibilities that interfere with
practice to use the is_readable function to verify that RESULT:
file is located in a different directory, you must specify the operation of these functions on other
the file can be read from a PHP page. If a file exists and the full path of the file. systems. c:\data\webinfo is a directory.
is readable, the is_readable function returns a value
of true.

DETERMINE THE STATUS OF A FILE

⁄ To store the path of a ‹ Between the parentheses, ˇ To determine whether the ‡ Type the code that ° To determine whether ‚ Type the code that uses — Display the PHP page ■ The Web browser
file you want to check in type the name of the variable file can be read from the PHP uses the result of you can write to the file, the result of determining in a Web browser. displays the results of
a variable, type the code that stores the path of the file. page, type is_readable(). determining whether type is_writable(). whether the file is writable. determining the status
that assigns the path to the file is readable. of a file.
the variable. › Type the code that uses the Á Between the parentheses, · Between the parentheses,
result of determining whether type the name of the variable type the name of the variable
¤ To determine whether the file is a file. that stores the path of the file. that stores the path of the file.
the file is a file, type
is_file().

130 131
PHP WORK WITH FILES 5
Only the owner of a file or the system The chown function can be used to change
administrator can change the group or the owner of a file. When using the chown

SET FILE GROUP AND PERMISSIONS ON UNIX 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
function, you must specify the location and
name of the file and the user name of the
new owner. Only the system administrator
ou can use a PHP page to change the group a file dash followed by a series of nine characters. The first three

Y
owner belongs. The system administrator can use the chown function.
belongs to and set the permissions for the file. characters represent the permissions for the file's owner. can assign a file to any group.
Changing the group and permissions for a file The next three characters represent the permissions for the Example:
allows you to restrict access to the file. owner's group and the last three characters represent the chown("/var/www/html/file1", "maryc")
permissions for all other users.
The system function allows you to execute UNIX
commands from within a PHP page. To view the group To change the permissions for a file, you use the chmod
The fileowner function allows you to determine the owner of a
and permissions for each file in the current directory, function. The chmod function takes two arguments––the
file. You can use the filegroup function to determine the group
you can use the ls -l command. location and name of the file and the octal value representing
a file belongs to, which is usually the group to which the owner
the file permissions you want to use. The octal value consists
The chgrp function is used to assign a file to a new group. belongs. These functions retrieve an ID number that represents
of three digits, which represent the permissions for the
To use the chgrp function, you specify the location and the user name of the owner or the name of the group. You can
owner, followed by the permissions for the owner's group
name of the file you want to assign to a new group followed use the password file or group file available in Unix to match an
and the permissions for other users. For example, the
by the name of the group. ID number with the corresponding user name or group name.
-rwxr-xr-x permissions will have an octal value of 755.
Unix systems allow you to assign any combination of You should precede the octal value with a zero (0). TYPE THIS: RESULT:
read (r), write (w), and execute (x) permissions to a file's The chgrp and chmod functions return a value of true
owner, the group the file belongs to and all other users.
print ("The UID is: " . fileowner("/var/www/html/file1")) . "br"; The UID is: 48
when the functions are executed successfully. print ("The GID is: " . filegroup("/var/www/html/file1")); The GID is: 501
The permissions for a file are typically represented by a

SET FILE GROUP AND PERMISSIONS ON UNIX

⁄ To execute a Unix ¤ To display a list of files CHANGE FILE GROUP ˇ Type a comma, SET FILE PERMISSIONS ° Type a comma, followed by ‚ Display the PHP page ■ The Web browser
command from the PHP in the current directory ‹ To assign a file to a new followed by the name Á To change the the octal value that represents in a Web browser. displays the results of
page, type system(). and the permissions for group, type chgrp(). of the group to which permissions for a file, the permissions you want to changing the group and
each file, type "ls –l" you want to assign type chmod(). assign to the file. The octal permissions for a file.
between the parentheses. › Between the parentheses, the file, enclosed in value should be preceded by 0.
type the location and name quotation marks. ‡ Between the
of the file, enclosed in parentheses, type the · To display an updated
quotation marks. location and name of list of the files in the current
the file, enclosed in directory, repeat steps 1 and 2.
132 quotation marks. 133
PHP WORK WITH FILES 5
PHP allows you to specify permissions for a directory in In order to successfully create and remove
octal notation. When creating a directory on a computer directories, you must have the appropriate
CREATE AND DELETE DIRECTORIES 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
file and operating system permissions on
the computer where the directories are to
chart. The UNIX permissions include read (r), write (w) be created or removed. For information
separate the words in a variable name, you

P
HP provides functions that allow you to manage A directory you want to remove must not contain any files and execute (x). The octal value will consist of three about the permissions for an operating
directories from within a PHP page. The mkdir or subdirectories. You must delete any existing files and should capitalize each word. system, refer to the operating system's
digits, representing the permissions for the owner,
function creates a new directory, while the rmdir subdirectories from a directory before you can delete the followed
Example: by the permissions for the owner's group documentation.
function removes an existing directory. You may want to directory. For information about deleting files, see page 128. and the permissions for other users. For example,
create a directory to store temporary files and then remove Dim My_Date_Of_Birth
a directory with permissions -rwxrw-r-- will have the
the directory when the files are no longer needed by the When the mkdir and rmdir functions successfully create The chdir function allows you to change
octal value 764. When entering the permissions in a
PHP page. or remove a directory, they return an integer value other which directory you are working in. This
PHP script, precede the octal value with a zero (0).
than 0. If the functions are not successful, they return a is useful when you want to work with files
When working with directories in the current directory, value of 0. stored in another directory. To change the
UNIX PERMISSIONS: OCTAL VALUE:
you specify the name of the directory you want to create current directory, specify the name of the
or remove. If you want to work with directories in a different It is good programming practice to verify whether a --- 0 directory you want to work in, enclosed in
directory, you must specify the full path of the directory you directory exists before attempting to create or remove quotation marks.
--x 1
want to create or remove. You may want to store the name the directory. You can use the file_exists function
to determine whether a file exists. -w- 2 Example:
or path of a directory in a variable and then use the variable
with the mkdir or rmdir function. -wx 3 chdir("temp");
r-- 4
When creating a new directory on a computer running the
UNIX operating system, you must also specify permissions r-x 5
for the directory. Permissions control access to the directory rw- 6
and determine the operations, such as reading and writing, rwx 7
that can be performed.

CREATE A DIRECTORY DELETE A DIRECTORY

⁄ To store the name or ‹ Between the ˇ Display the PHP page ■ The directory has ⁄ To store the name or path ¤ To remove a directory, › Display the PHP page ■ The directory has
path of the directory you parentheses, type the in a Web browser. been created. of the directory you want to type rmdir(). in a Web browser. been removed.
want to create in a variable, name of the variable remove in a variable, type
type the code that assigns the you created in step 1. the code that assigns the ‹ Between the parentheses,
information to the variable. information to the variable. type the name of the variable
› If necessary, type a you created in step 1.
¤ To create a directory, comma and then type
type mkdir(). the octal value for the
permissions you want
134 the directory to use. 135
PHP CREATING AND PROCESSING FORMS 6

CREATE A FORM ADD ELEMENTS TO A FORM


A E
dding a form to a Web page allows you to gather use depends on the amount of data that will be passed. lements are areas in a form where users can enter The name you specify is used by the PHP page that
data from users who visit the page. A form can The get method sends data to the PHP page by appending data and select options. The most commonly used processes the form to identify the element and access
be placed anywhere between the <body> and the data to the URL of the page. The post method sends element is a text box, which allows users to enter a the information in the element. A name can contain
</body> tags in an HTML document. The body of your the data and the URL separately. The get method is faster single line of data into a form. Text boxes are often used letters and numbers, but should not contain spaces or
Web page can include as many forms as you need. than the post method and is suitable for small forms. for entering names, addresses and other short responses. punctuation. If you want to include spaces in a name,
The post method is suitable for large forms that will use an underscore character (_) instead.
You use the <form> tag to create a form and the action send more than 2000 characters to a PHP page. Elements you add to a form must be placed between the
attribute to specify the location and name of the PHP page <form> and </form> tags. A form can contain as many You must add a submit button to every form you create.
that will process the data entered into the form. If the Unlike many other technologies used to process form elements as you need. The submit button allows users to send the data they
PHP page is stored in the same directory as the Web page information, PHP can automatically determine whether entered into the form to the Web server. When the Web
containing the form, you have to specify only the name a form is submitting data using the get or post method There are many different types of elements you can add server receives data from a form, the server transfers
of the PHP page. If the PHP page is not stored on the and then retrieve the information accordingly. to a form, such as text areas and check boxes. Text areas the data to the PHP page that will process the data.
same Web server as the Web page containing the form, allow users to enter several lines or paragraphs of text, The PHP page can then perform an action with the data,
you must specify the full URL of the PHP page. For information about creating a PHP page that processes while check boxes let users select options on a form. such as storing the data in a database or displaying the
data from a form, see page 140. For information about commonly used elements, see information in a Web browser.
You must also specify which method the form will use page 138.
to pass data to the PHP page. There are two methods the
form can use––get and post. The method you should 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.

CREATE A FORM ADD ELEMENTS TO A FORM


Add Elements To A Form - Microsoft Internet Explorer

⁄ Type <form action="" ¤ Between the quotation ‹ Type method="">. ˇ Type </form> where ⁄ To add a text box to a ‹ To add a submit button ˇ Display the Web ■ The Web browser
where you want to add marks, type the location and you want to end the form, type <input type="text" to the form, type <input page in a Web browser. displays the text box
a form to a Web page. name of the PHP page that › Between the quotation form. name=""> between the type="submit" name="">. and submit button.
will process the data entered marks, type the method <form> and </form> tags.
into the form. the form will use to pass ■ You can now add › Between the quotation
data to the PHP page. elements to the form. ¤ Between the quotation marks, type a word that
marks, type a word that describes the button.
136 describes the text box. 137
PHP CREATING AND PROCESSING FORMS 6
FORM ELEMENTS COMMONLY USED ELEMENTS (CONTINUED)
n element is an area in a form where users can You can find more information about form elements

A 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
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
Text Area
The textarea element displays a large text area that
allows users to enter several lines or paragraphs of text.
determine how the element will appear on a Web page. attribute to text and use the name attribute to create a A large text area is ideal for gathering comments or
text box. You may also want to use the maxlength and questions from users. You must use the name attribute
COMMONLY USED ATTRIBUTES size attributes. to create a text area.
First Name <input type="text" name="firstName" maxlength="20"> Questions? <textarea name="userQuestions"></textarea>
Type Name Value
The type attribute allows The name attribute allows you to specify The value attribute allows you First Name Questions?
you to specify the kind of a name for an element. The PHP page that will to specify a value for an element.
element you want to use. process data from the element uses the name If an element displays a button,
attribute to identify the data. Element names you can use the value attribute Check Box
can contain more than one word, but should to specify the text that will Check boxes allow users to select one or more options. For
not contain spaces or special characters. appear on the button. 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
Maxlength Size Checked
a check box. You may also want to use the checked attribute.
The maxlength attribute The size attribute allows you to The checked attribute allows
allows you to restrict the specify the width of an element. an element to display a selected Which states have you visited in the past year?<br> Which states have you visited in the past year?
number of characters a user option by default. New York <input type="checkbox" name="states" value="New York" checked> New York California Texas
California <input type="checkbox" name="states" value="California">
can enter into an element.
Texas <input type="checkbox" name="states" value="Texas">

Radio Button
COMMONLY USED ELEMENTS 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
Password Box Drop-Down List radio and use the name and value attributes to create a radio
A password box allows users to enter private data. When The select element displays a drop-down list that button. You may also want to use the checked attribute.
a user types data into a password box, an asterisk (*) allows users to select an option from a list of several
appears for each character, which prevents others from options. For example, a drop-down list can be used to What is your gender?<br> What is your gender?
viewing the data on the screen. A password box does not allow users to select one of three shipping methods. Female <input type="radio" name="gender" value="female" checked> Female Male
Male <input type="radio" name="gender" value="male">
protect the data from being accessed as it is transferred You must use the name attribute to create a drop-down
over the Internet. You must set the type attribute to list. You use the <option> tag with the value attribute
password and use the name attribute to create a to add options to the list. Submit Button Reset Button
password box. You may also want to use the value, A submit button allows users to send data in the form to A reset button allows users to clear the data they
How would you like your products shipped?
maxlength and size attributes. the PHP page that will process the data. You must add a entered into a form. A user cannot redisplay data that
<select name="shipMethod">
Password Please <input type="password" <option value="air">Air</option> submit button to each form you create. You must set the has been cleared. Reset buttons are commonly used
name="secretWord" value="password" maxlength="20"> <option value="land">Land</option> type attribute to submit to create a submit button. You in forms that have many text boxes. You must set
<option value="sea">Sea</option> may also want to use the name and value attributes. the type attribute to reset to create a reset button.
</select> You may also want to use the value attribute.
<input type="submit" name="submit" value="Submit Now">
Password Please ******** How would you like your products shipped? Air <input type="reset" value="Click to Reset">
Air Submit Now
Land Click to Reset
Sea

138 139
PHP CREATING AND PROCESSING FORMS 6
In addition to using forms, data can also be passed to a PHP page As a security precaution, a PHP
by a query string. A query string is one or more name-value pairs page that processes form data

PROCESS DATA FROM A FORM 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
should not be used to display
secure information based on the
data submitted in the form. For
and a value for the name. To enter multiple name-value pairs, example, you should not display

A
fter creating a form on a Web page, you can create The PHP page that processes a form also automatically
a PHP page that will process data submitted in the identifies the method the form is using to transfer separate each pair with an ampersand (&). A query string should troubleshooting or administrative
form. A PHP page can use information it accesses information. This allows you to create a PHP page that not exceed 2000 characters. The PHP page that receives the data information when a user name such
from a form to perform tasks such as displaying the data processes form data without having to specify whether the will create variables using the names you specify and will assign as admin is entered in a text box.
or storing the data in session variables or a database. form uses the get or post method. For more information the specified values to the variables. Form data can be easily manipulated,
about the methods a form can use to transfer information, allowing unauthorized users to
Example:
PHP makes it easy to process data from a form. When a see page 136. access the secure information.
PHP page receives form information, the page automatically http://www.abccorp.com/processform.php?userName=Ernest&region=USA
converts the names of form elements to PHP variables and After creating and saving a PHP page that processes data
assigns the data entered in the elements to the variables. To submitted in a form, you should review the code for the The empty function can be used to verify whether a user
process data entered in a form element, you simply access Web page that contains the form to verify that the action entered data in a form element. If a user leaves the form
the variable for the element by prefixing the name of the attribute displays the correct filename and location for the element blank, the empty function will return a value of true.
element with a dollar sign ($). The name of a form element PHP page. You should also verify that each form element
is specified when the element is created on the Web page has a unique name to ensure that the PHP page will create TYPE THIS: RESULT:
containing the form. For information about creating a unique variable for each form element. As with all
elements on a form, see page 137.
if(empty($userName)) You did not enter a user name.
variable names in PHP, the names of variables that store {
form data are case sensitive. print "You did not enter a user name.";
}

PROCESS DATA FROM A FORM

SET UP THE PHP PAGE ¤ Type the code that ‹ Repeat steps 1 and 2 PROCESS FORM DATA ¤ Enter data into the form. ■ The Web browser
⁄ Type $ followed by the uses the data from the for each form element ⁄ In a Web browser, displays the result of
form element. you want to access. ‹ Click the submit button processing data from
name of a form element display the Web page to pass the data in the form
you want to access. containing the form a form.
to the PHP page that will
you want to process. process the data.

140 141
PHP CREATING AND PROCESSING FORMS 6
PROCESS MULTIPLE FORM SELECTIONS
ost elements in a form are used to submit a single In the PHP page that processes the form data, you can

M 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
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
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
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
than one option at once. For example, you can create a the name of the element with a dollar sign ($), just as you the selected options in an array. options from a list, you can add error-checking
form that allows a user to select one or more items from would access a single item of information from an element. code that ensures two selections were made.
a list. Using the count function to determine the number of Example:
values passed by the element allows you to specify when <form action="select.php"> Example:
The elements most often used to pass multiple selections the for loop should end. <input type="checkbox" name="services[]" if (count($services) > 1)
in a form are the drop-down list and the check box value="tune-up" checked>tune-up<br> {
element. For more information about form elements, After creating and saving the PHP page, you should review <input type="checkbox" name="services[]" for ($x = 0; $x < count($services); $x++)
see page 138. the code for the Web page that contains the form to verify value="tire rotation">tire rotation<br> print "$services[$x]<br>";
<input type="checkbox" name="services[]" }
that the action attribute displays the correct filename and value="oil change">oil change<br>
When creating a form that can pass multiple selections for location for the PHP page. else
one element to a PHP page, you must indicate that the PHP <input type="submit" value="Submit"> {
</form> print "Please select at least 2 items.";
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[]">.

PROCESS MULTIPLE FORM SELECTIONS

tire rotation
oil change
brake inspection

CREATE THE FORM ¤ To indicate that the SET UP THE PHP PAGE ¤ Type the code for the PROCESS MULTIPLE SELECTIONS Note: To select multiple options ■ The Web browser displays
⁄ Type the code that information from the ⁄ In the PHP page, type $ for loop that will access ⁄ In a Web browser, display from a drop-down list, hold the result of processing
creates a form with an element should be stored followed by the name of the each piece of data from the Web page containing the down Ctrl as you click each multiple form selections.
element that allows users in an array, type [] after form element that allows the form element. form you want to process. option.
to select multiple options. the name of the element. users to select multiple
¤ Select options in the form. ‹ Click the submit
options. button to pass the data in
the form to the PHP page
that will process the data.
142 143
PHP CREATING AND PROCESSING FORMS 6
You may incorporate other form elements into a form that allows The ability to upload files using forms
users to upload files. This is useful for transferring other information, is not strictly a PHP feature. It is an
such as the sender's name and a file description, which you may HTML specification and can be used
CREATE A FORM TO UPLOAD A FILE want to use when processing the file that has been sent.
Example:
to upload files to Web servers using
technologies other than PHP. For
form can be used to allow users to upload a file to a to select a file from their computer. The name attribute more detailed information about how

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
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
<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">
files are transferred using forms, you
may refer to the World Wide Web
Consortium (W3C) Web site at
www.w3.org/TR/device-upload.
can send plain text files or binary files, such as images and
compressed files. The files users send are usually stored to the form, which allows users to start the process of </form>
on your Web server. transferring the file to the Web server.
You may also want to provide users with an alternate You may add a hidden field to your form to specify the maximum
The action attribute of the <form> tag should specify the size of the file that may be sent to the Web server. The value
PHP page where the file is to be sent and processed. In the method of transferring files, such as using an FTP server.
This is especially helpful in cases where a user's Web MAX_FILE_SIZE is assigned to the name attribute, and the
<form> tag, you should also use the enctype attribute value attribute is used to specify the maximum size, in bytes.
with the multipart/form-data value to ensure that the browser is not able to upload files.
This hidden field must be placed before the file input field.
files users send will transfer in the proper format. The form After the file has been sent to a Web browser, a PHP page
should also use the post method when transferring a file. may be used to retrieve and process the uploaded file. Example:
For information about using a PHP page to process a file <form action="savefile.php" enctype="multipart/form-data" method="post">
To indicate that a form element will be used to upload a file, <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
the type attribute of the <input> tag should have a value submitted using a form, see page 146.
Enter File Name: <input type="file" name="uploadedFile"><p>
of file. This form element will allow users to type the <input type="submit" value="Upload File">
name of the file they wish to send or use a Browse button </form>

CREATE A FORM TO UPLOAD A FILE

⁄ In the <form> tag, ¤ Between the quotation ‹ Type enctype="multipart/form- ˇ Between the <form> Á To add the element that ° Between the · Save the page with ■ Users can click in the box
type action="". marks, type the name of data" to ensure that the files and </form> tags, type allows users to send a file, quotation marks, type the .html extension and and type the location and name
the PHP page that will users send will transfer in the the text you want to type <input type="file">. the name that will be display the HTML page of the file they want to send.
process the file sent by proper format. appear beside the area used to identify the file. in a Web browser.
the form. that will allow users to ‡ In the <input> tag, ■ Users can also click the
› Type method="post" to send files. type name="". ■ The Web browser Browse button to open a dialog
specify the method used to displays an area that box that will help them locate
transfer the file. allows users to send the file they want to send.
144 a file. 145
PHP CREATING AND PROCESSING FORMS 6
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
PROCESS AN UPLOADED FILE the php.ini file on the Web server and look for the following section of code.
;;;;;;;;;;;;;;;;
; File Uploads ;
PHP page can be used to retrieve and process uploaded file. When accessing information from the

A 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,
$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
;;;;;;;;;;;;;;;;
file_uploads
upload_tmp_dir
= On ; Whether to allow HTTP file uploads
= c:\temp ; temporary directory for HTTP uploaded files
upload_max_filesize = 2M ; Maximum allowed size for uploaded files
form used to send the file. You must also specify the index Before you can process uploaded files using a PHP page, you must make sure
it is first temporarily stored using a filename assigned by name of the information you want to access. You use the
PHP. This temporary file will be deleted after the PHP page that file upload has been enabled and the temporary directory specified in the
tmp_name index name to access the temporary filename php.ini file exists on the Web server.
has finished processing. You can use the copy function to assigned to the uploaded file.
save a permanent copy of the uploaded file. You need to
pass two arguments to the copy function––the temporary You can use other index names to access additional pieces When an uploaded file is permanently saved on a Web server, by default, the
filename and the filename to be used to save the file, of information about the file from the $HTTP_POST_FILES file is saved in the same directory where the PHP page is located. You may
which can be the original name of the file. After the file array. For example, use the name index name to want to save the file in a different directory by appending the directory path to
has been permanently stored, you can access the file as determine the original filename of the uploaded file. the name of the file. To avoid errors, you should make sure that the specified
you would access any other file on the Web server. The size index name returns the file size, in bytes. directory exists on the Web server before attempting to save the uploaded file.
To determine the file type, you specify the type index
To determine the temporary filename of the uploaded file, name. Some Web browsers may not allow you to Example:
you must access the $HTTP_POST_FILES array, which is determine the file type. $tempFile = $HTTP_POST_FILES['uploadedFile']['tmp_name'];
an associative array that stores information about the $destination = "c:\\uploads\files\\" .
$HTTP_POST_FILES['uploadedFile']['name'];
copy($tempFile, $destination);

PROCESS AN UPLOADED FILE

⁄ To access information ¤ Between the first set of › To save a permanent ˇ Between the parentheses, Á To use the original ‡ Type the code that uses ■ After a user uploads a file ■ The file is also
about a file uploaded brackets, type the name used copy of the uploaded file, repeat steps 1 to 3, except filename to store the copy the accessed information to the Web server using a form, permanently saved
to the Web server, type to identify the uploaded file type copy(). type the tmp_name index of the uploaded file, type about the uploaded file. the PHP page will be able to on the Web server.
$HTTP_POST_FILES[][]. enclosed in single quotation name, enclosed in single a comma and then repeat process the file and display the
marks. quotation marks, in the steps 1 to 3, except type the ° Save the page with the result of accessing information
second set of brackets to name index name, enclosed
.php extension. about the uploaded file.
‹ Between the second set of access the temporary name in single quotation marks, in
brackets, type the index name of the file. the second set of brackets.
of the information you want
to access enclosed in single
146 quotation marks. 147
PHP MANAGING COOKIES AND SESSIONS 7
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.
CREATE AND READ A COOKIE Example:
header("Set-Cookie: accessedBefore=Yes; expires=Friday, 07-Mar-2003 00:00:00 GMT;");

P
HP pages can be used to create and read cookies. allows the cookie to store information for longer periods
When a user accesses a page that creates a cookie, of time. The time function can be used to set the expiry To prevent unauthorized pages from reading a cookie you placed
the cookie is typically stored as a small text file on time, in seconds, for a cookie. on a user's computer, you can specify a path and domain for the
the user's computer. The cookie can later be read by a PHP cookie in the setcookie function. Only the pages stored in the
page to access the information stored in the cookie. For After creating a cookie, you can have a PHP page read
the cookie. When a user with a cookie stored on their specified directory and domain will be able to read the cookie.
example, a cookie can store a user's name. When the user
accesses the PHP page again later, the page can use the computer visits a PHP page that can read the cookie, PHP Example:
value stored in the cookie to display the user's name. automatically converts the name of the cookie to a variable setcookie("accessedBefore", "Yes", time() + 3600, "/web/text", "www.test.com");
and assigns the value stored in the cookie to the variable.
To create a cookie, you use the setcookie function. This makes it easy to work with cookies using PHP. To read
If a PHP page attempts to access a variable that does not exist, an
The function takes several arguments, including the name a cookie stored on a user's computer, you simply access
error will be generated. You may want to use the isset function
you want to assign to the cookie, the value you want the the cookie variable by prefixing the name of the cookie
to verify that a cookie variable exists before attempting to access
cookie to store and an expiry time for the cookie. The with a dollar sign ($).
the variable in a PHP page.
setcookie function must be placed before any other
code on a PHP page. When working with cookies, keep in mind that a client Example:
may be configured to reject cookies or may be located if (isset($cookieValue))
By default, a cookie will be deleted when the user closes behind a security firewall that filters out cookie {
their Web browser. Setting an expiry time for a cookie information. print "A cookie exists on your computer";
}

CREATE A COOKIE READ A COOKIE

⁄ To create a cookie, type setcookie(). ‹ To specify when ˇ Display the PHP page ■ The cookie is now stored ⁄ In the PHP page, type $ ¤ Type the code that ‹ Display the PHP page ■ The Web browser
the cookie will in a Web browser. on the computer. followed by the name of the uses the value of the in a Web browser. displays the result of
¤ Between the parentheses, type expire, type a comma cookie you want to read. cookie. reading a cookie.
a name for the cookie enclosed in followed by time().
quotation marks. Then type a comma
followed by the value you want to › Type + followed
assign to the cookie enclosed in by the expiry time
quotation marks. for the cookie in
seconds.
148 149
PHP MANAGING COOKIES AND SESSIONS 7
DELETE A COOKIE
If you want to make changes to a cookie you have previously

P
HP allows you to delete a cookie before it expires. When deleting a cookie, the value you assign to the created, you must delete the cookie and then recreate the
This is useful if you no longer need the information cookie can be an empty string. If you specified a path and cookie using the new information. The process of deleting
in the cookie. For example, you may want to delete domain when you created the original cookie, you must and then recreating a cookie differs depending on the version
a cookie that contains user registration information if the specify the same path and domain when deleting the of PHP you are using.
user cancels their registration to your Web site. cookie. This ensures that the correct cookie is removed.
For information about specifying a path and domain for
It may also be necessary to remove cookies if you already PHP Version 4 PHP Version 3
a cookie, see the top of page 148.
have the maximum number of cookies allowed, but want
When using PHP version 4, cookies you create When using PHP version 3, cookies you
to create more. PHP permits each domain to store up to Working with cookies is not always a simple task. Some
and delete using the setcookie function are create and delete using the setcookie
20 cookies. You can delete cookies you no longer need Web servers and Web browsers work with cookies in
processed in the order they appear in the PHP function are processed in reverse order. To
to make room for new cookies. different ways. For example, some Web servers will not
script. To delete and then recreate a cookie, delete and then recreate a cookie, you must
allow a cookie to be removed from a client computer until
To remove a cookie, you use the setcookie function to you must place the setcookie statement place the setcookie statement that recreates
the cookie reaches its original expiry time. When working
create a new cookie that has the same name as the cookie that deletes the cookie before the setcookie the cookie before the setcookie statement
with cookies, you should thoroughly test your code on
you want to remove, but has an expiry time set as a time statement that recreates the cookie. that deletes the cookie.
all Web browsers you expect to access your PHP page.
in the past. For example, you can use the time function Example: Example:
to set the expiry time as a negative number of seconds,
setcookie("status", "", time() - 60); setcookie("status", "approved", time() + 3600);
such as time() - 60. This will cause the cookie to expire setcookie("status", "approved", time() + 3600); setcookie("status", "", time() - 60);
immediately. The setcookie function must be placed
before any other code on a PHP page.

DELETE A COOKIE

⁄ To delete a cookie, ¤ Between the ‹ Type a comma and › To specify an expiry ˇ If you specified a path Á If you specified a domain ‡ Display the PHP page ■ The cookie has been
type setcookie(). parentheses, type the then type "" to enter an time in the past, type a for the cookie when the for the cookie when the in a Web browser. deleted from the computer.
name of the cookie you empty string for the value comma and then type cookie was created, type cookie was created, type
want to delete enclosed of the cookie. time() - followed by a a comma and then type a comma and then type
in quotation marks. number of seconds. the path enclosed in the domain enclosed in
quotation marks. quotation marks.

150 151
PHP MANAGING COOKIES AND SESSIONS 7

START A SESSION PHP typically stores session information in


a directory on the Web server. The name
and location of this directory is specified
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
session is created for each user that requests a PHP The Web server keeps track of each session by assigning by the session.save_path value in the you can use as identifiers in your code. The session

A 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
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
php.ini configuration file. You should check
to make sure the directory exists before
starting a session. If the directory does not
ID must be enclosed in quotation marks and placed
within the parentheses following the session_id
function. You should use only alphanumeric
Web server. For example, if a user specifies a user name on requests another page from the site, the user's Web browser exist, you can create it. For example, if the characters when specifying a session ID.
the main page of a Web site, this user name can be used sends the session ID to the Web server to identify the user. php.ini configuration file specifies /tmp as
Example:
by the Web server to personalize any other Web pages the To access the current session ID using a PHP page, you type the session.save_path value, you can
user requests during that session. $PHPSESSID. session_id("User593204");
create a directory named tmp in the main
directory on the Web server.
To start a session in a PHP page, you use the Session IDs are randomly generated by the Web server.
session_start function. The session_start function You should not use the session ID as a unique identifier, You can also use the session_id function
must be placed before any HTML code on your PHP page. such as the primary key in a database, as the session ID You can change the name of the cookie used to access the session ID instead of using the
It is also good programming practice to start a session at the may not always be unique. For example, if the Web server to store the session ID number by changing PHPSESSID cookie. Before using the session_id
beginning of your PHP page so that session information is is restarted, the server may assign a user a session ID that PHPSESSID in the session.name value function, you should call the session_start
available throughout the page. Calling the session_start was previously assigned to a different user. in the php.ini configuration file on the Web function to indicate that you will use session
function while an existing session is in progress will not server. Using a unique session.name information.
create a new session or affect the existing session. value helps to increase the security of your
Example:
PHP pages.
print session_id();

START A SESSION ACCESS THE SESSION ID


Access a Session ID - Microsoft Internet Explorer

⁄ To start a session, ■ The session_start ¤ Display the PHP ■ The session is started. ⁄ Type $PHPSESSID ¤ Type the code that will ‹ Display the PHP page ■ The Web browser
type session_start(). function should be placed page in a Web browser. where you want to access display the session ID in a in a Web browser. displays the result of
before any HTML code on a session ID. Web browser. accessing the session ID.
your PHP page.

152 153
PHP MANAGING COOKIES AND SESSIONS 7

CREATE AND READ A SESSION VARIABLE All session variables and the information stored in them You can use the session_unregister
will be discarded when the session ends or is terminated. function to remove a session variable you
s a user moves through the pages in your Web site, value assigned to a session variable in any PHP page.

A 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
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.
If necessary, you can use cookies or a database to save
the information stored in a session variable.
created in the current session.
Example:
session_unregister("userName");
this information and make the information available to The session_is_registered function can be used
all the pages viewed by the user in your Web site. This The session_start function should be called at
the beginning of every PHP page that will use session to determine if a variable has been registered as a session
saves the user from having to repeatedly enter the same variable. The function will return a value of true if the
information to display each page during a session. information. Calling the session_start function To remove all the session variables that
will have no effect if a session is already in progress. variable has been registered in the current session.
have been created for the current session,
You use the session_register function to specify If the session_register function is used before Example: you can use the session_unset
the name of the variable you want to create. The name of the session_start function is called, a session will if (session_is_registered("userName")) function. The session will remain open
the session variable must be enclosed in quotation marks. be started automatically. { after you use the session_unset
Once the session variable has been registered, you can print "The user name has been registered."; function, but the variables created during
assign a value to the variable. The information stored in The use of session variables is an effective way of }
collecting and accessing information across multiple else the session will no longer be available.
a session variable can come from sources such as forms, {
databases and cookies. pages on a Web site and is more secure and easier Example:
to maintain than HTML hidden fields or cookies. print "The user name does not exist in this Web site.";
session_unset();
}
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 READ A SESSION VARIABLE

⁄ To create a session variable, ‹ Type $ followed by the › Display the PHP page ■ The session variable ⁄ In the PHP page ¤ Between the parentheses, › Display the PHP page ■ The Web browser
type session_register(). name of the session variable. in a Web browser. is now stored on the where you want to read type the name of the session in a Web browser. displays the result of
Then type = followed by the computer. information stored in a variable you want to read, reading a session variable.
¤ Between the parentheses, value you want to assign to session variable, type enclosed in quotation marks.
type a name for the session the session variable. session_register().
variable, enclosed in quotation ‹ Type the code that uses
marks. ■ String values must be the value of the session
enclosed in quotation marks. variable.
154 155
PHP MANAGING COOKIES AND SESSIONS 7

SAVE SESSION INFORMATION TO A FILE Saving session information to a file is an effective Saving session information to a file
way of storing relatively small amounts of session can be used in conjunction with, or as
ession information you store in session variables will The encoded session information saved in a file includes

S 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
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
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
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
been created will be lost. If you want to be able to access new session that has a different session ID. For example, of storing session information. In order to store users may disable cookies in their Web
session information after a session has ended, you can saving session information makes it easy to transfer the session information in a database, your Web browsers.
save the session information to a file. This is useful when information between multiple Web servers used by the server must have database capabilities.
you want to be able to restore the information for a client same Web site. When a user accesses a different Web
at a later time. server on the Web site, the session information saved in
a file can be passed to the new Web server with the client, If you do not want the file that stores session
To save session information to a file, you use the maintaining continuity even though a new session has information to be overwritten each time a client
session_encode function to encode the information been started on the second server. visits the PHP page, you can append data to the
for the session in a string. After encoding the session file. This is useful when you want to store session
information, you can write the string returned by the After saving session information to a file, you can have information for multiple users in a single file. To
function to a file. You must use the fopen function to a PHP page restore the session information from the file. access the information for a particular session
open the file and use the fputs function to write the For information about restoring session information from later, you can search the file for a unique identifier
encoded session information to the file. For more a file, see page 158. for the information.
information about writing data to a file, see page 124.

SAVE SESSION INFORMATION TO A FILE

⁄ Type the code that ■ For information about ¤ To be able to store the ‹ To encode the session › Type the code that ˇ Type the code that Á Display the PHP page ■ The session information
creates the session variables creating session variables, encoded session information information in a string, writes the string returned closes the file. in a Web browser. has been written to the file.
you want to use to store see page 154. in a file, type the code that type session_encode(). by the session_encode
session information. opens the file for writing. function to the file.

156 157
PHP MANAGING COOKIES AND SESSIONS 7
If you use the session_decode function Session information stored in a file is encoded
RESTORE SESSION within another function, the scope of the
session variables restored from a file will be
in a format that is easy to read and understand.
You can open the file that stores session
limited to that function. If you want to be information in a text editor or word processor
INFORMATION FROM A FILE able to use the session variables outside the
function, you must use the global keyword
to view the session information before restoring
the information in a PHP page. Viewing session
ou can have a PHP page restore session information contains the session information you want to restore from to give the session variables returned by the information can be useful for troubleshooting

Y 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
the file. For more information about the fgets function,
see page 126.
When session information is restored from a file, the
session_decode function global scope.
Example:
function getname()
session-related problems.
Example:
userName|s:4:"Paul";location|s:8:"New York";
variables containing a user's login information to a file, {
you can restore the information when the user begins a session variables stored in the file are automatically $fp = fopen("sessionInfo.txt", "r");
new session. This saves the user from having to re-enter available to the PHP page. This means that you do not global $userName, $location;
the information each time a new session is started. need to recreate the variables in the page. session_decode(fgets($fp, 4096));
fclose($fp);
Restoring session information from a previous session After storing session information in a file, a new }
does not alter the session ID for the current session. session must be started before the session information
To restore session information from a file, you first open can be restored from the file. You should use the
the file for reading using the fopen function. For more session_start function on a PHP page that restores As with any file you want to access from
information about opening a file for reading, see page 126. session information to start a new session. The within a PHP page, the file that stores
The session_decode function can then be used to session_start function must be placed before any session information you want to restore
decode and restore the session information from the file. HTML code on the PHP page. For more information must have the appropriate file and operating
The session_decode function takes a string of text about the session_start function, see page 152. system permissions in order for you to
containing encoded session information as its argument. retrieve information from the file. For more
You can use the fgets function to retrieve the string that 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 ¤ To restore the session ‹ Between the parentheses, › Type the code that ˇ Type the code that uses Á Display the PHP page ■ The Web browser displays
contains the session information stored in the type the code that uses the closes the file. the session information in a Web browser. the result of restoring session
information you want to file, type session_decode(). fgets function to retrieve the restored from the file. information from a file.
restore, type the code that information stored in the file.
opens the file for reading.

158 159
PHP DEMYSTIFYING OBJECTS 8
USING OBJECTS IN PHP The key difference between traditional and object-oriented One of the benefits of object-oriented
nlike C++ and Java, PHP is not a true object-oriented variable to create a dir object. The dir class is a built-in programming is the way data and the functions that process programming is known as data hiding, or the

U language; however, PHP does support object-oriented


programming concepts that allow programmers to
write code in an object-oriented fashion.
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,
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
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
you must include the new keyword. For more information
Objects, which are packages of code composed of data and about defining and using classes, see page 162. be designed as a single program containing customer access the class, not the internal workings
functions that make use of the data, are the core features of information, item inventory and shipping functions. A slight of the class. Data hiding is often used in
object-oriented programming. In PHP, an object's members, Once you create a new object, you can access the properties change made to one portion of the program may greatly programs to protect classes from tampering
or properties, are made up of the data for the object. An and methods of the object. For example, the path property affect the rest of the program, which can make the program and to ensure that the methods of the classes
object also has member functions, or methods, that are used of the dir object contains the path to the directory specified difficult to manage. Using object-oriented programming, are used are originally intended. A programmer
to manipulate the object. when the object was instantiated. The read method returns however, allows you to structure and organize code in your can modify and maintain the code within the
the names of the files in the directory one at a time. The applications into distinct modules, or objects. The variables class without affecting the programs that use
A class is PHP code that serves as a template for creating an close method is used to close the directory once all the and functions that deal with a specific feature, such as the class. This also helps ensure that objects
object, which is also referred to as an instance of the class. files have been retrieved. shipping, can be maintained separately from the other developed by multiple people are compatible.
It is possible to create many objects using the same class. components. This can make the application easier to
Once created, each object can operate independently from To access an object's properties and methods, you use the manage, especially if there are multiple programmers
other objects. variable that represents the object followed by the member working on the same application.
access operator (->). You then indicate the property or
To create a new object, you assign a new instance of a class method you want the object to access.
to a variable. For example, you can assign the dir class to a

USING OBJECTS IN PHP

⁄ To create an object, ‹ Between the parentheses, › To access a property of ˇ Type the name of Á To call a method of the object, ° Repeat steps 6 and 7 ‚ Display the PHP page ■ The Web browser
type a variable name for type any arguments needed the object, type the name the property you want type the name of the variable that for each method you in a Web browser. displays the result of
the object followed by =. to create the object. of the variable that contains to access. contains the object followed by –>. want to call. using the properties
the object, followed by –>. and methods of an
¤ Type the name of the Note: In this example, the path of ■ Repeat steps 4 and 5 ‡ Type the name of the method · Type the code that object.
class that you want use the directory is included as an for each property you you want to call followed by (). uses the accessed
to create the object, argument. want to access. properties and the called
followed by (). ■ Type any arguments for the methods of the object.
method between the parentheses.
160 161
PHP DEMYSTIFYING OBJECTS 8

DEFINE A CLASS When assigning an initial value to a property of


an object, you must indicate a literal value. An
Although PHP allows you to set the property
of an object using the assignment operator (=),
ou may define a class that will serve as a template you assign to the property can be any data type, such as error will occur if you attempt to set the initial this practice is not recommended and should

Y 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
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
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
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
letters, numbers or underscore characters. Class names class definition.
are case-insensitive, but it is good programming practice use a method to assign the value to the may cause an object to work improperly.
to use a consistent format for naming classes you define. Once a class has been defined, you can create an object property. The following example shows
from the class. You create a variable to store the object property declarations that will cause errors.
The name of the class is followed by a pair of braces {}. and then use the new keyword followed by the name of
Example:
The code between the braces is referred to as the body of the class to create an object.
class Fruit
the class and may consist of properties, which are the data
You can also access the properties of the class in the {
for the object, and methods, which are the structures that var $name = "Granny" . "Smith";
contain the code for specific actions. For information about object. To access the properties, use the variable that
var $type = $name;
defining methods, see page 164. represents the object followed by the member access var $soldOn = time();
operator (->). You can then indicate the property you var $quantity = 1 + 1;
You can define properties for a class you create by using want to access. When accessing a property, the property }
the keyword var followed by a name for the property name must be typed exactly as it was specified in the
preceded by a dollar sign ($). You may then assign an initial class definition, without the dollar sign ($).
value to the property or leave the property unset. The value

DEFINE A CLASS

⁄ Type class followed by ¤ To define a property of › Repeat steps 2 and 3 CREATE AN OBJECT ACCESS PROPERTIES · Type the code that — Display the PHP page ■ The Web browser
the name of the class you the class, type var followed for each property you USING A CLASS OF AN OBJECT uses the accessed in a Web browser. displays the result of
want to create. Then type by $ and the name of the want to define. ˇ Type the variable name ‡ Type the name of the property. defining and using a
the opening and closing property. for the object followed by =. variable that contains the class.
braces for the class. object followed by –>.
‚ Repeat steps 7 to 9
‹ To assign a value to the Á Type new followed by for each property you
property, type = followed the name of the class you ° Type the name of the want to access.
by the value you want to want to use to create the property you want to
162 assign. object. access. 163
PHP DEMYSTIFYING OBJECTS 8
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
DEFINE A METHOD 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.

A
fter defining a class, you can define the methods The body of a method is enclosed in braces {}. Within the
TYPE THIS: RESULT:
for the class. You can use methods to perform any body of a method, you can use the special variable $this
number of tasks that relate to an object. For example, to set or access the value of a property. The special variable class Fruit Fruit: apple
you may want to define a method that sets the properties $this is followed by the member access operator (->) { Fruit: mango
var $name;
of an object or displays the current values of the object's and the name of the property. To set a new value, you then var $color;
properties. include the assignment operator (=) followed by the new var $saleDate;
value for the property. function Fruit($name, $color)
A method is created using the function keyword followed {
by the name of the method and a set of parentheses. You Similar to functions, methods may return a value using a $this->name = $name;
can set up a method to accept arguments. In the function return statement. When accessing a property of an object, $this->color = $color;
statement, you define one or more variables between the you would ideally use a method that returns the value of the $this->saleDate = time();
parentheses that follow the method name. Each variable property rather than referring to the property directly. This }
represents an argument you will pass to the method. You practice of accessing the properties of an object through a function PrintName()
{
can use the variables you create in the function statement method does not have to be strictly adhered to, but it is a print "<b>Fruit:</b> " . $this->name . "<br>";
within the body of the method. When specifying the more proper way of writing object-oriented programs. }
arguments of a method, you may specify a default value }
for an argument of the method. You use the assignment $fruitObject = new Fruit("apple", "red");
operator (=) to assign a default value to the argument. $fruitObject->PrintName();
$fruitObject->Fruit("mango", "green");
$fruitObject->PrintName();

DEFINE A METHOD

⁄ Type the code that ‹ To allow the method to ˇ Type the opening and Á To have the method ‡ To define a method ° To have the method · Repeat steps 2 to 5 for ■ You can now call
defines a class. accept arguments, type the closing braces of the method set the value of a that accesses properties access the value of a any other methods you want a method in the PHP
names of the variables you want body. The code you want the property, type $this–> of the class, repeat property, type $this–> to create. script. See page 166
¤ To define a method, type to store the arguments. Separate method to execute is placed followed by the name of steps 2 to 5. followed by the name of to call a method.
function followed by the each argument with a comma. between the braces. the property. Then type = the property you want to ‚ To return a value from a
name of the method you followed by the value or access. method, type return in the
want to define. Then type (). › To set a default value for an variable you want to use. body of the method, followed
argument, type = followed by the by the information you want
164 default value after the argument. the function to return. 165
PHP DEMYSTIFYING OBJECTS 8
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,
CALL A METHOD 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

A
fter creating an object in your script, you can call The special variable $this must be used when calling
the object's methods. Calling a method tells PHP a private method within the body of another method. dynamically access an object's property or call an object's method.
to access and execute the code in the method. The special variable $this is followed by the member
TYPE THIS: RESULT:
access operator (->), the name of the method and a set
To call a method, you type the name of the object followed of parentheses. You may place any required arguments class Fruit Red Apple
by the member access operator (->) and the name of the between the parentheses. {
method where you want to execute the code. The method var $name;
name is followed by a set of parentheses. If the method was Unfortunately, PHP does not make any distinctions var $color;
set up to accept arguments, you specify the arguments you between the different methods that you define. There function Fruit($name, $color)
{
want to pass to the method between the parentheses. is no mechanism in PHP that will allow you to restrict the $this->name = $name;
access of certain methods to within the class itself. This $this->color = $color;
A method can be accessed from within the body of another makes it possible to misuse code. To help avoid misuse, }
method in the class definition. This is useful for defining a you should include clear, descriptive comments in your function GetProperty($propertyName)
method that is to be used only within the class itself, such code to label private methods so they are not used outside {
as a method used to perform internal calculations. This the class definition. return $this->$propertyName;
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 $fruitObject = new Fruit("Apple", "Red");
print $fruitObject->GetProperty("color") . " ";
methods containing a large amount of code, which improves
print $fruitObject->GetProperty("name");
the readability of the code.

CALL A METHOD

⁄ Type the code that ¤ Type the code that ‹ To call a method of the › Between the parentheses, Á To call a private method ° Type the code that ‚ Display the PHP page ■ The Web browser displays
creates a class and its creates an object. object, type the name of type the arguments you within another method of the uses the result of calling in a Web browser. the results of calling the
methods. the object followed by –>. want to pass to the method. class, type $this–> followed by the private method. methods of an object.
Then type the name of the Separate each argument with the name of the method. Then
method followed by (). a comma. type (). · Repeat steps 6 to 8
for each private method
ˇ Repeat steps 3 and 4 for ‡ Between the parentheses, you want to call.
each method you want to call. type the arguments you
want to pass. Separate each
166 argument with a comma. 167
PHP DEMYSTIFYING OBJECTS 8
A class you defined as a child class can be used It is good programming practice to design
as the parent class of another class. This allows classes so they perform only a general set
you to create a chain of child classes and parent of tasks. Specialized methods can then be
EXTEND A CLASS classes. Although there is no limit to the number
of child classes that can be created from other
added by extending the parent class. This
prevents the parent class from becoming
child classes, you should try to limit the chain of bloated and maximizes the re-usability of

I
f a class you are defining is related to a class you have a constructor method must be defined for the child class. extensions to prevent your code from becoming code while maintaining the code's speed
previously defined, you can make the new class an In the constructor method of the child class, you must call too confusing. You should also place information and efficiency. When a class becomes too
extension of the original class. This allows you to re-use the constructor method of the parent class using the special about the parent class in the child class definition large, more memory and resources are
properties and methods of the original class without having variable $this and indicate the appropriate arguments. For to prevent potential conflicts from occurring. used by an object of the class. Extending
to retype the code in the new class. When you extend a more information about the constructor methods, see the a class also maintains the integrity of the
class, the base class is usually referred to as the parent class, top of page 165. Example:
parent class. This ensures that new
while the new class is called the child class. class Spread extends Fruit
When creating a child class, you can override a method in {
modifications will not have any adverse
When defining a class you want to use as a child class, you the parent class that you do not want to be available when // Inherited from Fruit effects on the rest of the program.
must use the extends keyword to specify the name of the the child class is accessed. To override a method in the // Properties: name, color
class that will act as the parent class. When the child class parent class, you must create a method in the child class // Methods: Fruit, PrintMessage
. . .
is used to create an object, the resulting object inherits the that has the same name as the method you want to override. }
properties and methods of the parent class in addition to When an object is created using the child class, the method
any new properties and methods indicated in the child class. in the child class will be available instead of the method in class Sandwich extends Spread
the parent class. {
If the parent class has a constructor method, the constructor // Inherited from Fruit and Spread
method is not automatically called when a new instance // Properties: name, color, type
of the child class is created. If you want the constructor // Methods: Fruit, PrintMessage
method to execute for each instance of the child class, . . .
}

EXTEND A CLASS

⁄ Type the code that defines ‹ In the class definition, › To call the constructor ˇ Enclose any Á In the child class, you ‡ Type the code that · Display the PHP page ■ The Web browser
a class you want to be able to type extends followed by method of the parent class arguments for the may define a method that creates an object using in a Web browser. displays the result of
extend to another class. the name of the class you within the constructor method method in parentheses. overrides one of the methods the child class. creating an object
want to use as the parent of the child class, type $this–> in the parent class. of a child class and
¤ Type the code that defines class. followed by the name of the ° Type the code that accessing its methods.
a class you want to use as an constructor method from the Note: The method must have the calls a method of the
extension of another class. parent class. same name as the method in the object.
parent class that it overrides.
168 169
PHP DEMYSTIFYING OBJECTS 8

WORK WITH EXTERNAL DATA IN CLASSES You can place a class definition in an include
file to make the class accessible to multiple
As the complexity of your Web site increases, you
may find it more practical to use include files to
PHP pages. You can name the include file organize constants, functions and classes used
class can access functions, constants and variables You can also access variables that are defined outside a

A 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
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
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
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
method is not practical, such as when you want to process
called in a method by simply specifying the name of the within the <?php and ?> delimiters. As for constants first, followed by the include files for
an undetermined number of values from a form.
function and any arguments the function requires. This is with functions, classes can be declared only functions and then the include files for class
useful when you already have a library of useful functions You should keep in mind that a class becomes less portable once in a script. To include a class file in a definitions.
that you do not want to retype as private methods of a when it is dependent on external data. You should use script, you can use the include_once
Example:
class. Some functions also will not work properly if they external data only when necessary. When using external statement.
// Constants
are within a class definition. For example, when using data, you may also want to place comments in the class Example: include_once("color_constants.inc");
the usort function in a method, you need to pass a definition to indicate how constants, global variables or include_once("font_constants.inc");
include_once("Fruit.inc");
comparison function located outside of the class definition functions are being accessed. Comments will help avoid include_once("Vegetable.inc");
as an argument for the comparison function to be used confusion and make potential problems easier to track. // Functions
properly. include_once("text_formatting_functions.inc");

To access a constant defined outside the class definition, // Classes


you need to specify only the name of the constant. The include_once("Fruit.inc");
include_once("Vegetable.inc");
constant definition must be placed before the class
definition in the PHP script.

WORK WITH EXTERNAL DATA IN CLASSES

⁄ Type the code that ‹ To call a function created ˇ Repeat steps 3 and 4 for ‡ Type the code that ° To access a variable ‚ Type the code that — Display the PHP page ■ The Web browser
creates any constants, outside the class definition, each function you want to uses the constant. defined outside the class creates an object and in a Web browser. displays the result of using
variables and functions type the name of the call in the class. definition, type global calls a method of the external data in a class.
that will be used in a class. function followed by ( ). followed by the name object.
Á To use a constant defined of the variable.
¤ Type the code that › Between the parentheses, outside the class definition,
defines a class. type any arguments for the type name of the constant. · Type the code that
function. uses the variable.
170 171
PHP DEMYSTIFYING OBJECTS 8

GET INFORMATION ABOUT AN OBJECT 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

P
HP provides several functions that allow you to obtain object you want to check. The get_object_vars function
information about an object. You can use the functions returns an associative array containing the object's properties, whose values are the default property values. Properties that do
to examine the attributes of an object without having including any properties inherited from parent classes. The not have a default value specified are not included in the array.
to manually read through its class definition. This can save keys of the array contain the property names and the values
TYPE THIS: RESULT:
you time and effort, especially if you are working with of the array contain the current values of the properties.
include files. You can also use the functions to automate Properties that do not have an assigned value are not class Fruit Default property values of Fruit:
some tasks, such as generating documentation for your returned in the array. { name is apple
var $name = "apple";
programs. This can help you avoid conflicts when naming var $color = "red";
color is red
methods and properties. To obtain the methods of an object, use the size is large
get_class_methods function. To use the var $size = "large";
var $onSale;
You can use the get_class function to obtain the class get_class_methods function, you need to specify the }
name of an object. The get_class function takes the name of the class from which you want to get the list of $fruitObject = new Fruit;
variable that contains the instance of the object you want methods. If you do not know the class name, you can use print "<b>Default property values of Fruit:</b><br>";
to check as its argument. The function returns the name the get_class function to determine the class name of the foreach(get_class_vars("Fruit") as $propertyName => $defaultValue)
of the class the object belongs to. object and then use the result in the get_class_methods {
function. The get_class_methods function returns an print "$propertyName is $defaultValue<br>";
You can obtain a list of the properties of an object by using array of methods in the specified class, including any
}
the get_object_vars function. To use this function, you methods inherited from parent classes.
must specify the variable that contains the instance of the

GET INFORMATION ABOUT AN OBJECT

⁄ Type the code that ‹ Between the parentheses, ˇ To determine the ‡ Type the code that uses ° To determine the ■ If you do not know the — Display the PHP page ■ The Web browser
defines a class and creates type the name of the object properties of an object, the get_object_vars methods of an object, name of the class, use the in a Web browser. displays the results of
an instance of the class. you want to check. type get_object_vars(). function. type get_class_methods(). get_class function as retrieving information
the argument. about the object.
¤ To determine which › Type the code that uses Á Between the parentheses, · Between the
class an object belongs to, the get_class function. type the name of the object parentheses, type the ‚ Type the code that uses
type get_class(). you want to check. name of the class from the get_class_method
which the object was function.
172 instantiated. 173
PHP DEMYSTIFYING OBJECTS 8
The is_subclass_of function is used created using a child class of the specified
to determine if an object was created using parent class, the function will return a value
CHECK FOR CLASSES AND a child class of a specified parent class.
The is_subclass_of function takes
of true. The parent class being checked does
not have to be an immediate parent of the

METHODS IN A SCRIPT two arguments––the name of the variable


that stores the object and the name of the
parent class you want to check, enclosed
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.
in quotation marks. If the object was

T
here are several functions available that you can classes in mind so you do not inadvertently define any
use to check for the presence of classes and classes with the same name as the built-in classes.
TYPE THIS: RESULT:
methods in your script. These functions are useful
for troubleshooting large, complex PHP scripts. Using You can use the class_exists function to check if class Spread extends Fruit Fruit is a parent of Spread.
functions to test for certain conditions can save you a particular class has been defined in the script. When {
from having to examine every line of code in a script. using the class_exists function, you must specify var $type;
the name of the class you want to check, enclosed in function Spread($name, $color, $type)
The get_declared_classes function is used to quotation marks, as an argument. The class_exists {
$this->Fruit($name, $color);
determine the classes that are currently being used function will return a value of true if the specified class $this->type = $type;
in the script. There are no arguments required when has been defined in the script. }
calling the get_declared_classes function. The }
get_declared_classes function returns an array The method_exists function is used to determine $spreadObject = new Spread("apple", "red", "jelly");
containing the names of the classes being used in the if a particular method belongs to an object. The if (is_subclass_of($spreadObject, "Fruit") == TRUE)
script. method_exists function takes two arguments––the {
name of the variable that contains the object and the print "Fruit is a parent of Spread.";
When viewing the array elements returned by the name of the method you want to check, enclosed in }
get_declared_classes function, you may see quotation marks. The method_exists function will return else
{
classes that you have not defined. These are built-in a value of true if the specified method is part print "Fruit is not a parent of Spread.";
classes in PHP. You may want to keep these built-in of the class used to create the object. }

CHECK FOR CLASSES AND METHODS IN A SCRIPT

⁄ Type the code that ¤ To get a list of classes › To check if a class has been Á Type the code that ‡ To check if a specific · Type the name of the — Display the PHP page ■ The Web browser
defines a class and creates used in the script, type defined, type class_exists( ). uses the class_exists method exists in an object, method you want to check, in a Web browser. displays the results of
an instance of the class. get_declared_classes(). function. type method_exists(). enclosed in quotation marks. checking for classes and
ˇ Between the parentheses, methods in the script.
‹ Type the code that uses the type the name of class you ° Between the parentheses, ‚ Type the code that uses
get_declared_classes want to check, enclosed in type name of the object the method_exists
function. quotation marks. followed by a comma. function.
174 175
PHP WORK WITH DATABASES 9

INTRODUCTION TO DATABASES TYPES OF DATABASES


ne of the most useful features of PHP is the ability PHP page, the information in the PHP page will be created

O 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
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
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
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
visit your Web site. you to access data quickly, but manipulating the data may is commonly used with flat file, hierarchical and
pages to access that information is an efficient method of be difficult. A database with a more complex structure relational databases.
Instead of storing information in text files or static Web displaying up-to-date information in a Web site. allows you to easily manipulate data, but requires more
pages, a PHP page can be set up to retrieve, format and
display data from a database. When a user accesses the

Flat File Databases


DATABASE STRUCTURE When working with larger applications, a flat file
Flat file databases are the most basic database type. Flat
file databases have minimal structure and usually store database can be inefficient and difficult to maintain.
information in one large table, similar to a tab-delimited The simple structure of a flat file database makes it
Information in a database is made up of two category of information in a table, such as the first
text file. A flat file database is very easy to set up and is inadequate for storing complex relationships, resulting
components––raw data and meta-data. The raw data names of all your clients. A record is a collection of
in the duplication of information. Also, if your data
component of a database is the actual information information about one person, place or thing, such as ideal for creating simple Web applications that use small
storage requirements change, a flat file database can
being stored, such as the phone number of a client. the name and address of a client. More sophisticated amounts of data, such as an application that keeps track be very difficult to modify.
The meta-data component of a database determines the databases would also contain meta-data such as data of user preferences.
way the data is structured and organized. For example, types and the relationship between tables.
data in a database is usually organized into tables,
which consist of fields and records. A field is a specific
Hierarchical Databases
A hierarchical database organizes data into different Due to its rigid structure, manipulating data in
levels, similar to directories and sub-directories. This a hierarchical database can be very slow. Data
DATABASE MANAGEMENT SYSTEM (DBMS) organization makes data access fast and easy. You redundancy can also be problem. For example, if you
would typically use a hierarchical database to store organized customers by method of payment in a
large amounts of information that seldom need to hierarchical database, a customer who pays by both
To access and modify the data in a database, you write your own DBMS in PHP for a flat file database. cash and credit card would have two accounts. Data
need a program or set of programs called a DataBase You can also obtain a DBMS, such as MySQL or Oracle, be changed, such as contact lists or user directories.
redundancy makes hierarchical databases inefficient
Management System (DBMS). Depending on the type which is capable of handling more complex databases. Some of the hierarchical databases supported by PHP for certain applications.
of database you are using, the DBMS can be very use the Lightweight Directory Access Protocol (LDAP).
simple or very sophisticated. For example, you can This protocol was designed specifically for reading
data quickly. You can use PHP's LDAP functions to
access these types of databases.

ACCESSING A DATABASE
Relational Databases
Relational databases store information in separate information. A relational database is also faster and
The way you access a database depends on the type of you are using. For example, if you are using a MySQL tables. Each record in a table has a unique identifier, easier to maintain than other types of databases. You
database you are using. You can use PHP's Filesystem database, you would use PHP's MySQL functions. If or primary key, which can be used to form relationships would typically use a relational database when building
functions to directly access a flat file database. For other the database you are using does not have its own set with entries in other tables. Using relationships to bring dynamic database-driven Web sites with PHP.
types of databases, you must create a connection to the of functions, you can use PHP's Unified ODBC functions together information from different tables eliminates
database before you can access the database. To create to connect to the database. ODBC, or Open DataBase data redundancy. Relational databases are powerful,
a connection to a database, you use the set of PHP Connectivity, is a standard supported by many flexible and effectively store large amounts of
functions specifically written to work with the database databases.

176 177
PHP WORK WITH DATABASES 9

PLAN A DATABASE SELECT A DATABASE MANAGEMENT SYSTEM


ou should take the time to properly design a database, that is designed properly will be easier to modify and work

Y especially when working with a relational database


management system. A good database design ensures
that you will be able to perform tasks efficiently and
with as it grows. Good planning can also make it easier for
other users to work with a database you create. 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
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
accurately. As you add information to a database, the consider a number of factors, such as your budget and standards, moving data to a new system might be difficult.
database becomes larger and more complex. A database the volume of information the database will be required

Determine the Purpose of the Database Determine the Tables You Need MySQL Oracle
Decide what you want the database to do and how Gather all the information you want to store in MySQL is the database program most commonly Oracle is a powerful database program that is typically used
you plan to use the information. If other people will the database and then divide the information into used to develop database-driven PHP Web sites. with high-end Web servers on large commercial Web sites,
be using the database, you should consult with separate tables. A table should contain related MySQL is a fast, efficient program that is available such as sites that offer online shopping. Oracle is reliable,
them and consider their needs. This can help you information about one subject only. The same for use on Unix and Windows computers. MySQL provides advanced security, is highly scalable and includes
determine what information you need to include information should not appear in more than one is suitable for small to medium-sized projects powerful tools that you can use to manage your database.
to make the database complete. table in a database. You can work more efficiently and requires very few system resources to run. Oracle is available for both Unix and Windows computers.
and reduce errors if you need to update information MySQL is also an Open Source product, which For more information about the Oracle database program,
in only one table. means you can use it free of charge. Although you can visit the www.oracle.com Web site.
Security and Reliability MySQL is very powerful, it is relatively easy to
You should determine the level of security you install and manage. This makes it a good program
will need to protect the information the database Consider the Fields You Need for new developers to use when learning to work Microsoft SQL Server
will store. If the database will store sensitive Each field should relate directly to the subject with databases using PHP. More information Microsoft SQL Server is an industrial-strength DBMS that
information such as credit card numbers, you of the table. When adding fields, make sure you about MySQL is available at the www.mysql.com offers features that are comparable to Oracle. SQL Server
need to select a database system that is secure break down information into its smallest parts. For Web site. includes advanced features, such as OnLine Analytical
and reliable. To ensure maximum security, you example, break down names into two fields called Processing (OLAP) and data mining, which allow you to
may even want to create a separate database to firstName and lastName. work more efficiently with information in a large database.
store sensitive information. PostgreSQL SQL Server is only available for use with Windows systems.
Try to keep the number of fields in a table to a PostgreSQL is another popular DBMS used with For more information about SQL Server, you can visit the
minimum. For example, do not include a field PHP. Like MySQL, PostgreSQL is an Open Source www.microsoft.com/sql Web site.
Anticipate Future Needs containing data you can calculate from other fields. product that is freely available for personal and
Tables with many fields increase the time it takes commercial use, but PostgreSQL is a more
Decide on a naming convention for databases, to process information in a database.
tables and fields. Make sure names are concise and advanced system that supports almost all SQL Microsoft Access
descriptive to prevent confusion in case changes features. PostgreSQL is available for use only Microsoft Access is a database program that is useful for
need to be made in the future. If many people will Determine the Relationship Between Tables on Unix systems and is usually included with small to medium-sized applications. Access is available as
work with the database, you should also decide the RedHat distribution of the Linux operating a stand-alone product or as part of the Microsoft Office
on a method for documenting changes made to the A relationship tells a relational database how system. For more information about PostgreSQL, package. There are currently no built-in PHP functions that
database. For example, you can use a spreadsheet to bring together related information stored in you can visit the www.postgresql.org Web site. allow you to connect to an Access database from a PHP page,
program to keep track of the dates and times separate tables. You can use the primary key to so you must use PHP's Unified ODBC functions to connect.
changes were made and the name of the person form a relationship between tables. A primary key For more information about PHP's Unified ODBC functions,
who made the changes. is one or more fields that uniquely identifies each you can visit the www.php.net/manual/en/ref.odbc.php
record in a table. For example, the primary key Web site. Information about Access is available at the
for a table of employees could be the social www.microsoft.com/access Web site.
security number of each employee.

178 179
PHP WORK WITH DATABASES 9
SQL STATEMENTS
SQL is made up of many statements and clauses.
In order to work with a database in your PHP
INTRODUCTION TO scripts, you will need to be familiar with some
common SQL statements and how they are used.

STRUCTURED QUERY LANGUAGE CREATE TABLE SELECT


elational database management systems, such as Originally developed by IBM as a database query language

R 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
for use with mainframe computers, SQL was soon adopted
by many vendors for use with their relational database
management systems. Most relational database management
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.
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
database, the script must be able to communicate with the systems that have a client/server structure now support SQL. You also specify a description of each field that includes clause to specify the name of the table that stores the
database. Structured Query Language (SQL) is the language the data type of the field and other attributes, such as the data you want to retrieve. The WHERE clause specifies
used in a PHP script to communicate with a database. maximum number of characters the field can hold. The exactly which data you want to retrieve.
data types you specify will depend on the database you
Example:
are using. You should refer to the database documentation
SELECT invoiceNumber, totalCost FROM orders
for more information. WHERE totalCost > 100.00
Example:
Standardization Flexibility CREATE TABLE orders Result Set
(
SQL is the industry standard language for managing and The ability to easily manipulate data into many invoiceNumber INT(8), The SELECT statement returns data in a table format
manipulating data in a database. SQL can be used to useful forms makes SQL a very effective tool. SQL orderDetails CHAR(255), called a result set. The fields you specify make up the
work with many types of databases, which makes it easy allows you to easily format data you retrieve from totalCost FLOAT(9, 2) columns of the table and the information from each
to upgrade from one database management system to a database in a variety of ways. You can sort data ) field forms the rows. For example, when you issue a
another. For example, a small Web site might start out in a specific order, create summaries and combine SELECT statement that retrieves the invoice numbers
using MySQL but then grow large enough to require a information from different fields. This saves for orders totaling less than $100 from a table in a
INSERT
database created using Oracle. You have to learn only you from having to expend additional time and database, the result set will display a table with two
one language to have your PHP scripts communicate resources to format the retrieved data in PHP. The INSERT statement allows you to add records to a columns that show the invoice numbers and the
with both types of databases. database. The INSERT statement uses the INTO clause amounts.
to specify the name of the table to which you want to
Vendor Specifications add data and the names of the fields that store the data The SELECT statement allows you to access different
Ease of Use Although many of the basic concepts of SQL, in the table. The VALUES clause specifies the values you groups of data from one or more tables and display the
SQL uses many easy-to-understand commands, which such as selecting and inserting data, are common are adding. data in a single result set. You can indicate parameters
makes it a very simple language to work with. For to most database management systems, certain with the SELECT statement, such as a specific sorting
Example: order, to control the way the data is displayed in the
example, SQL uses the INSERT statement to add features may vary depending on the vendor of the INSERT INTO orders (invoiceNumber, totalCost)
information to a database and the DELETE statement system. For example, a database may include a result set.
VALUES (12843, 34.56)
to remove information. These plain-language commands unique set of commands that allow users to access
make it easy for you to read and determine the purpose information about a table. These commands may DELETE
of SQL code. not work for other databases since they are not UPDATE
part of the standard set of SQL statements. The The DELETE statement is used to remove data from
The UPDATE statement is used to modify data in a
types of information that a database can store a database. The DELETE statement uses the FROM
database. You indicate the table that contains the data you
Power may also vary depending on the vendor. clause to specify the name of the table that stores the
want to modify after the UPDATE statement. The UPDATE
Although SQL is easy to use, it is a very powerful data you want to delete. The WHERE clause contains
statement uses the SET statement to indicate which field
language. As well as being suitable for retrieving data information that uniquely identifies the data you want
needs to be changed and the new value. The WHERE clause
from a database and performing simple tasks such to delete.
is then used to specify the data to be modified.
as adding and deleting records, SQL can be used to Example:
Example:
perform complicated procedures, such as compiling DELETE FROM orders WHERE year < 1996
different types of data from multiple data sources. UPDATE orders SET totalCost = 55.66
WHERE invoiceNumber = 12843

180 181
PHP WORK WITH DATABASES 9
USING A DATABASE CLIENT 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
In addition to text-based client software,
most relational database management
systems also include a client that utilizes
so, you need to know the address of the server a Graphical User Interface (GUI). You can

T
he most popular relational DataBase Management SQL statements from a PHP script, this process is often more
Systems (DBMS) have a client/server architecture. difficult and time consuming than using the client software. and login information, such as a user name and use GUI client software to modify and
A client/server architecture allows multiple users to Typically, client software can also be used to perform password. If you are using an Internet Service administer a database without having to
simultaneously connect to a single database. Compared to administrative duties, such as adding users to the system, Provider (ISP) to run your PHP scripts, you will type SQL statements. This type of client
other database management systems, this type of system provided the correct access privileges have been granted. typically have access to a database server, software is much easier to use than a
is extremely cost effective and offers a high level of although there may be additional costs for the text-based client and can help you quickly
performance. When a DBMS is installed on a server, both the server and server's use. You can consult your ISP to obtain set up a database.
client software are installed. To access the server from a more information about connecting to the
The server component of the DBMS contains the actual remote computer, only the client software is required on database server.
database. The server software interprets commands from the computer. The operating system of some client
users and then manages the data in the database accordingly. computers may have to be altered in order to work properly
with the client software. For more information, consult the You may want to type your SQL statements
The client component of the system provides the interface documentation that came with your DBMS. Before using in a text editor and then copy and paste the
needed to work with the server. You can issue Structured the client software to work with a database, you must make statements into the client software. Typing
Query Language (SQL) statements from a text-based client sure that both the client and server software are running. long SQL statements directly into client
to perform tasks such as displaying a list of the databases It is a common error to launch the client software without software can be a slow and tedious process.
on the server, finding a list of the tables in a database or launching the server software first. If you make a mistake that generates an error,
viewing the contents of a table. you will have to retype the entire statement
again. When working in a text editor, you can
You can also use the client software that came with your easily edit your SQL statements and even
DBMS to set up a database. While it is possible to perform save the statements for later use.
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. Welcome to the MySQL monitor. Commands end with ; or \g. Type 'help;' or '\h' for help. Type '\c' to clear the buffer | students |
Your MySQL connection id is 7 to server version: 3.23.33 Your MySQL connection id is 7 to server version: 3.23.33 +--------------------+
mysql> SHOW DATABASES; 2 rows in set (0.06 sec)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer Type 'help;' or '\h' for help. Type '\c' to clear the buffer +--------------+
| Database | mysql> SELECT * FROM students;
mysql> SHOW DATABASES; mysql> SHOW DATABASES; +--------------+ +--------------+-------------+------------------+
+--------------+ | books | studentID | firstName | lastName |
| Database | school +--------------+-------------+------------------+
+--------------+ | shopping | 10293843 | Martine | Edwards |
| books | videos | 01298348 | Lindsay | Sandman |
| school +--------------+ | 10562940 | Sandy | Rodrigues |
| shopping 4 rows in set (0.00 sec) | 38290169 | Barry | Pruett |
| video +--------------+-------------+-----------------+
+--------------+ mysql> USE school; 4 rows in set (0.00 sec)
4 rows in set (0.00 sec) Database changed
mysql> CREATE TABLE teachers
mysql> SHOW TABLES;
-> (
mysql> USE school; +-------------------------+
-> teacherID CHAR(4),
Database changed | Tables_in_school |
-> firstName CHAR(20),
mysql> SHOW TABLES; +-------------------------+
-> lastName CHAR(25)
| courses |
-> );
| students | Query OK, 0 rows affected (0.05 sec)
+-------------------------+
2 rows in set (0.06 sec) mysql> INSERT INTO teachers (teacherID, firstName, lastName)
-> VALUES ("2323", "Maureen", "Spears");
mysql> SELECT * FROM students;

⁄ Locate and start the ■ The database server ■ A list of the databases › To display a list of ■ A list of the tables in ˇ To display the contents of ■ The contents of the table ‡ Type the code that
client software for your you want to connect on the server appears. the tables in the current the database appears. a table, type SELECT * FROM appear. creates fields and
database management to must be running. database, type SHOW followed by the name of the records for the table.
system. ‹ To select the database you TABLES; and then press table whose contents you Á To create a new table in the
¤ To display a list of the want to work with, type USE Enter. want to view. Then type a current database, type CREATE ■ The new table is
databases on the server, followed by the name of the semicolon and press Enter. TABLE followed by the name of created and added
type SHOW DATABASES; database and a semicolon. the table you want to create. to the database.
182 and then press Enter. Then press Enter. Then press Enter. 183
PHP PHP AND MYSQL 10

Once a connection to a MySQL server has been The error control operator (@) is often used with
CONNECT TO A MYSQL SERVER established, you can use the mysql_select_db
function to select the database you want to work with.
the mysql_connect function. This operator
prevents a PHP error message from appearing in
To use the mysql_select_db function, you must a user's Web browser when a connection to the
o enable a PHP page to access a database stored on The link identifier can be used by other functions in the PHP

T 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.
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
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
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
using a specific MySQL server connection. If no link identifier
The mysql_connect function takes three arguments––the successful. script and display a customized error message.
is specified, the last successful connection made in the script
host name or IP address of the computer running the MySQL will be used. Example:
Example:
server, a user name and a password. If the MySQL server is
$linkID = mysql_connect("localhost", "", ""); $linkID = @mysql_connect("localhost", "", "") or
running on the same computer as the Web server, you can If you include more than one mysql_connect function with die("Connection to the database cannot be made.");
specify the host name localhost or the IP address 127.0.0.1 the same arguments in a script, new connections will not be if (mysql_select_db("mysql", $linkID) != FALSE)
to connect to the MySQL server. If the MySQL server does created when the subsequent functions are called. Instead, {
not require a user name and password, you can enter empty the functions will use the link identifier for the first print "The database was successfully selected.";
strings ("") for these arguments. connection. }
else
When a connection to the MySQL server is made successfully, When a PHP script that opens a MySQL server connection {
the mysql_connect function returns a link identifier. A link terminates, the connection to the server is automatically print "The specified database cannot be selected.";
identifier is a positive integer that labels the connection to the closed. You can use the mysql_close function to explicitly }
server. If a connection is not made successfully, the function close a connection.
will return a value of false.

CONNECT TO A MYSQL SERVER

⁄ To connect to a ¤ Between the parentheses, ‹ Type a comma followed Note: If a user name or password is Á To test if a connection ° Between the parentheses, · Display the PHP page ■ The Web browser
MySQL server, type type the host name or IP by a user name enclosed in not required, enter an empty string. to the MySQL server was type the name of the variable in a Web browser. displays the results of
mysql_connect(). address of the computer quotation marks. made successfully, type the that stores the link identifier. connecting to a MySQL
ˇ Type the code that assigns code that checks the value server.
running the MySQL server the link identifier returned
enclosed in quotation marks. › Type a comma followed of the link identifier.
by a password enclosed in by the mysql_connect
quotation marks. function to a variable. ‡ To close the connection
to the MySQL server, type
184 mysql_close(). 185
PHP PHP AND MYSQL 10
CREATE A PERSISTENT When specifying the host argument for the mysql_pconnect function,
you may specify a port number by typing the host name or IP address

CONNECTION TO A MYSQL SERVER 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
ou can use the mysql_pconnect function to create When a connection to the server is made successfully, the not set to the default port number. If multiple MySQL servers are running on

Y 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.
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
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.
When the mysql_pconnect function is called again in return a value of false. Example:
another PHP script using the same arguments as the original $linkID = mysql_pconnect("localhost:3307", "martine", "secret");
mysql_pconnect function call, the original connection will A connection created using the mysql_pconnect function
be used instead of creating a new connection. cannot be closed using the mysql_close function. A
connection using the mysql_pconnect function will
The mysql_pconnect function will work only if PHP is set eventually close after it has been idle for a specific amount When working in the Unix environment, you can specify the path of a socket
up as a module. For information about setting up PHP as an of time. being used by a MySQL server. A socket provides a means for the client to
Apache module, see the top of page 11. To set up PHP as a communicate with the server and is similar to a network port number. The path
module on a different type of Web server, refer to PHP's The mysql_pconnect function is useful in instances of a socket can be specified in the host argument for the mysql_pconnect
documentation. where many connections to the database have to be made function by typing the host name or IP address followed by a colon (:) and
in a short period of time using the same user name and the path to the socket file. The default socket is /tmp/mysql.sock. You may
The mysql_pconnect function takes three arguments–– password. Opening and closing database connections can also specify a path to a socket when calling the mysql_connect function.
the host name or IP address of the computer running the use a substantial amount of system resources and thus slow
Example:
MySQL server, a user name and a password. If a user name down a server. Using a persistent connection to a database
$linkID = mysql_pconnect("localhost:/tmp/mysql2.sock", "martine", "secret");
or password is not required, you can enter empty strings ("") is more efficient and improves the performance of the
for these arguments. application.

CREATE A PERSISTENT CONNECTION TO A MYSQL SERVER

⁄ To create a persistent ¤ Between the parentheses, ‹ Type a comma followed › Type a comma followed ˇ Type the code that assigns Á To test if the persistent ‡ Display the PHP page ■ The Web browser displays
connection to a MySQL type the host name or IP by a user name enclosed in by a password enclosed in the link identifier returned connection to the MySQL in a Web browser. the results of creating a
server, type mysql_pconnect(). address of the computer quotation marks. quotation marks. by the mysql_pconnect server was made successfully, persistent connection to
running the MySQL server function to a variable. type the code that checks the a MySQL server.
enclosed in quotation marks. Note: If a user name or password value of the link identifier.
is not required, enter an empty
string.
186 187
PHP PHP AND MYSQL 10
ISSUE AN SQL STATEMENT
TO A MYSQL SERVER The mysql_create_db function can be used in a
PHP script to create a database. To use this function,
The mysql_drop_db function allows you to
delete a database from a MySQL server. If the
you need to specify the name of the database you database is deleted successfully, a value of true is
want to create followed by the link identifier for the returned. Otherwise, a value of false is returned.

A
fter creating a connection to a MySQL server in a SQL statements used to retrieve data from a database,
PHP page and selecting the database you want to such as SELECT and SHOW TABLES, return a result MySQL server connection. The mysql_create_db
Example:
work with, you can use the mysql_query function identifier if successfully executed. The result identifier is function returns a value of true if the database was
$resultID = mysql_drop_db("customers", $linkID);
to issue an SQL statement to the server. Issuing an SQL a positive integer that points to the data retrieved from successfully created or false if the operation fails. In
statement to a MySQL server allows you to manipulate the database, which is temporarily stored in a result set. order to create a database, the user name used to
a database and perform tasks such as creating a table, To access the data from the result set, you specify the make the MySQL server connection must have the
retrieving data or adding records. appropriate permissions. You can use the mysql_db_query function
result identifier as an argument for the function you want
to send an SQL statement directly to a database
to use, such as the mysql_fetch_row function. Example:
To use the mysql_query function, you need to specify a after creating a connection to the server.
valid SQL statement. You can also specify the link identifier You should keep in mind that the database program you if (mysql_create_db("accounting", $linkID) == TRUE) The mysql_db_query function takes three
for the MySQL server connection you want to use. are using determines the SQL statements you can issue. { arguments––the name of the database you want
print "The database was created successfully.";
Certain SQL features are not available in MySQL in order } to query, an SQL statement and the link identifier
If the SQL statement is successfully executed, the to improve the database program's performance and speed. for the MySQL server connection.
mysql_query function will return a value of true or else
There are also special SQL statements that can be used only { Example:
a result identifier. If the statement is not successfully on a MySQL database. You can consult the www.mysql.com print "The database could not be created.";
executed, the function will return a value of false. SQL Web site to find more information about the specific } $resultID = mysql_db_query("accounting",
statements that perform an operation but do not retrieve "CREATE TABLE employee(id INT(4), name CHAR(15),
features of MySQL. extension INT(4))", $linkID);
data from a database, such as CREATE TABLE and
UPDATE, return a value of true if successfully executed.

ISSUE AN SQL STATEMENT TO A MYSQL SERVER

⁄ Type the code that ¤ To issue an SQL ‹ Between the parentheses, › Type a comma followed ˇ Type the code that Á To test if the SQL ‡ Display the PHP page ■ The Web browser
connects the PHP page statement to the type the SQL statement you by the name of the variable assigns the value returned statement was issued in a Web browser. displays the result of
to the MySQL server and MySQL server, type want to issue, enclosed in that stores the link identifier. by the mysql_query successfully, type the code issuing an SQL statement
selects the database you mysql_query(). quotation marks. function to a variable. that checks the value of to a MySQL server.
want to work with. the variable storing the
mysql_query function.

188 189
PHP PHP AND MYSQL 10
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
RETRIEVE INFORMATION FROM A DATABASE simplify your code and make your arrays easier to work with.
Example:

T
he SQL SELECT statement allows you to retrieve The mysql_query function returns a result identifier, which $resultID = mysql_query("SELECT firstName, extension FROM employees", $linkID);
information from a database. This is useful when points to the result set. If the SELECT statement is not print "<table>";
you want to display the contents of a table. The executed successfully, the function returns a value of false. print "<tr><th>First Name</th><th>Extension</th></tr>";
mysql_query function is used to issue a SELECT while (list($firstName, $extension) = mysql_fetch_row($resultID))
statement to the database. Once the SELECT statement has been successfully issued to {
the database, you can use the mysql_fetch_row function print "<tr><td>$firstName</td><td>$extension</td></tr>";
The SELECT statement allows you to specify the data you to access the data in the result set. You must specify the }
print "</table>";
want to retrieve from a table. You can specify the data you variable that stores the result identifier as the argument for
want to retrieve by name or use an asterisk (*) to retrieve the mysql_fetch_row function. The mysql_fetch_row
all the data in a table. The SELECT statement uses the function returns an array containing the values from one row You can use the WHERE clause with a SELECT statement to specify
FROM clause to specify the name of the table that stores of the result set. To retrieve subsequent rows in the result a condition for retrieving data. To specify multiple conditions, you
the information you want to retrieve. set, you can use the mysql_fetch_row function in a loop. can also use the OR and AND operators. For more information about
When the SELECT statement has been executed successfully, Information retrieved from a database is commonly placed using the WHERE clause, consult the MySQL documentation at the
the data retrieved from the database is temporarily stored in in an HTML table. This allows you to neatly display the www.mysql.com Web site.
a result set, which has the same format as a table. The fields information on a Web page. Example:
specified in the SELECT statement make up the columns of SELECT invoiceNumber, totalCost FROM orders WHERE totalCost = 50
the result set and the values from each field form the rows. OR (totalCost >= 100 AND totalCost <= 300)

RETRIEVE INFORMATION FROM A DATABASE

⁄ Type the code that ¤ To issue an SQL ‹ Between the parentheses, › Type a comma Á To access the data ° Type the code that · Display the PHP page ■ The Web browser
connects the PHP page statement to the MySQL type SELECT * FROM followed followed by the name of retrieved from the database, processes the result of in a Web browser. displays the result of
to the MySQL server server, type mysql_query( ). by the name of the table that the variable that stores type mysql_fetch_row( ). the mysql_fetch_row retrieving information
and selects the database stores the information you the link identifier. function and formats the from a database.
you want to work with. want to retrieve. Enclose ‡ Between the parentheses, information for display.
the SELECT statement in ˇ Type the code that type the name of the variable
quotation marks. assigns the value returned that stores the result
by the mysql_query identifier.
190 function to a variable. 191
PHP PHP AND MYSQL 10
When adding a string value that contains quotation marks, You can make changes to the php.ini
ADD A RECORD you must escape the quotation marks by placing the backslash
character (\) before each quotation mark. If the quotation
file so that quotation marks, backslash
characters and NULL characters in strings
marks in a string are not escaped, an error may occur when are automatically escaped when the
nce you establish a connection with a database, If you do not specify the names of the fields you want to

O you can add records to the database using the


INSERT statement.
When adding a record to a database, you use the
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 INSERT statement is executed.
Example:
mysql_query("INSERT INTO customer (customerID, firstName,
lastName) VALUES (111, 'Tim', 'O\'Brien')", $linkID);
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
the table. are escaped automatically. When the
mysql_query function to issue an INSERT statement
to the MySQL server. The mysql_query function returns You may insert multiple records using the same INSERT magic_quotes_runtime directive
a value of true if the new records are added successfully. statement. After the values for the first record are specified, You can insert a string value stored in a variable into a is enabled, functions that retrieve
Otherwise, the function returns a value of false. values for subsequent records are included, enclosed in record in your database. You should use the addslashes information from external sources,
parentheses. Each record you add must be separated by function to escape the quotation marks in a string stored in such as databases and text files, return
The INSERT statement uses the INTO clause to specify a comma. a variable before it is used with an INSERT statement. The strings that are escaped automatically.
the name of the table into which you want to insert addslashes function takes the variable that contains a
records. After the table name, you indicate the fields The MySQL server requires that appropriate permissions string value as an argument. When a variable is used in an
into which you want to insert data. be granted before a script can add information to a SQL statement, the variable name is enclosed in single
database. For information about setting permissions in quotation marks.
The VALUES clause is used to specify the values for each a MySQL server, consult the MySQL documentation at
record you want to add to the table. You must specify a the www.mysql.com Web site. Example:
value that corresponds to each field name indicated in the $text = "O'Brien";
INTO clause. You must place the values in the same order $escaped = addslashes($text);
the fields were specified in the INTO clause. String values mysql_query("INSERT INTO customer (customerID, firstName,
should be enclosed in single quotation marks (' '). lastName) VALUES (111, 'Tim', '$escaped')", $linkID);

ADD A RECORD

⁄ Type the code that ¤ To add a record in the › Between the parentheses, Á Type the values you ° Type the code that assigns ‚ Type the code that — Display the PHP ■ The Web browser
connects the PHP page database, type mysql_query(""). type the names of the fields want to assign to each field the value returned by the displays information page in a Web browser. displays the result of
to the MySQL server in the table, separating each in the record, enclosed in mysql_query function to from the database in adding a record to a
and selects the database ‹ Between the quotation field name with a comma. parentheses. A comma a variable. the PHP page. database.
you want to work with. marks, type INSERT INTO separates each value.
followed by the name of the ˇ To specify the values for · To test if the records were
table to which you want to a record you want to add, ‡ Outside the quotation added successfully, type the
add records. Then type (). type VALUES. marks, type a comma code that checks the value
followed by the link of the variable storing the
192 identifier. mysql_query function. 193
PHP PHP AND MYSQL 10
The mysql_affected_rows function may be used to determine
the number of records that were affected by an UPDATE statement.

UPDATE A RECORD 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
nce you establish a connection with a database, unique ID for the record in the WHERE clause. If a WHERE line that updates the database. The mysql_affected_rows

O you can edit the information contained in the


database. Editing the information in a database
allows you to keep the information up-to-date.
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
function may also be used to determine the number of records
affected by an INSERT or DELETE statement.
Example:
To update records in a database, you use the mysql_query be enclosed in single quotation marks (''). If the value $result = mysql_query("UPDATE customer SET lastName = 'Edwards'
function to issue an UPDATE statement to the MySQL server. contains quotation marks, you must escape the quotation WHERE firstName = 'Martine'", $linkID);
The mysql_query function returns a value of true marks by placing the backslash character (\) before each print mysql_affected_rows($linkID) . " record(s) were updated.";
if the update is made successfully. quotation mark, such as \' and \".
After the UPDATE statement, you indicate the name of the The MySQL server requires that appropriate permissions be You may want to store SQL statements in variables and then pass a variable
table that contains the records you want to modify. The SET granted before a script can update information in a database. as an argument to the mysql_query function. Using variables to store SQL
clause specifies which field in a record needs to be changed For information about setting update permissions in a statements is a common programming practice and can make your code
and the new value. You can specify more than one field to MySQL server, consult the MySQL documentation at the easier to read and update. Storing SQL statements in variables also provides a
be changed. The UPDATE statement uses the WHERE clause www.mysql.com Web site. convenient way to switch between statements when troubleshooting a script.
to specify the data that identifies the record to be modified. You simply place two slashes (//) in front of each statement you temporarily
do not want to use.
Depending on the data specified in the WHERE clause, you
may update the value of one or more records in a table. Example:
To update a single record, you would typically indicate the // $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 ¤ To update a record › Type the name of the field Á To specify which records ° Outside the quotation ‚ To test if the update was ± Display the PHP page ■ The Web browser
connects the PHP page in the database, type you want to change followed to update, type WHERE. marks, type a comma made successfully, type the in a Web browser. displays the result of
to the MySQL server and mysql_query(""). by =. Then type the new value followed by the link code that checks the value updating a record in
selects the database you you want to assign. ‡ Type the name of the identifier. of the variable storing the a database.
want to work with. ‹ Between the quotation field followed by =. Then mysql_query function.
marks, type UPDATE ˇ Repeat step 4 for each field type the value that identifies · Type the code that
followed by the name you want to change, separating the records to be modified. assigns the result of the — Type the code that
of the table you want to each field with a comma. mysql_query function displays the information
194 update. Then type SET. to a variable. in the database. 195
PHP PHP AND MYSQL 10
DELETE A RECORD Multiple records can be removed from a table at one
time by specifying a range of values in the WHERE clause
You can remove a field from a table by
using the ALTER TABLE statement with

A
fter creating a connection to a MySQL server in a marks, you must escape the quotation marks by placing of the DELETE statement. For example, if you have a field the mysql_query function. After specifying
PHP page and selecting the database you want to the backslash character (\) before each quotation mark, that stores the last date on which a customer made a the table you want to affect, the DROP
work with, you can use the DELETE statement to such as \' and \". purchase, you can use an expression with the WHERE clause is used to specify the field you want
remove a record from the database. clause to delete all the records of customers who made to remove. When a field is removed, all
After the DELETE statement, you can specify the link their last purchase before a specific date. the data in the field is also deleted.
When deleting a record from a database, you use the identifier for the MySQL server connection you want to
mysql_query function to issue a DELETE statement use. If you simply want to use the last connection that Example: Example:
to MySQL server. The mysql_query function returns was made to the server, you can omit the link identifier $result = mysql_query("DELETE FROM customer $result = mysql_query("ALTER TABLE customer
a value of true if the record is deleted successfully. from the mysql_query function. WHERE lastPurchase < '2000-04-23'", $linkID); DROP middleName", $linkID);
Otherwise, the function returns a value of false.
If you want to remove all the records from a table at one
The DELETE statement uses the FROM clause to specify time, you can use the DELETE statement without including To delete an entire table and all the data stored in the table
the name of the table that stores the record you want the WHERE clause. This will delete all the data in the table from a database, you can use the DROP TABLE statement
to delete. The WHERE clause indicates information that but will not delete the table from the database. with the mysql_query function. After the DROP TABLE
uniquely identifies the record you want to delete. You statement, you must specify the name of the table you
should be careful when identifying the record you want The MySQL server requires that appropriate permissions
be granted before a script can delete information from a want to delete. You should be careful not to delete a table
to delete, as information accidentally deleted from a that you might need at a later time.
database often cannot be recovered. database. For information about setting permissions in a
MySQL server, consult the MySQL documentation at the Example:
When identifying the information in the record you www.mysql.com Web site. $result = mysql_query("DROP TABLE oldCustomers", $linkID);
want to delete, a string value must be enclosed in single
quotation marks (''). If the value contains quotation

DELETE A RECORD

⁄ Type the code that ¤ To delete a record › To specify the record Á Outside the quotation ‡ Type the code that assigns · Type the code that ‚ Display the PHP page ■ The Web browser
connects the PHP page from the database, type to delete, type WHERE. marks, type a comma the value returned by the displays information in a Web browser. displays the result of
to the MySQL server and mysql_query(""). followed by the link mysql_query function to from the database in deleting a record from
selects the database you ˇ Type the name of the identifier. a variable. the PHP page. a database.
want to work with. ‹ Between the quotation field followed by =. Then
marks, type DELETE FROM type the value in the field ° To test if the record was
followed by the name of that identifies the record deleted successfully, type the
the table from which you to be deleted. code that checks the value
want to delete a record. of the variable storing the
196 mysql_query function. 197
PHP PHP AND MYSQL 10
RETRIEVE INFORMATION
AS AN ASSOCIATIVE ARRAY The mysql_fetch_object function allows
you to retrieve information from a result set
The mysql_fetch_array function is used to
retrieve information from a database as an array
as an object. This function returns an object that contains both numeric and associative keys.

A
fter using the SELECT statement with the To call the mysql_fetch_assoc function, you must pass with property names that are the same as the The mysql_fetch_array function returns
mysql_query function to retrieve information from the result identifier that points to the data stored in the field names in the table. To access the value an array in which each field value appears
a database and place it in a result set, you can use result set as an argument. If the function is successful, the of a field, specify the name of the variable that twice––once with a numeric key and once with an
the mysql_fetch_assoc function to retrieve information associative array is returned. If there is no information in stores the object followed by the member associative key. This duplication of values makes
from the result set as an associative array. the result set, the mysql_fetch_assoc function returns access operator (->) and the field name. the mysql_fetch_array function inefficient for
a value of false. retrieving large amounts of information from a
The mysql_fetch_assoc function returns an associative Example:
result set. You should use this function only when
array in which the keys are the same as the names of the To access a value from the associative array, you specify while ($row = mysql_fetch_object($resultID))
both the numeric order and the field names to
fields in the result set and the array values correspond to the the name of the variable that stores the result of the {
print "<tr>"; which the values belong are needed.
values in the fields. Many programmers assign the result of mysql_fetch_assoc function followed by brackets []. print "<td>" . $row->customerID . "</td>"; Example:
the mysql_fetch_assoc function to a variable to make Between the brackets, specify the name of the field that print "<td>" . $row->firstName . "</td>";
the associative array easier to work with. stores the value you want. print "<td>" . $row->lastName . "</td>"; while ($row = mysql_fetch_array($resultID))
print "</tr>"; {
Accessing data as an associative array can make your PHP The mysql_fetch_assoc function is often used with } print "<tr>";
code more readable because it identifies exactly which a loop to allow access to all the information from the print "<td>" . $row[0] . "</td>";
fields are being used instead of identifying the fields only by result set. You can use the mysql_num_rows function print "<td>" . $row[firstName] . "</td>";
print "<td>" . $row[2] . "</td>";
number. Using associative arrays also means that you do not in the loop code to indicate when the loop should end. print "</tr>";
need to consider the order in which the fields appear in the The mysql_num_rows function determines the number }
result set. This may help prevent problems that may arise of rows returned by the SELECT statement issued by the
if the structure of the table were to change in the future. mysql_query function.

RETRIEVE INFORMATION AS AN ASSOCIATIVE ARRAY

⁄ Type the code that ¤ Type the code that uses ‹ To retrieve information ˇ Type the code that Á To access a value from the ‡ Repeat step 6 for each · Display the PHP page ■ The Web browser
connects the PHP page a mysql_query function from the result set as an assigns the result of the result set, type the name of value you want to retrieve. in a Web browser. displays the result of
to the MySQL server to retrieve information from associative array, type mysql_fetch_assoc the variable that stores the retrieving information
and selects the database the database and assigns the mysql_fetch_assoc(). function to a variable. associative array. Then type ° Type the code that from a database as an
you want to work with. result identifier returned by the name of the field that uses the information associative array.
the mysql_query function › Between the parentheses, stores the value you want to retrieved as an associative
to a variable. type the name of the variable access, enclosed in brackets []. array and formats the
198 that stores the result identifier. information for display. 199
PHP PHP AND MYSQL 10
You can use the MySQL AS construct to specify a When you want to display all the records
different name for a field you are retrieving. Specifying from one of the tables in a join, you can use
a different name for a field can be particularly useful the LEFT JOIN clause. This clause allows
RETRIEVE INFORMATION when using the mysql_fetch_assoc function. The
associative array returned by this function is indexed
you to retrieve all the records from a table,
regardless of whether the records have
using only field names. This can cause problems if you corresponding entries in the second table.
FROM MULTIPLE TABLES retrieve fields that have the same name from different
tables.
To use the LEFT JOIN clause, specify the
name of the table from which you want to
retrieve all the records directly following
ne of the most useful features of a relational tables, you specify the name of the first table and the name Example:

O database is the ability to retrieve data from


multiple tables and then combine the data
into a single result set.
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
SELECT orders.totalCost AS orderTotal,
shipping.totalCost AS shippingTotal FROM orders,
shipping WHERE orders.customerID = shipping.customerID
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.
first table. If the unique identifier for a record in the first
You use the SELECT statement to combine related data table matches information in the second table, then the Example:
from multiple tables. This operation is referred to as a join. You can use the MySQL CONCAT function to combine
record will be retrieved from both tables. For example, data from different fields into a single field. To use SELECT customer.firstName, customer.lastName,
To select a field for a join, you specify the name of the table you may want to join data from two tables called customer orders.itemDescription, orders.quantity,
containing the field and the name of the field, separated by the CONCAT function, you must specify the names of orders.purchaseDate FROM orders LEFT JOIN
and orders. The customer table has a primary key field the fields you want to retrieve, separated by commas.
a dot(.). You can select as many fields as you need for a that stores a unique customer id for each customer, as customer ON customer.customerID =
join. You use the FROM clause to specify the names of the You can also include a string, such as a space (' '), to orders.customerID
well as fields containing information such as first and last separate the fields. You can then use the AS construct
two tables from which you want to retrieve information. names. The orders table contains the orders made by each to specify a name for the new field.
The WHERE clause allows you to specify the relationship customer and includes each customer's id. You can join
between the tables being joined. Each table has a field that data from the two tables to create a report that includes Example:
stores a unique identifier for each record, referred to as a specific information for each customer who has placed SELECT CONCAT(firstName, ' ', lastName) AS fullName,
primary key. To specify the relationship between the two an order. customerID FROM customer

RETRIEVE INFORMATION FROM MULTIPLE TABLES

⁄ To issue an SQL ‹ To specify a field for the ˇ Type FROM followed Á To specify the ° Type = followed by the name ‚ Type the code that uses — Display the PHP page ■ The Web browser
statement to the MySQL join, type the name of the by the names of the tables relationship between of the second table and a dot. the mysql_fetch_row in a Web browser. displays the result of
server, type mysql_query(""). table followed by a dot and containing information the tables, type WHERE. Then type the name of the field function to access and retrieving information
the name of the field. you want to retrieve, that stores the same values as retrieve data and formats from multiple tables.
¤ Between the quotation separated by commas. ‡ Type the name of the those stored in the primary key the data for display.
marks, type SELECT. › Repeat step 3 until you first table followed by a of the first table.
have specified all the fields dot and the name of the
for the join, separating primary key field for the · Type the code that assigns
each table and field name table. the result of the mysql_query
200 pair with a comma. function to a variable. 201
PHP PHP AND MYSQL 10
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
ACCESS A PORTION OF A RESULT SET will return the value of the first field in the specified row.
TYPE THIS: RESULT:

A
fter information has been retrieved from a database to access in the result set. The offset positions of the rows $resultID = mysql_query("SELECT customer.firstName, customer.lastName, Martine
and placed in a result set, you can use the in a result set are numbered starting from zero (0). If you orders.itemDescription, orders.quantity, orders.purchaseDate
mysql_data_seek function to access a portion specify an offset position that is equal to or greater than the FROM customer, orders WHERE customer.customerID = orders.customerID",
of the result set. The mysql_data_seek function advances number of rows in the result set, an error will be generated. $linkID);
print mysql_result($resultID, 3);
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 The mysql_data_seek function will return a value of true
set without having to iterate through the entire result set. or false depending on whether the function was executed
successfully. When using the mysql_result function, you can specify the value you
The mysql_data_seek function is typically used to want to retrieve from a row. To retrieve a value from a specific field in the
separate a large number of records to be displayed on a Once the pointer is positioned at the first row you want to row, you can include a third argument to specify the offset position of the
Web page. For example, if a user's query retrieves a large access in the result set, you can call the mysql_fetch_row field. You can also specify the name of the field instead of the offset position
number of records from a database, you may want to display function to retrieve the information in the row. The pointer is of the field. Another option allows you to prefix the field name with the
the records on the Web page in small segments at a time then advanced to the next row. To retrieve subsequent rows, name of the table from which you want to retrieve the data. This is useful
instead of displaying all the records at once. Handling a you can call the mysql_fetch_row function repeatedly when working with a result set created from multiple tables.
large result set in this manner is very efficient, since you using code that creates a loop, such as a for statement.
Example:
retrieve only the data you need. mysql_result($resultID, 3, 4);
To use the mysql_data_seek function, you must specify Can be typed as:
the result identifier that points to the data stored in the result mysql_result($resultID, 3, "purchaseDate");
set. You also specify the offset position of the row you want 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 ¤ Type the code that uses ‹ To move the row pointer ˇ Type a comma, followed Á To retrieve the row at which ° Type the code that · Display the PHP page ■ The Web browser
connects the PHP page a mysql_query function to a specific row in the result by the number that specifies the pointer is positioned, type processes the result of in a Web browser. displays the result of
to the MySQL server to retrieve information from set, type mysql_data_seek(). the offset position of the row mysql_fetch_row( ). the mysql_fetch_row accessing a portion
and selects the database the database and assigns the where you want to place the function and formats the of a result set.
you want to work with. result identifier returned by › Between the parentheses, pointer. ‡ Between the parentheses, information for display.
the mysql_query function type the name of the variable type the name of the variable
to a variable. that stores the result identifier. that stores the result identifier.
202 203
PHP PHP AND MYSQL 10
You can use functions to obtain information about identifier obtained from the mysql_list_tables
the tables in a database. To obtain a list of tables in function as an argument. You can also determine the
GET INFORMATION ABOUT FIELDS a database, you can use the mysql_list_tables
function. The function takes two arguments––the
name of a table by using the mysql_tablename
function. You must specify the result identifier
name of the database and the link identifier of obtained from the mysql_list_tables function

T
he mysql_list_fields function returns a result There are a number of functions that use the result identifier the MySQL server connection. To determine the and the offset position of the table in the database
identifier that can be used to obtain information about obtained from the mysql_list_fields function to number of tables in a database, you can use the as arguments for the mysql_tablename function.
the fields in a table. You may find it useful to retrieve retrieve information about a field. The mysql_field_name mysql_num_rows function, which takes the result
information such as the names or data types of fields before function is used to retrieve the name of a field. You can
making an SQL query. The mysql_list_fields function use the mysql_field_type function to retrieve the data Example:
takes three arguments––the name of a database, the name of type of a field. The mysql_field_len function is used $resultID = mysql_list_tables("shopping", $linkID);
the table containing the fields you want to work with and the to retrieve the maximum length of a field. You can use the for ($tablePos = 0; $tablePos < mysql_num_rows($resultID); $tablePos++)
link identifier of the MySQL server connection. If you do not mysql_field_flags function to retrieve other information {
print mysql_tablename($resultID, $tablePos) . "<br>";
specify a link identifier, the last successful connection to the about a field. These functions all take two arguments––the }
MySQL server will be used. The mysql_list_fields result identifier obtained from the mysql_list_fields
function will return a result identifier if successful, otherwise function and the offset position of the field in the table.
it will return a value of false. The offset positions of the fields are numbered starting You can obtain a list of databases on a MySQL argument. You can then use the mysql_num_rows
from zero (0) and are determined by where the fields server by using the mysql_list_dbs function. function to determine the number of databases
You can obtain the number of fields in a table by using appear in the table. An error will occur if an offset position The mysql_list_dbs function takes the link in the list. You can also determine the name of a
the mysql_num_fields function. When calling the that is equal to or greater than the number of fields in identifier of the MySQL server connection as an database by using the mysql_tablename function.
mysql_num_fields function, you must pass the result a table is specified.
identifier obtained from the mysql_list_fields function Example:
as an argument. The mysql_num_fields function is often $resultID = mysql_list_dbs($linkID);
used as a counter in a loop that cycles through each field for ($dbPos = 0; $dbPos < mysql_num_rows($resultID); $dbPos++)
in a table. This type of loop allows you to access information {
print mysql_tablename($resultID, $dbPos) . "<br>";
about each field. }

GET INFORMATION ABOUT FIELDS

⁄ Type the code that ‹ Between the parentheses, ˇ Type the code that assigns ‡ Between the parentheses, · To obtain information — Repeat steps 9 and 10 ¡ Display the PHP page ■ The Web browser
connects the PHP page type the name of the database, the result identifier returned type the result identifier. about a specific field, type for each function you want in a Web browser. displays the result of
to the MySQL server. enclosed in quotation marks. by the mysql_list_fields the name of the function you to call. obtaining information
function to a variable. ° Type the code that uses want to call followed by (). about the fields in a table.
¤ To retrieve information › Type a comma followed the mysql_num_fields ± Type the code the uses
about a table, type by the name of the table, Á To obtain the number function. ‚ Between the parentheses, the results of the functions
mysql_list_fields(). enclosed in quotation marks. of fields in a table, type type the result identifier. Then you called.
Then type a comma followed mysql_num_fields( ). type a comma followed the
204 by the link identifier. offset position of the field. 205
PHP PHP AND MYSQL 10
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

USE A FORM TO WORK WITH A DATABASE function to retrieve the error number from the MySQL server
and the mysql_error function to retrieve the error message.
Example:
orms provide an easy-to-use interface for manipulating If the result of the mysql_query function is of the boolean

F 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,
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 ((gettype($resultID) == "boolean") && ($resultID == FALSE))
{
print "There was an error in the SQL statement.<br>";
print "Error #" . mysql_errno($linkID) . ": " . mysql_error($linkID);
processes the statement and displays the result. }
If the returned result is of the boolean data type and has a
When creating the code for a form that will be used to value of true, the SQL statement was successfully executed.
issue SQL statements to a database, you must specify the You may want to use the mysql_affected_rows When creating a table that displays retrieved records, you can use
name of the PHP page that connects to the database in function to display the number of records that were affected the mysql_num_fields function to retrieve the number of fields
the action attribute of the <form> tag. You can use the by the query. in the result set. You can use the result of this function to create a
<textarea> tag to create a text area element on the form for loop that uses the mysql_field_name function to retrieve
that users can enter SQL statements into. The PHP page will When the returned result is not of the boolean data type,
all the field names.
use the value of the name attribute for the <textarea> tag the SQL statement returned a result set. You can use the
to access the SQL statement passed by the form. mysql_num_rows function to display the number of Example:
rows in the result set. You can also retrieve the records print "<table border=\"1\">";
The PHP page used to process the form must have a in the result set using the mysql_fetch_row function.
connection to the MySQL server and select the database print "<tr>";
you want to work with. The PHP page must also contain for ($i = 0; $i < mysql_num_fields($resultID); $i++)
{
the mysql_query function, which will process the SQL print "<th>" . mysql_field_name($resultID, $i) . "</th>";
statement passed by the form. }
print "</tr>";

USE A FORM TO WORK WITH A DATABASE

⁄ Type the code that ¤ To have the PHP page › Type a comma Á Type the code that ‡ Type the code that ° Type the code you want · In a Web browser, — Click the submit button
connects the PHP page accept and process an SQL followed by the name of determines if the result determines if the result of to process when the result display the form you to pass the SQL statement
to the MySQL server statement passed by a form, the variable that stores of the mysql_query the mysql_query function of the mysql_query created to issue SQL to the PHP page.
and selects the database type mysql_query(). the link identifier. function is of the boolean is of the boolean data type function is of a data type statements to the database.
you want to work with. data type and is false. Then and is true. Then type the other than boolean. ■ The PHP page that
‹ Between the parentheses, ˇ Type the code that type the code you want to code you want to process ‚ Enter an SQL statement processes the SQL statement
type $ followed by the value assigns the result of the process in this situation. in this situation. into the form. will appear and the database
assigned to the name attribute mysql_query function will be modified.
of the <textarea> tag in to a variable.
206 the form. 207
PHP TROUBLESHOOTING PHP SCRIPTS 11
When specifying the information you want to To view the error information saved to the
LOG ERRORS TO A FILE display in the error log, you may want to append
a newline character (\n) to the end of the error
operating system's log with Windows NT,
2000 or XP, open the Control Panel and
message you specify in the error_log function. double-click Administrative Tools. Then

W
hen an error is generated in a PHP script, you The first argument specifies the message you want to The newline character will help ensure that each double-click Event Viewer and click
may want to save information about the error display in the error log when an error occurs. The second entry in the error log is placed on its own line, Application Log. For more information
in a file for later review. Saving error information argument indicates the message type, which determines making the error log easier to read when viewed about logging errors and the location
to a file is useful for keeping track of non-critical errors how the message will be stored. To specify that you want in a text editor. of system logs, consult your operating
that do not require immediate attention, such as an error a message to be stored in an error log, you use a message system's documentation.
generated when a user forgets to enter a user name. type of 0.
If you are using Windows NT, 2000 or XP, you
Before you can log errors to a file, you must make changes When a PHP script encounters an error, PHP will use a can add error information to the operating
to the php.ini configuration file. To specify that you want to built-in error-handling function to save the date and time system's log instead of logging errors to a file.
log errors, change the value of the log_errors directive of the error and the message you specified to the error In the php.ini configuration file, remove the
in the php.ini file to "On." To specify a file to which you log. You can create a custom error-handling function to semicolon preceding the error_log directive
want to log errors, you enter the location and name of the keep track of additional details about errors. For more that specifies the syslog value. If you previously
file as the value for the error_log directive. If the file information about creating a custom error-handling specified a file to which error information was
you specify does not exist, PHP will create the file when function, see page 214. to be saved, place a semicolon in front of that
the first error occurs. For more information about the error_log line to have the php.ini file ignore
php.ini file, see page 26. The error log is a simple text file that can be viewed the command.
at any time using a text editor or word processor.
To pass error information from a PHP page to an error log, log_errors = On
;error_log = c:\php\error.log
you include the error_log function in the PHP code for error_log = syslog
the page. The error_log function takes two arguments.
LOG ERRORS TO A FILE

CHANGE THE PHP.INI SETTINGS ‹ To activate the SET UP THE PHP PAGE ‹ To specify that the ˇ Display the PHP page ■ When an error is DISPLAY THE ERROR LOG ■ The error log displays
⁄ In the php.ini file, select error_log directive, ⁄ In the PHP page for message should be stored in a Web browser. generated, the message ⁄ Locate and open the the date and time an
the value of the log_errors delete the semicolon which you want to save error in an error log, type a you specified will be error log in a text editor. error was generated and
directive and type On. preceding the directive. information, type error_log(). comma followed by 0. written to the error log. the error message you
specified.
¤ To specify a file in which to › Save the file. ¤ Between the parentheses, › Type the code that
log errors, select the value of type the message you want uses the error_log
the error_log directive and to display in the error log, function.
type the location and name of enclosed in quotation marks.
the file you want to use.

208 209
PHP TROUBLESHOOTING PHP SCRIPTS 11

SEND AN ERROR MESSAGE 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
On Unix-based systems, such as computers
running the Linux operating system,
Sendmail is the universally accepted program
TO AN E-MAIL ADDRESS mail system available to the Web server. On
Windows computers, you must ensure that the
used to process e-mail messages. You must
use the php.ini file to specify the location of
php.ini file specifies the name of the mail server the Sendmail program on the Web server.

T
he error_log function allows you to send a message To send an error message to an e-mail address, you use used to send mail, often referred to as the SMTP The e-mail account on the Web server used
to an e-mail address when an error occurs in a PHP a message type of 1. You must also specify the e-mail server. You must also specify an e-mail address to send messages will be used when the
page. This is useful when a critical error occurs that address to which you want to send the message. that is authorized to send mail using the mail error_log function is processed. Locate
requires the immediate attention of support personnel, such server. In the php.ini file, locate the [mail the [mail function] section heading in
as an error generated by a database that is not responding Although not required, you can also specify new header
function] section heading and then change the php.ini file and then change the value of
or a failed attempt to log on as the administrator. information for the e-mail message. E-mail message headers
the value of the SMTP directive to reflect the the sendmail_path directive to reflect the
contain information such as the name of the person who
With the advent of telecommunication devices that can name of the outgoing mail server. Then change location of the Sendmail program.
sent the message, the subject of the message and the date
receive e-mail messages, such as pagers and mobile the value of the sendmail_from directive to
the message was sent. You can alter an existing header Example:
telephones, sending error messages to an e-mail address reflect a valid e-mail address.
or you can add a new header to the e-mail message. For [mail function]
is an efficient way for Webmasters to stay informed about example, you may want to change the 'From:' header to Example:
the status of their Web servers. reflect the name of the computer that generated the error. [mail function] sendmail_path = usr/bin/sendmail
If you specify a header that does not exist, the new header SMTP = mail.c1.us
To use the error_log function to send an error message will be created and sent with the e-mail message. Creating sendmail_from = ted@abccorp.com
to an e-mail address, you must specify the error message a new header is useful for support departments that
you want to send. You must also specify the message type, organize error messages according to the value of a
which determines where the error message will be sent. customized header.

SEND AN ERROR MESSAGE TO AN E-MAIL ADDRESS

⁄ To send a message ¤ Between the parentheses, ‹ To specify that the › To specify the e-mail ˇ To specify new header Á Type the code that ‡ Display the PHP page ■ When an error occurs,
to an e-mail address type the message you want to message should be sent address you want to send information for the e-mail uses the error_log in a Web browser. the message you created
when an error occurs, send, enclosed in quotation to an e-mail address, the message to, type a message, type a comma function. is sent to the specified
type error_log(). marks. type a comma followed comma followed by the followed by the header e-mail address.
by 1. e-mail address enclosed information enclosed in
in quotation marks. quotation marks.

210 211
PHP TROUBLESHOOTING PHP SCRIPTS 11
Besides E_NOTICE, E_WARNING and E_ERROR, If you do not want to report any
two other commonly used error reporting errors in a PHP script, you can turn
level constants are E_CORE_ERROR and off error reporting. To turn off error
CHANGE THE ERROR REPORTING LEVEL E_CORE_WARNING. These two constants are
similar to E_ERROR and E_WARNING, except
reporting, set the argument for the
error_reporting function to
that E_CORE_ERROR and E_CORE_WARNING zero (0).

W
hen PHP encounters an error in a section of constants include E_NOTICE, E_WARNING and E_ERROR.
detect errors generated by the PHP program
code, the program generates an error message You can use the E_NOTICE constant as the argument for Example:
itself and not by a script. Other error reporting
that is displayed in the user's Web browser. the error_reporting function when you want PHP to error_reporting(0);
levels include E_PARSE, E_COMPILE_ERROR,
You can change the error reporting level of PHP to specify detect inconsistencies that could be errors, but you do not
E_COMPILE_WARNING, E_USER_ERROR,
which errors PHP should generate an error message for. want PHP to print error messages for the inconsistencies.
E_USER_WARNING and E_USER_NOTICE.
You can use the E_WARNING constant to detect more
PHP can detect several different types of errors. Simple serious types of errors that may require attention and print
errors, such as dividing a number by zero, are the most error messages for the errors. The E_ERROR constant When using the error_reporting function to
common type of error. PHP can also identify and report reports only fatal errors in a script. If a fatal error occurs, change the error reporting level, you can assign
more serious errors, such as calling a function without the script is terminated after the error_reporting the function to a variable. You can then use the
passing the correct number or type of arguments. Some function is called. value of the variable later in your script to return
errors, called fatal errors, force PHP to terminate the to the original error reporting level.
processing of a script. Fatal errors are caused by critical You can specify more than one constant in the
problems, such as memory allocation problems. error_reporting function. This allows you to specify Type this:
more than one error reporting level. To use more than $oldLevel = error_reporting(E_NOTICE | E_ERROR);
The error_reporting function allows you to specify one constant, use the OR operator (|) to separate each
which errors PHP should report. The error reporting level constant in the error_reporting function. To return to the original level, type:
is specified using predefined constants. Commonly used error_reporting($oldLevel);

CHANGE THE ERROR REPORTING LEVEL

⁄ Type the code that ¤ To change the error ‹ Between the parentheses, › To specify another ˇ Type the constant that ■ You can repeat steps 4 ‡ Display the PHP page in ■ In this example,
will generate an error. reporting level, type type the constant that error reporting level, represents another error and 5 for each error a Web browser. an error message is
error_reporting(). represents the error reporting type |. reporting level you want reporting level you want displayed only for
level you want to use. to use. to specify. ■ When an error occurs, PHP the first error.
uses the specified reporting
Á Type the code that will level to determine if an error
generate another error. message should be displayed.
212 213
PHP TROUBLESHOOTING PHP SCRIPTS 11

After an error occurs, PHP will try to continue processing


CREATE AN ERROR-HANDLING FUNCTION the remainder of the PHP script from the point at which the
error occurred. Since a script may not continue working
n error occurs when a PHP script that contains a To set up the error-handling function to access the values, properly when a command fails, you may want to have the

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 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.
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.
you can have PHP use a custom error-handling function For example, in order to access the name of the script that
you created to display information about the error. generated an error, you will need to also specify variables TYPE THIS: RESULT:
for the error code number and description. set_error_handler("CustomErrorHandler");
Using a custom error-handling function allows you to The result of the calculation is:
print "The result of the calculation is: ";
enhance the functionality of a PHP script when an error After creating a custom error-handling function, you include $x = 1/0;
occurs. For example, you can use a custom error-handling the set_error_handler function in the PHP code for print "$x<br>"; An error has occurred.
function to access detailed information about an error and the page. The set_error_handler function takes as its print "The script has been processed."; Error number: 2
display the information in a format that is easy to read argument the name of the custom function you want to use. function CustomErrorHandler($errNumber,
Description: Division by zero
and understand. You should use the set_error_handler function at the $errDescript, $errFile, $errLine)
{ Script name: c:\web_apps\apache\htdocs\errorhandler.php
beginning of your PHP code to ensure that the custom Line number: 12
When an error occurs, PHP passes several values to error-handling function you specify will be accessible
print "<h2>An error has occurred.</h2>";
the error-handling function. The values include the code print "Error number: $errNumber<br>";
throughout your code. print "Description: $errDescript<br>";
number for the error, a brief description of the error,
print "Script name: $errFile<br>";
the name of the PHP script that generated the error print "Line number: $errLine<br>";
and the number of the line in the script where the die();
error was detected. The values are always passed to }
the error-handling function in this order.

CREATE AN ERROR-HANDLING FUNCTION

⁄ To create an error-handling ¤ Between the parentheses, ‹ Type the code that uses › To specify that you ˇ Between the parentheses, Á Display the PHP page ■ When an error occurs,
function, type function type a variable name for each the variables that store the want to use the custom type the name of the in a Web browser. the Web browser displays
followed by the name of value PHP will pass to the error information. Enclose error-handling function error-handling function, the result of using a
the function. Then type (). function when an error the code in braces. you created, type enclosed in quotation marks. custom error-handling
occurs. Separate each set_error_handler(). function.
variable name with a comma.
214 215
PHP TROUBLESHOOTING PHP SCRIPTS 11
You can use the show_source function to display a

EMBED DEBUGGING MESSAGES 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
mbedding debugging information into the HTML code You include debugging information within HTML code by

E 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
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 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.
major task that is executed in a PHP script. page. Any code enclosed in the delimiters will be processed TYPE THIS: RESULT:
by the Web server and the results will be sent to the Web
When specifying debugging information to be embedded, browser. <html>
you can include information such as the values of variables, <head>
Hello
the functions that are being called from within the PHP script After the PHP page is viewed in a Web browser, you can <title>Test Page</title>
and the number of iterations performed by loops. Debugging view the debugging information within the HTML code by </head> <html>
information can be a simple text message or can contain PHP displaying the source code of the page. Users who display <body> <head>
<?php <title>Test Page</title>
or HTML code. The message can also contain scripting code the HTML source code will also be able to view the print "Hello"; </head>
such as JavaScript or VBScript and can be one or more lines information. To ensure the security of your Web pages, print "<hr>"; <body>
long. you should include debugging messages in HTML code show_source("test.php"); <?php
only when developing and testing your Web pages. ?> print "Hello";
Debugging information is often inserted into HTML code </body> print "<hr>";
using a custom function. This enables you to standardize the </html> show_source("test.php");
message that is inserted into the HTML code each time the ?>
function is called. For example, you can include formatting </body>
code in the function to make the information easy to identify </html>
in the HTML code.

EMBED DEBUGGING MESSAGES

⁄ To create a function that ‹ Type the braces {} ˇ Between the opening and Á Type the code ‡ Type the code that ° Repeat step 7 at each · Display the PHP page ■ The HTML source code
generates an HTML comment, that will hold the body closing delimiters, type the that will display the calls the function and location in the PHP code in a Web browser. displays the debugging
type function followed by a name of the function. message you want the function debugging message in passes the information where you want to generate messages generated
for the function. Then type (). to embed in the HTML code. the HTML source code. you want to display in a debugging message. ‚ Display the source when the PHP page was
› In the body of the The message can include text, the debugging message code of the PHP page. processed.
¤ Between the parentheses, type function, type <!– – HTML or PHP code, as well to the function.
the name of a variable that will and – –>. as the variable that stores the
store the debugging message. information passed to the
216 function. 217
PHP TROUBLESHOOTING PHP SCRIPTS 11
USING TELNET TO
CONNECT TO A WEB SERVER 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
nce a PHP page is stored on a Web server, you may commands you can issue to a Web server are part of the

O 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
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
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
not typically accessible through a Web browser, in order to Consortium (W3C) Web site at www.w3.org. processed by the Web server. To change the maximum execution time, open
troubleshoot a PHP page. the php.ini file on the Web server and look for the following section of code.
Two common HTTP commands are GET and HEAD. The
You can view information for a PHP page, such as the HTTP GET command allows you to retrieve a PHP page from a ;;;;;;;;;;;;;;;;;;;
headers, by connecting to the Web server using a telnet Web server. The HEAD command is used to retrieve the ; Resource Limits ;
;;;;;;;;;;;;;;;;;;;
program. A telnet program uses a text-based interface and HTTP header information from a PHP page. max_execution_time = 120 ; Maximum execution time of each script, in seconds
allows you to view the content of a page in text form.
Some telnet programs require you to enable local echo
When using a telnet program to connect to a Web server, before you can view the commands you are typing. You
you must specify the URL or IP address of the Web server can consult your telnet program's documentation for Most Unix and Windows computers include a telnet program as part of
and the port number used by the Web server. A Web server more information about local echo. the operating system files. If you do not have a telnet program installed
typically uses port 80. on your computer, you can download a telnet program from the Tucows
Web site at www.tucows.com.
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


www.abccorp.com www.abccorp.com

RETRIEVE A PHP PAGE ¤ Type the URL or IP › Type GET /. ■ The HTML code for the VIEW HTTP HEADERS ¤ Type the URL or IP › Type HEAD /. ■ The HTTP header
⁄ At the command address of the Web server PHP page is displayed in ⁄ At the command address of the Web server information for the PHP
you want to connect to. ˇ Type the name of the the telnet window. you want to connect to. ˇ Type the name of the page is displayed.
prompt, type telnet. PHP page you want to prompt, type telnet. PHP page for which you
Then type the port number Then type the port number
used by the Web server. retrieve and then press Note: The HTML code may be used by the Web server. want to view the HTTP Note: The information may be
Enter. formatted differently, depending header information. formatted differently, depending
‹ Press Enter to start the on the Web server and telnet ‹ Press Enter to start the on the Web server and telnet
telnet program and connect telnet program and connect Á Type http/1.0 and then
program you are using. press Enter twice. program you are using.
to the Web server. to the Web server.
218 219
PHP PHP FUNCTIONS QUICK REFERENCE 12
ARRAY FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE Function


array_slice(array, offset
Description
Returns a slice from an array.
Returns
Array
Legend [, length])
plain courier text = required array_splice(array, offset Replaces elements in an array and returns the removed Array
italics = user-defined [, length [, replacement]]) elements.
[] = optional array_sum(array) Calculates the sum of values in an array. Mixed
... = list of items array_unique(array) Removes duplicate values. Array
| = or
array_unshift(array, Pushes elements onto the beginning of an array. Integer
variables)
APACHE-SPECIFIC FUNCTIONS
array_values(array) Returns all the values in an array. Array
Function Description Returns array_walk(array, function Applies a function to array elements. Integer
[, parameter])
apache_lookup_uri(filename) Returns information about a URI. Class
arsort(array) Sorts an array in descending order and retains index Void
apache_note(note_name Gets or, if the second parameter is used, sets values String association.
[, note_value]) in a notes table.
asort(array) Sorts an array in ascending order and retains index association. Void
ascii2ebcdic(ascii_string) Translates a string from ASCII to EBCDIC. Integer
compact(varnames) Creates an array using variables. Array
ebcdic2ascii(ebcdic_string) Translates a string from EBCDIC to ASCII. Integer
count(array) Counts array elements. Integer
getallheaders() Returns HTTP request headers. Array
current(array) Returns the current array element. Mixed
virtual(filename) Performs an Apache sub-request. Integer
each(array) Returns the current array element. Array
end(array) Makes the last element the current element. Mixed
ARRAY FUNCTIONS
extract(array [, extract_type Imports variables into the symbol table from an array. Integer
[, prefix]])
Function Description Returns in_array(value, array, strict) Indicates if a value exists in an array. Boolean
array([...]) Creates an array from provided parameters. Array key(array) Returns the key for the current element. Mixed
array_count_values(array) Counts the values in an array. Array krsort(array) Sorts an array by key in reverse order. Integer
array_diff(arrays) Returns values in the first array that do not occur Array ksort(array) Sorts an array by key. Integer
in the other arrays.
array_flip(array) Flips the values and keys in an array. Array list(variables) Assigns variables as if they were an array. Void
array_intersect(arrays) Returns values in the first array that occur in the other arrays. Array natcasesort(array) Sorts an array in a case-insensitive "natural order." Void
array_keys(array Returns all keys or only specified keys. Array natsort(array) Sorts an array in a "natural order." Void
[, search_value]) next(array) Advances the pointer one element in an array. Mixed
array_merge(arrays) Merges arrays. Array pos(array) Returns the current array element. Mixed
array_merge_recursive(arrays) Merges arrays recursively. Array prev(array) Moves the pointer back one element in an array. Mixed
array_multisort(array Sorts several arrays or a multi-dimensional array. Boolean range(low, high) Creates an array containing the integers in the specified range. Array
[, mixed])
reset(array) Moves the pointer to the first array element. Mixed
array_pad(array, size, value) Pads an array to the specified size with a value. Array
rsort(array) Sorts an array in descending order. Void
array_pop(array) Removes and returns the last array element. Mixed
shuffle(array) Shuffles an array. Void
array_push(array, variables) Pushes elements onto the end of an array. Integer
sizeof(array) Returns the number of array elements. Integer
array_rand(array [, num_req]) Returns one or more random entries from an array. Mixed
sort(array) Sorts an array in ascending order. Void
array_reverse(array) Returns array elements in reverse order. Array
uasort(array, function) Sorts an array using a function and retains index association. Void
array_search(value, array, Searches an array for a specified value and returns the Mixed
strict) corresponding key. uksort(array, function) Sorts an array by key using a function. Void
array_shift(array) Removes and returns the first array element. Mixed usort(array, function) Sorts an array by value using a function. Void

220 221
PHP PHP FUNCTIONS QUICK REFERENCE 12
CLASS/OBJECT FUNCTIONS

Function Description Returns


call_user_method(method_name, Calls a user method from an object. Mixed
object [, parameters])
call_user_method_array Calls a user method from an object using an array Mixed
(method_name, object of parameters.
[, parameters_array])
PHP FUNCTIONS QUICK REFERENCE class_exists(class_name) Checks if a class has been defined. Boolean
get_class(object) Returns the class name of an object. String
get_class_methods(class_name) Returns the methods for a class. Array
ASPELL FUNCTIONS
get_class_vars(class_name) Returns the default properties for a class. Array
Function Description Returns get_declared_classes() Returns defined classes for the current script. Array
aspell_check(link, word) Checks the spelling of a word. Boolean get_object_vars(object) Returns the properties of an object. Array
aspell_check_raw(link, word) Checks the spelling of a word without changing case Boolean get_parent_class(object) Returns the parent class name of an object. String
or trimming.
is_subclass_of(object, Determines if an object belongs to a subclass of a specified Boolean
aspell_new(master, personal) Loads a new directory. Integer superclass) superclass.
aspell_suggest(link, word) Suggests spellings for a word. Array method_exists(object, Checks if a method exists. Boolean
method_name)

CALENDAR FUNCTIONS
CLIENT URL LIBRARY (CURL) FUNCTIONS
Function Description Returns
easter_date([year]) Returns a UNIX timestamp for midnight on Easter Integer Function Description Returns
in a specified year. curl_close(handle) Closes a CURL session. Void
easter_days([year]) Returns the number of days after March 21 that Easter Integer curl_exec(handle) Executes a CURL session. Boolean
falls in a specified year.
curl_init([url]) Initializes a CURL session. Integer
frenchtojd(french) Converts a French Republican Calendar date to Integer
Julian Day Count. curl_setopt(handle, option, Sets an option for a CURL session. Boolean
value)
gregoriantojd(gregorian) Converts a Gregorian Calendar date to Julian Day Count. Integer
curl_version() Returns the current CURL version. String
jddayofweek(julianday, mode) Returns the day of the week. Mixed
jdmonthname(julianday, mode) Returns the month of the year. String
DATABASE FUNCTIONS
jdtofrench(julianday) Converts a Julian Day Count to a French Republican String
Calendar date.
jdtogregorian(julianday) Converts a Julian Day Count to a Gregorian Calendar date. String Database Abstraction Layer Functions
jdtojewish(julianday) Converts a Julian Day Count to a Jewish Calendar date. String Function Description Returns
jdtojulian(julianday) Converts a Julian Day Count to a Julian Calendar date. String dba_close(handle) Closes a database. Void
jdtounix(julianday) Converts a Julian Day Count to a UNIX timestamp. Integer dba_delete(key, handle) Deletes an entry in a database. String
jewishtojd(jewish) Converts a Jewish Calendar date to Julian Day Count. Integer dba_exists(key, handle) Checks if a key exists in a database. Boolean
juliantojd(julian) Converts a Julian Calendar date to Julian Day Count. Integer dba_fetch(key, handle) Returns the requested data. String
unixtojd(timestamp) Converts a UNIX timestamp to Julian Day Count. Integer dba_firstkey(handle) Returns the first key in a database. String

222 223
PHP PHP FUNCTIONS QUICK REFERENCE 12

DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE DBM Functions

Function Description Returns


dblist() Describes the DBM-compatible library being used. String
DATABASE FUNCTIONS (CONTINUED) dbmclose(dbm_id) Closes a DBM database. Boolean
dbmdelete(dbm_id, key) Deletes a value from a DBM database. Boolean
Database Abstraction Layer Functions (Continued) dbmexists(dbm_id, key) Checks if a value exists for a key in a DBM database. Boolean
Function Description Returns dbmfetch(dbm_id, key) Returns a value for a key from a DBM database. String
dba_insert(key, value, handle) Inserts an entry into a database. Boolean dbmfirstkey(dbm_id) Returns the first key in a DBM database. String
dba_nextkey(handle) Returns the next key in a database. String dbminsert(dbm_id, key, value) Inserts a key-value pair into a DBM database. Integer
dba_open(path, mode, handler) Opens a database. Integer dbmnextkey(dbm_id, key) Returns the next key in a DBM database. String
dba_optimize(handle) Optimizes a database. Boolean dbmopen(filename, flags) Opens a DBM database. Integer
dba_popen(path, mode, handler Opens a persistent connection to a database. Integer dbmreplace(dbm_id, key, value) Replaces a value in a DBM database. Boolean
[, ...])
dba_replace(key, value, Replaces or inserts an entry in a database. Boolean
handle)
dba_sync(handle) Synchronizes a database. Boolean Informix Functions

Function Description Returns


ifx_affected_rows(result_id) Returns the number of rows affected by a query. Integer
dBase Functions ifx_blobinfile_mode(mode) Sets the default BLOB mode. Void
Function Description Returns ifx_byteasvarchar(mode) Sets the default byte mode. Void
dbase_add_record(dbase_id, Adds a record to a dBase database. Boolean ifx_close([link_identifier]) Closes the connection to an Informix database. Integer
record)
ifx_connect([database Opens a connection to an Informix database. Integer
dbase_close(dbase_id) Closes a dBase database. Boolean [, userid [, password]]])
dbase_create(filename, fields) Creates a dBase database. Integer ifx_copy_blob(bid) Copies a BLOB object. Integer
dbase_delete_record Deletes a record from a dBase database. Boolean ifx_create_blob(type, mode, Creates a BLOB object. Integer
(dbase_id, record) param)
dbase_get_record(dbase_id, Returns a record from a dBase database. Array ifx_create_char(param) Creates a char object. Integer
record)
ifx_do(result_id) Executes a prepared SQL statement. Integer
dbase_get_record_with_names Returns a record from a dBase database as an associative array. Array
(dbase_id, record) ifx_error() Returns the last error. String
dbase_numfields(dbase_id) Returns the number of fields in a dBase database. Integer ifx_errormsg([error_code]) Returns the error message for the last error or a specified String
error code.
dbase_numrecords(dbase_id) Returns the number of records in a dBase database. Integer
ifx_fetch_row(result_id Fetches a row as an enumerated array. Array
dbase_open(filename, flags) Opens a dBase database. Integer [, position])
dbase_pack(dbase_id) Removes deleted records from a dBase database. Boolean ifx_fieldproperties Returns the field names and SQL field properties. Array
(result_id)
dbase_replace_record Replaces a record in a dBase database. Boolean
(dbase_id, record, record_num) ifx_fieldtypes(result_id) Returns the field names and SQL field types. Array

224 225
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)

InterBase Functions

Function Description Returns


PHP FUNCTIONS QUICK REFERENCE ibase_close([connection_id]) Closes the connection to an InterBase database. Integer
ibase_commit([link_identifier, Commits a transaction. Integer
trans_number])
DATABASE FUNCTIONS (CONTINUED) ibase_connect(database Opens a connection to an InterBase database. Integer
[, username [, password
[, charset [, buffers
Informix Functions (Continued) [, dialect [, role]]]]]])

Function Description Returns ibase_errmsg() Returns an error message. String


ifx_free_blob(bid) Deletes a BLOB object. Integer ibase_execute(query Executes a prepared query. Integer
[, bind_args])
ifx_free_char(bid) Deletes a char object. Integer
ibase_fetch_object Returns a row as an object. Object
ifx_free_result(result_id) Frees resources used by a query. Integer (result_id)
ifx_get_blob(bid) Returns the contents of a BLOB object. Integer ibase_fetch_row(result_id) Returns the next row in a result set. Array
ifx_get_char(bid) Returns the contents of a char object. Integer ibase_field_info(result_id, Returns information about a field in a result set. Array
field_number)
ifx_getsqlca(result_id) Returns the contents of sqlca.sqlerrd[0..5]after a query. Array
ibase_free_query(query) Frees a prepared query. Integer
ifx_htmltbl_result(result_id Formats rows of a query in an HTML table. Integer
[, html_table_options]) ibase_free_result(result_id) Frees a result set. Integer
ifx_nullformat(mode) Sets the default value for NULL values in a fetched row. Void ibase_num_fields(result_id) Returns the number of fields in a result set. Integer
ifx_num_fields(result_id) Returns the number of fields in a query. Integer ibase_pconnect(database Opens a persistent connection to an InterBase database. Integer
[, username [, password
ifx_num_rows(result_id) Returns the number of rows fetched for a query. Integer [, charset [, buffers
ifx_pconnect([database Opens a persistent connection to an Informix database. Integer [, dialect [, role]]]]]])
[, userid [, password]]]) ibase_prepare Prepares a query for execution. Integer
ifx_prepare(query Prepares an SQL statement for execution. Integer ([link_identifier, query])
[, link_identifier ibase_query([link_identifier, Executes a query. Integer
[, cursor_type query [, bind_args]])
[, blobidarray]]])
ibase_rollback Rolls back a transaction. Integer
ifx_query(query Executes a query. Integer ([link_identifier,
[, link_identifier trans_number])
[, cursor_type
[, blobidarray]]]) ibase_timefmt(format, Sets the format of timestamp, date and time columns Integer
[columntype]) returned from queries.
ifx_textasvarchar(mode) Sets the default text mode. Void
ibase_trans([trans_args Begins a transaction. Integer
ifx_update_blob(bid, content) Updates a BLOB object. Integer [, link_identifier]])
ifx_update_char(bid, content) Updates a char object. Integer
ifxus_close_slob(bid) Deletes a SLOB object. Integer
ifxus_create_slob(mode) Creates and opens a SLOB object. Integer Microsoft SQL Server Functions
ifxus_free_slob(bid) Deletes a SLOB object. Integer
Function Description Returns
ifxus_open_slob(bid, mode) Opens a SLOB object. Integer
mssql_close(link_id) Closes the connection to an MS SQL database. Integer
ifxus_read_slob(bid, bytes) Reads bytes from a SLOB object. Integer
mssql_connect([server_name Opens a connection to an MS SQL database. Integer
ifxus_seek_slob(bid, mode, Sets the current seek position of a SLOB object. Integer [, username [, password]]])
offset)
mssql_data_seek(result_id, Moves to a specified row in a result set. Integer
ifxus_tell_slob(bid) Returns the current seek position of a SLOB object. Integer row_number)
ifxus_write_slob(bid, content) Writes content to a SLOB object. Integer mssql_fetch_array(result_id) Returns the next row as an array. Integer

226 227
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE mSQL Functions (Continued)

Function Description Returns


msql_connect([hostname]) Opens a connection to an mSQL database. Integer
DATABASE FUNCTIONS (CONTINUED) msql_create_db(name Creates an mSQL database. Integer
[, link_id])
Microsoft SQL Server Functions (Continued) msql_createdb(name Creates an mSQL database. Integer
[, link_id])
Function Description Returns msql_data_seek(query_id, Moves to a specified row in a result set. Integer
mssql_fetch_field(result_id Returns field information. Object row_number)
[, field_offset]) msql_dbname(query_id, index) Returns the name of an mSQL database. String
mssql_fetch_object Returns the next row as an object. Integer msql_drop_db(name, link_id) Deletes an mSQL database. Integer
(result_id)
msql_dropdb(name, link_id) Deletes an mSQL database. Integer
mssql_fetch_row(result_id) Returns the next row as an enumerated array. Array
msql_error() Returns an error message from the last SQL operation. String
mssql_field_length(result_id Returns the length of a field in a result set. Integer
[, offset]) msql_fetch_array(query_id Returns the next row as an array. Integer
[, result_type])
mssql_field_name(result_id Returns the name of a field in a result set. Integer
[, offset]) msql_fetch_field(query_id, Returns field information. Object
field_offset)
mssql_field_seek(result_id, Moves to a specified field in a result set. Integer
field_offset) msql_fetch_object(query_id Returns the next row as an object. Integer
[, result_type])
mssql_field_type(result_id Returns the type of a field in a result set. String
[, offset]) msql_fetch_row(query_id) Returns the next row as an enumerated array. Array
mssql_free_result(result_id) Frees memory used by a result set. Integer msql_field_seek(query_id, Moves to a specified field in a result set. Integer
field_offset)
mssql_get_last_message() Returns the last server message. String
msql_fieldflags(query_id, Returns flags for a field in a result set. String
mssql_min_error_severity Sets the lower error severity. Void field)
(severity)
msql_fieldlen(query_id, field) Returns the length of a field in a result set. Integer
mssql_min_message_severity Sets the lower message severity. Void
(severity) msql_fieldname(query_id, Returns the name of a field in a result set. String
field)
mssql_num_fields(result_id) Returns the number of fields in a result set. Integer
msql_fieldtable(query_id, Returns the name of the table a field belongs to. Integer
mssql_num_rows(result_id) Returns the number of rows in a result set. Integer field)
mssql_pconnect([servername Opens a persistent connection to an MS SQL database. Integer msql_fieldtype(query_id, Returns the type of a field in a result set. String
[, username [, password]]]) field)
mssql_query(query [, link_id]) Executes a query. Integer msql_free_result(query_id) Frees the memory used by a result set. Integer
mssql_result(result_id, row, Returns the contents of a cell in a result set. Integer msql_freeresult(query_id) Frees the memory used by a result set. Integer
field)
msql_list_dbs() Lists the mSQL databases on a server. Integer
mssql_select_db(database, Makes an MS SQL database the current database. Integer
link_id) msql_list_fields(database, Lists the fields in a table. Integer
table)
msql_list_tables(database) Lists the tables in an mSQL database. Integer
msql_listdbs() Lists the mSQL databases on a server. Integer
mSQL Functions
msql_listfields(database, Lists the fields in a table. Integer
Function Description Returns table)
msql(database, query, link_id) Executes a query. Integer msql_listtables(database) Lists the tables in an mSQL database. Integer
msql_affected_rows(query_id) Returns the number of rows a query affects. Integer msql_num_fields(query_id) Returns the number of fields in a result set. Integer
msql_close(link_id) Closes the connection to an mSQL database. Integer msql_num_rows(query_id) Returns the number of rows in a result set. Integer

228 229
PHP PHP FUNCTIONS QUICK REFERENCE 12
PHP FUNCTIONS QUICK REFERENCE DATABASE FUNCTIONS (CONTINUED)

MySQL Functions (Continued)


DATABASE FUNCTIONS (CONTINUED) Function Description Returns
mysql_error([link_id]) Returns the error message from the last MySQL operation. String
mSQL Functions (Continued) mysql_fetch_array(result_id Returns the next row as an array. Array
[, result_type])
Function Description Returns
mysql_fetch_assoc(result_id) Returns a row as an associative array. Array
msql_numfields(query_id) Returns the number of fields in a result set. Integer
msql_numrows(query_id) Returns the number of rows in a result set. Integer mysql_fetch_field(result_id Returns field information. Object
[, field_offset])
msql_pconnect([hostname]) Opens a persistent connection to an mSQL database. Integer
mysql_fetch_lengths(result_id) Returns the length of each field in a result set. Array
msql_query(query, link_id) Executes a query. Integer
mysql_fetch_object(result_id Returns the next row as an object. Object
msql_regcase(string) Makes a regular expression for a case-insensitive match. String [, result_type])
msql_result(query_id, row, Returns the contents of a cell in a result set. Integer mysql_fetch_row(result_id) Returns the next row as an enumerated array. Array
field)
mysql_field_flags(result_id, Returns the flags for a field in a result set. String
msql_select_db(database, Makes an mSQL database the current database. Integer field)
link_id)
mysql_field_len(result_id, Returns the length of a field in a result set. Integer
msql_selectdb(database, Makes an mSQL database the current database. Integer field)
link_id)
mysql_field_name(result_id, Returns the name of a field in a result set. String
msql_tablename(query_id, Returns the name of the table for a field. String field)
field)
mysql_field_seek(result_id, Moves to a specified field offset. Integer
field_offset)
mysql_field_table(result_id, Returns the name of the table a field belongs to. String
field)
MySQL Functions
mysql_field_type(result_id, Returns the type of a field in a result set. String
Function Description Returns field)

mysql_affected_rows(link_id) Returns the number of rows affected by the last query. Integer mysql_free_result(result_id) Frees the memory used by a result set. Integer

mysql_change_user(user, Changes the logged in user of the connection. Integer mysql_insert_id([link_id]) Returns the ID generated from the last INSERT operation. Integer
password [, database mysql_list_dbs([link_id]) Lists the databases on a MySQL server. Integer
[, link_id]])
mysql_list_fields(database, Lists the fields in a table. Integer
mysql_close([link_id]) Closes the connection to a MySQL database. Integer table [, link_id])
mysql_connect([hostname Opens a connection to a MySQL database. Integer mysql_list_tables(database) Lists the tables in a MySQL database. Integer
[:port] [:/path/to/socket]
[,username [,password]]]) mysql_num_fields(result_id) Returns the number of fields in a result set. Integer
mysql_create_db(database Creates a MySQL database. Integer mysql_num_rows(result_id) Returns the number of rows in a result set. Integer
[, link_id])
mysql_pconnect([hostname Opens a persistent connection to a MySQL database. Integer
mysql_data_seek(result_id, Moves to a specified row in a result set. Integer [:port] [:/path/to/socket]
row_number) [, username [, password]]])
mysql_db_name(result_id, row Returns result data. Integer mysql_query(query [, link_id]) Executes a query. Integer
[, field])
mysql_result(result_id, row Returns the contents of a cell in a result set. Mixed
mysql_db_query(database, Executes a query. Integer [, field])
query [, link_id])
mysql_select_db(database Makes a MySQL database the current database. Integer
mysql_drop_db(database_name Deletes a MySQL database. Integer [, link_id])
[, link_id])
mysql_tablename(result_id, Returns the name of the table for a field. String
mysql_errno([link_id]) Returns the error number from the last MySQL operation. Integer index)

230 231
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)

Oracle 8 Functions (Continued)


PHP FUNCTIONS QUICK REFERENCE Function Description Returns
OCIPLogon(username, password Creates a persistent connection to an Oracle database. Integer
[, database])
DATABASE FUNCTIONS (CONTINUED)
OCIResult(statement, column) Returns column data for a fetched row. Mixed

Oracle 8 Functions OCIRollback(connection) Aborts all pending transactions on a connection. Integer


OCIRowCount(statement) Returns the number of affected rows in a result set. Integer
Function Description Returns
OCIServerVersion(connection) Returns server version information. String
OCIBindByName(statement, Binds a PHP variable to an Oracle Placeholder. Integer
ph_name, &variable, length OCIStatementType(statement) Returns the type of an OCI statement. String
[, type])
OCIColumnIsNULL(statement, Tests whether a column contains a NULL value. Integer
column)
OCIColumnName(statement, Returns the name of a column in a result set. String Oracle Functions
column_number)
Function Description Returns
OCIColumnSize(statement, Returns the size of a column in a result set. Integer
column) ora_bind(cursor, &variable, Binds a PHP variable to an Oracle parameter. Integer
SQLparameter, length [, type])
OCIColumnType(statement, Returns the type of a column in a result set. Mixed
column_number) ora_close(cursor) Closes an Oracle cursor. Integer
OCICommit(connection) Commits pending transactions on a connection. Integer ora_columnname(cursor, column) Returns the name of a column. String
OCIDefineByName(statement, Fetches a column into a PHP variable. Integer ora_columnsize(cursor, column) Returns the size of a column. Integer
column_name, &variable ora_columntype(cursor, column) Returns the type of a column. String
[, type])
OCIError([statement | Returns the code for the last error. Array ora_commit(connection) Commits a transaction. Integer
connection | global]) ora_commitoff(connection) Disables automatic committing of transactions. Integer
OCIExecute(statement [, mode]) Executes an SQL statement. Integer ora_commiton(connection) Enables automatic committing of transactions. Integer
OCIFetch(statement) Fetches the next row from a result set. Integer ora_do(connection, query) Parses and executes a statement. Then fetches the first row. Integer
OCIFetchInto(statement, Fetches the next row from a result set into an array. Integer ora_error(cursor | connection) Returns the message for the last error. String
result [, mode])
ora_errorcode(cursor | Returns the code for the last error. Integer
OCIFetchStatement(statement, Fetches all rows from a result set into an array. Integer connection)
variable)
ora_exec(cursor) Executes a parsed statement on a cursor. Integer
OCIFreeCursor(statement) Frees the resources used by the cursor for a statement. Integer
ora_fetch(cursor) Fetches a row from a cursor. Integer
OCIFreeDesc(lob) Deletes a large object descriptor. Integer
ora_fetch_into(cursor, result Fetches a row into a result array. Integer
OCIFreeStatement(statement) Frees the resources used by a statement. Integer [, flags])
OCIInternalDebug(OnOff) Enables or disables internal debugging. Void ora_getcolumn(cursor, column) Returns data from a column. Mixed
OCILogOff(connection) Closes the connection to an Oracle Database. Integer ora_logoff(connection) Closes an Oracle connection. Integer
OCILogon(username, password Creates a connection to an Oracle database. Integer ora_logon(user, password) Opens an Oracle connection. Integer
[, database])
ora_numcols(cursor_ind) Returns the number of columns in a result set. Integer
OCINewCursor(connection) Returns a new cursor for a connection. Integer
ora_numrows(cursor_ind) Returns the number of rows in a result set. Integer
OCINewDescriptor(connection Initializes a new empty LOB or FILE descriptor. String
[, type]) ora_open(connection) Opens an Oracle cursor. Integer
OCINLogon(username, password Creates a new connection to an Oracle database. Integer ora_parse(cursor, Parses an SQL statement. Integer
[, database]) SQL_statement, defer)
OCINumCols(statement) Returns the number of columns in a result set. Integer ora_plogon(user, password) Opens a persistent connection to an Oracle database. Integer
OCIParse(connection, query) Parses a query. Integer ora_rollback(connection) Aborts a transaction. Integer

232 233
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)

PostgreSQL Functions (Continued)

PHP FUNCTIONS QUICK REFERENCE Function


pg_loopen(connection,
object_id, mode)
Description
Opens a large object.
Returns
Integer

pg_loread(file_descriptor, Reads a specified number of bytes from a large object. String


DATABASE FUNCTIONS (CONTINUED) len)
pg_loreadall(file_descriptor) Reads an entire large object and sends it to a browser. Void
PostgreSQL Functions pg_lounlink(connection, Deletes a large object. Void
object_id)
Function Description Returns pg_lowrite(file_descriptor, Writes to a large object. Integer
pg_client_encoding Returns the client encoding. String buf)
([connection])
pg_numfields(result_id) Returns the number of fields in a result set. Integer
pg_close(connection) Closes a PostgreSQL connection. Boolean pg_numrows(result_id) Returns the number of rows in a result set. Integer
pg_cmdtuples(result_id) Returns the number of tuples affected by queries. Integer pg_options(connection) Returns connection options. String
pg_connect(conn_string) Opens a connection to a PostgreSQL database. Integer pg_pconnect(conn_string) Opens a persistent connection to a PostgreSQL database. Integer
pg_dbname(connection) Returns the name of a database. String pg_port(connection) Returns the port number for a connection. Integer
pg_end_copy([connection]) Synchronizes PostgreSQL frontend with backend after a copy. Boolean pg_put_line([connection, Sends a NULL-terminated string to the PostgreSQL Boolean
pg_errormessage(connection) Returns an error message. String data]) backend server.
pg_exec(connection, query) Executes a query. Integer pg_result(result_id, Returns values from a result set. Mixed
row_number, field_name)
pg_fetch_array(result, row Fetches a row as an array. Array
[, result_type]) pg_set_client_encoding Sets the client encoding. Integer
([connection, encoding])
pg_fetch_object(result, row Fetches a row as an object. Object
[, result_type]) pg_trace(filename [, mode Enables tracing of a PostgreSQL connection. Boolean
[, connection]])
pg_fetch_row(result, row) Fetches a row as an enumerated array. Array
pg_tty(connection) Returns the connection's associated tty name. String
pg_fieldisnull(result_id, Indicates whether a field contains a NULL value. Integer
row, field) pg_untrace([connection]) Disables tracing of a PostgreSQL connection. Boolean
pg_fieldname(result_id, Returns the name of a field in a result set. String
field_number)
pg_fieldnum(result_id, Returns the number of a field in a result set. Integer Sybase Functions
field_name)
Function Description Returns
pg_fieldprtlen(result_id, Returns the printed length of a field in a result set. Integer
row_number, field_name) sybase_affected_rows Returns the number of rows affected by the last query. Integer
([link_id])
pg_fieldsize(result_id, Returns the internal storage size of a field in a result set. Integer
field_number) sybase_close(link_id) Closes the Sybase connection. Boolean
pg_fieldtype(result_id, Returns the type of a field in a result set. String sybase_connect(server_name, Opens a connection to a Sybase server. Integer
field_number) username, password
[, charset])
pg_freeresult(result_id) Frees the memory used by a result set. Integer
sybase_data_seek(result_id, Moves to a specified row in a result set. Boolean
pg_getlastoid(result_id) Returns the last object identifier. Integer row_number)
pg_host(connection) Returns the connection's associated host name. String sybase_fetch_array(result_id) Fetches the next row as an array. Array
pg_loclose(file_descriptor) Closes a large object. Void sybase_fetch_field(result_id Returns field information. Object
[, field_offset])
pg_locreate(connection) Creates a large object. Integer
pg_loexport(object_id, file Exports a large object to a file. Boolean sybase_fetch_object(result_id) Fetches the next row as an object. Integer
[, connection_id]) sybase_fetch_row(result_id) Fetches the next row as an enumerated array. Array
pg_loimport(file Imports a large object from a file. Integer sybase_field_seek(result_id, Moves to a specified field offset. Integer
[, connection_id]) field_offset)

234 235
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE Unified ODBC Functions (Continued)

Function Description Returns


odbc_connect(DSN, userid, Connects to an ODBC data source. Integer
DATABASE FUNCTIONS (CONTINUED) password [, cursor_type])
odbc_cursor(result_id) Returns the cursorname for a result set. String
Sybase Functions (Continued) odbc_do(connection_id, query) Prepares and executes a query. Integer
Function Description Returns odbc_error([connection_id]) Returns the last error code. Integer
sybase_free_result(result_id) Frees the memory used by a result set. Boolean odbc_errormsg([connection_id]) Returns the last error message. Integer
sybase_get_last_message() Returns the last message from the server. String odbc_exec(connection_id, Prepares and executes a query. Integer
query)
sybase_min_client_severity Sets the minimum client severity level. Void
(severity) odbc_execute(result_id, Executes a prepared SQL statement. Integer
[parameters])
sybase_min_error_severity Sets the minimum error severity level. Void
(severity) odbc_fetch_into(result_id Fetches a row from a result set. Integer
[, row_number, result])
sybase_min_message_severity Sets the minimum message severity level. Void
(severity) odbc_fetch_row(result_id Fetches a row from a result set. Integer
[, row_number])
sybase_min_server_severity Sets the minimum server severity level. Void
(severity) odbc_field_len(result_id, Returns the length of a field in a result set. Integer
field_number)
sybase_num_fields(result_id) Returns the number of fields in a result set. Integer
odbc_field_name(result_id, Returns the name of a field in a result set. String
sybase_num_rows(result_id) Returns the number of rows in a result set. Integer field_number)
sybase_pconnect(server_name, Opens a persistent connection to a Sybase server. Integer odbc_field_num(result_id, Returns the column number for a field in a result set. Integer
username, password field_name)
[, charset])
odbc_field_precision Returns the length of a field in a result set. String
sybase_query(query, link_id) Executes a Sybase query. Integer (result_id, field_number)
sybase_result(result_id, row, Fetches the contents of a cell in a result set. String odbc_field_scale(result_id, Returns the scale of a field in a result set. String
field) field_number)
sybase_select_db(database, Makes a Sybase database the current database. Boolean odbc_field_type(result_id, Returns the type of a field in a result set. String
link_id) field_number)
odbc_foreignkeys Returns information about foreign keys in a table. Integer
(connection_id, pk_qualifier,
pk_owner, pk_table,
Unified ODBC Functions fk_qualifier, fk_owner,
fk_table)
Function Description Returns odbc_free_result(result_id) Frees the memory used by a result set. Integer
odbc_autocommit Sets or gets autocommit behavior for a database. Integer odbc_gettypeinfo Returns information about the data types supported by Integer
(connection_id, [OnOff])
(connection_id [, data_type]) a data source.
odbc_binmode(result_id, mode) Sets the mode for converting binary data. Integer odbc_longreadlen(result_id, Determines the number of bytes returned by fields of Integer
odbc_close(connection_id) Closes an ODBC connection. Void length) the LONG data type.
odbc_close_all() Closes all ODBC connections. Void odbc_num_fields(result_id) Returns the number of fields in a result set. Integer
odbc_columnprivileges Lists columns and privileges for a table. Integer odbc_num_rows(result_id) Returns the number of rows in a result set. Integer
(connection_id [, qualifier
[, owner [, table_name odbc_pconnect(DSN, userid, Opens a persistent connection to an ODBC data source. Integer
[, column_name]]]]) password [, cursor_type])

odbc_columns(connection_id Lists all column names in a specified range. Integer odbc_prepare(connection_id, Prepares an SQL statement for execution. Integer
[, qualifier [, owner query)
[, table_name odbc_primarykeys Gets the column names that make up the primary key Integer
[, column_name]]]]) (connection_id, qualifier, for a table.
odbc_commit(connection_id) Commits the ODBC transactions on a connection. Integer owner, table)

236 237
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATE AND TIME FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE Function Description Returns


gmstrftime(format Formats a time/date using locale settings and returns String
[, timestamp]) a GMT time/date.
DATABASE FUNCTIONS (CONTINUED) localtime([timestamp Returns the local time. Array
[, is_associative]])
Unified ODBC Functions (Continued) microtime() Returns the current UNIX timestamp with microseconds. String
mktime(hour, minute, second, Returns the UNIX timestamp for a date. Integer
Function Description Returns month, day, year [, is_dst])
odbc_procedurecolumns Retrieves information about the parameters for procedures. Integer strftime(format [, timestamp]) Formats a local time/date using locale settings. String
(connection_id, [, qualifier
[, owner [ ,proc strtotime(time [, now]) Parses an English datetime description into a UNIX timestamp. Integer
[, column]]]])
odbc_procedures(connection_id, Gets a list of procedures in a data source. Integer time() Returns the current UNIX time in seconds. Integer
[, qualifier [, owner
[, name]]])
odbc_result(result_id, field) Returns the contents of a field in a result set. String DIRECTORY FUNCTIONS

odbc_result_all(result_id Prints a result set in an HTML table. Integer


[, format]) Function Description Returns
odbc_rollback(connection_id) Aborts all transactions on a connection. Integer chdir(directory) Sets a directory as the current directory. Integer
odbc_setoption(ID, function, Sets an ODBC option. Integer chroot(directory) Sets a directory as the current root directory. Integer
option, parameter) closedir(dir_handle) Closes a directory handle. Void
odbc_specialcolumns Returns the optimal set of columns that uniquely identifies Integer dir(directory) Returns a directory class. New
(connection_id, type, a row or columns that are automatically updated.
qualifier, owner, table, getcwd() Returns the current working directory. String
scope, nullable)
opendir(path) Opens a directory handle. Integer
odbc_statistics(connection_id, Returns statistics about a table. Integer
qualifier, owner, table_name, readdir(dir_handle) Reads the next entry from a directory. String
unique, accuracy)
rewinddir(dir_handle) Resets a directory handle to the beginning of the directory. Void
odbc_tableprivileges Lists the tables and their privileges. Integer
(connection_id [, qualifier
[, owner [, name]]]) DOM XML FUNCTIONS
odbc_tables(connection_id Lists the tables in a data source. Integer
[, qualifier [, owner
[, name [, types]]]]) Function Description Returns
domxml_add_root(doc, name) Adds a root element node to a DOM document. Resource
domxml_attributes(node) Returns all attributes of a node. Array
DATE AND TIME FUNCTIONS
domxml_children(doc | node) Returns all children of a node. Array

Function Description Returns domxml_dumpmem(doc) Creates an XML document from the DOM representation. String
checkdate(month, day, year) Validates a date. Integer domxml_get_attribute(node, Returns an attribute of a node. Object
name)
date(format [, timestamp]) Formats a local time/date. String
domxml_new_child(name, Adds a new child to a node. Resource
getdate([timestamp]) Returns date/time information. Array content)
gettimeofday() Returns the current time. Array domxml_new_xmldoc(version) Creates a DOM document from scratch. Object
gmdate(format [, timestamp]) Formats a local date/time and returns a GMT date/time. String domxml_root(doc) Returns the root element node of a DOM document. Object
gmmktime(hour, minute, second, Returns the UNIX timestamp for a GMT time/date. Integer domxml_set_attribute(node, Sets an attribute of a node. Object
month, day, year [, is_dst]) name, value)

238 239
PHP PHP FUNCTIONS QUICK REFERENCE 12
FILESYSTEM FUNCTIONS (CONTINUED)

Function Description Returns

PHP FUNCTIONS QUICK REFERENCE fclose(file_pointer)


feof(file_pointer)
Closes a file.
Tests for end-of-file on a file.
Integer
Integer
fflush(file_pointer) Flushes the buffered output to a file. Integer
DOM XML FUNCTIONS (CONTINUED) fgetc(file_pointer) Reads the next character from a file. String
fgetcsv(file_pointer, length Returns the next line of a file. Array
Function Description Returns [, delimiter])
xmldoc(str) Creates a DOM object from an XML document. Object fgets(file_pointer, length) Reads a line of a specific length from a file. String
xmldocfile(filename) Creates a DOM object from an XML file. Object fgetss(file_pointer, length Reads a line of a specific length from a file and strips String
[, allowable_tags]) PHP and HTML tags.
xmltree(str) Creates a tree of PHP objects from an XML document. Object
file(filename Reads an entire file. Array
xpath_eval(xpath_context) Evaluates an xpath expression. Array [, use_include_path])
xpath_new_context(doc) Creates a new xpath context. Object file_exists(filename) Checks whether a file exists. Boolean
fileatime(filename) Returns the time a file was last accessed. Integer
ERROR HANDLING AND LOGGING FUNCTIONS filectime(filename) Returns the time the inode data of a file was last changed. Integer
filegroup(filename) Returns a file owner's group ID. Integer
Function Description Returns
fileinode(filename) Returns a file's inode number. Integer
error_log(message, Sends an error message. Integer
message_type [, destination filemtime(filename) Returns the time a file was last modified. Integer
[, extra_headers]])
fileowner(filename) Returns a file owner's user ID. Integer
error_reporting([level]) Sets which PHP errors are reported. Integer fileperms(filename) Returns a file's permissions. Integer
restore_error_handler() Restores the previous error handler function. Void filesize(filename) Returns the size of a file. Integer
set_error_handler Sets a user-defined error handler function. String filetype(filename) Returns the type of a file. String
(error_handler)
trigger_error(error_msg Generates a user-level error message. Void flock(file_pointer, operation Sets or releases a lock on a file. Boolean
[, error_type]) [, wouldblock])

user_error(error_msg Generates a user-level error message. Void fopen(filename, mode Opens a file. Integer
[, error_type]) [, use_include_path])
fpassthru(file_pointer) Outputs all remaining data from a file. Integer
fputs(file_pointer, string Writes a string of a specific length to a file. Integer
FILESYSTEM FUNCTIONS [, length])
fread(file_pointer, length) Reads a specific number of characters from a file. String
Function Description Returns fscanf(handle, format Parses input from a file according to a specified format. Mixed
basename(path) Returns the filename from a path. String [, var1...])
chgrp(filename, group) Assigns a file to a group. Integer fseek(file_pointer, offset Moves the pointer in a file. Integer
[, whence])
chmod(filename, mode) Changes the mode of a file. Integer
fstat(file_pointer) Returns information about a file. Array
chown(filename, user) Changes the owner of a file. Integer
ftell(file_pointer) Returns the position of the pointer in a file. Integer
clearstatcache() Clears the file stat cache. Void
ftruncate(file_pointer, size) Truncates a file to a specific length. Integer
copy(source, destination) Copies a file. Integer
fwrite(file_pointer, string Writes a string of a specific length to a file. Integer
dirname(path) Returns the directory from a path. String [, length])
diskfreespace(directory) Returns the available space in a directory. Float is_dir(filename) Indicates whether a file is a directory. Boolean

240 241
PHP PHP FUNCTIONS QUICK REFERENCE 12
FORMS DATA FORMAT FUNCTIONS

Function Description Returns


PHP FUNCTIONS QUICK REFERENCE fdf_close(fdf_document) Closes an FDF document. Boolean
fdf_create() Creates an FDF document. Integer
fdf_get_file(fdf_document) Returns the value of the /F key in an FDF document. String
FILESYSTEM FUNCTIONS (CONTINUED)
fdf_get_status(fdf_document) Returns the value of the /STATUS key in an FDF document. String
Function Description Returns fdf_get_value(fdf_document, Returns the value of a field in an FDF document. String
fieldname)
is_executable(filename) Indicates whether a file is executable. Boolean
fdf_next_field_name Returns the name of the next field in an FDF document. String
is_file(filename) Indicates whether a file is a regular file. Boolean (fdf_document, fieldname)
is_link(filename) Indicates whether a file is a symbolic link. Boolean fdf_open(filename) Opens an FDF document. Integer
is_readable(filename) Indicates whether a file is readable. Boolean fdf_save(filename) Saves an FDF document. Integer
is_uploaded_file(filename) Indicates whether a file was uploaded via HTTP POST. Boolean fdf_set_ap(fdf_document, Sets the appearance of a field in an FDF document. Boolean
is_writable(filename) Indicates whether a file can be written to. Boolean fieldname, face, filename,
pagenumber)
is_writeable(filename) Indicates whether a file can be written to. Boolean
fdf_set_file(fdf_document, Sets the value of the /F key in an FDF document. Boolean
link(target, link) Creates a hard link. Integer filename)
linkinfo(path) Returns information about a link. Integer fdf_set_flags(fdf_document, Sets flags of a field in an FDF document. Boolean
fieldname, whichFlags,
lstat(filename) Returns information about a file or a symbolic link. Array newFlags)
mkdir(pathname, mode) Creates a directory. Integer fdf_set_javascript_action Sets a JavaScript action for a field in an FDF document. Boolean
(fdf_document, fieldname,
move_uploaded_file(filename, Moves an uploaded file to a new location. Boolean trigger, script)
destination)
fdf_set_opt(fdf_document, Sets an option of a field in an FDF document. Boolean
pclose(file_pointer) Closes a process file pointer. Integer fieldname, element, string1,
popen(command, mode) Opens a process file pointer. Integer string2)
readfile(filename Reads and outputs a file. Integer fdf_set_status(fdf_document, Sets the value of the /STATUS key in an FDF document. Boolean
[, use_include_path]) status)
readlink(path) Returns the target of a symbolic link. String fdf_set_submit_form_action Sets a submit form action for a field in an FDF document. Boolean
(fdf_document, fieldname,
realpath(path) Returns the canonicalized absolute pathname. String trigger, script, flags)
rename(oldname, newname) Renames a file. Integer fdf_set_value(fdf_document, Sets the value of a field in an FDF document. Boolean
fieldname, value, isname)
rewind(file_pointer) Rewinds the pointer to the beginning of a file. Integer
rmdir(directory) Removes a directory. Integer
set_file_buffer Sets the size of the buffer for a file. Integer FTP FUNCTIONS
(file_pointer, buffer)
stat(filename) Returns information about a file. Array Function Description Returns
symlink(target, link) Creates a symbolic link. Integer ftp_cdup(ftp_stream) Changes to the parent directory on an FTP server. Integer
tempnam(directory, prefix) Creates a unique temporary file name. String ftp_chdir(ftp_stream, Changes to another directory on an FTP server. Integer
directory)
tmpfile() Creates a temporary file. Integer
ftp_connect(host [, port]) Opens a connection to an FTP server. Integer
touch(filename [, time]) Sets the modification time of a file. Integer
ftp_delete(ftp_stream, path) Deletes a file on an FTP server. Integer
umask(mask) Changes the current umask. Integer
ftp_fget(ftp_stream, fp, Downloads a file from an FTP server and saves it to a file. Integer
unlink(filename) Deletes a file. Integer remote_file, mode)

242 243
PHP PHP FUNCTIONS QUICK REFERENCE 12
FUNCTION HANDLING FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE Function Description Returns


func_get_arg(arg_num) Returns an item from the argument list. Mixed
func_get_args() Returns a function's argument list. Array
FTP FUNCTIONS (CONTINUED)
func_num_args() Returns the number of arguments passed to a function. Integer
Function Description Returns function_exists(function_name) Checks if a function has been defined. Boolean
ftp_fput(ftp_stream, Uploads data from a file to an FTP server. Integer get_defined_functions() Returns all defined functions. Array
remote_file, fp, mode)
register_shutdown_function Registers a function to be executed when the script Integer
ftp_get(ftp_stream, Downloads a file from an FTP server. Integer (function) finishes processing.
local_file, remote_file, mode)
ftp_login(ftp_stream, Logs in an FTP connection. Integer
username, password) HTTP FUNCTIONS
ftp_mdtm(ftp_stream, Returns the time a file was last modified on an FTP server. Integer
remote_file) Function Description Returns
ftp_mkdir(ftp_stream, Creates a directory on an FTP server. String header(string) Sends an HTTP header. Integer
directory)
headers_sent() Checks if headers have been sent. Boolean
ftp_nlist(ftp_stream, Returns a list of files in a directory on an FTP server. Array
directory) setcookie(name [, value Sends a cookie. Integer
[, expire [, path [, domain
ftp_pasv(ftp_stream, pasv) Turns passive mode on or off for an FTP server. Integer [, secure]]]]])
ftp_put(ftp_stream, Uploads a file to an FTP server. Integer
remote_file, local_file, mode)
IMAGE FUNCTIONS
ftp_pwd(ftp_stream) Returns the name of the current directory on an FTP server. String
ftp_quit(ftp_stream) Closes a connection to an FTP server. Integer
Function Description Returns
ftp_rawlist(ftp_stream, Returns a detailed list of files in a directory on an FTP server. Array getimagesize(filename Returns the size of an image. Array
directory) [, image_info])
ftp_rename(ftp_stream, Renames a file on an FTP server. Integer imagearc(im, cx, cy, width, Draws a partial ellipse. Integer
from, to) height, start, end, col)
ftp_rmdir(ftp_stream, Removes a directory on an FTP server. Integer imagechar(im, font, x, y, Draws a character horizontally. Integer
directory) c, col)
ftp_site(ftp_stream, cmd) Sends a SITE command to an FTP server. Integer imagecharup(im, font, x, y, Draws a character vertically. Integer
ftp_size(ftp_stream, Returns the size of a file on an FTP server. Integer c, col)
remote_file) imagecolorallocate(im, red, Allocates a color for an image. Integer
ftp_systype(ftp_stream) Returns the system type identifier of a remote FTP server. String green, blue)
imagecolorat(im, x, y) Returns the index of the color of a pixel. Integer
imagecolorclosest(im, red, Returns the index of the closest color to the specified color. Integer
FUNCTION HANDLING FUNCTIONS green, blue)
imagecolordeallocate De-allocates a color for an image. Integer
Function Description Returns (im,index)
call_user_func(function_name Calls a user function. Mixed imagecolorexact(im, red, Returns the index of a color. Integer
[, parameter [, ...]]) green, blue)
call_user_func_array Calls a user function using an array of parameters. Mixed imagecolorresolve(im, red, Returns the index of a color or its closest possible alternative. Integer
(function_name green, blue)
[, parameters_array])
imagecolorset(im, index, Sets the color for a palette index. Boolean
create_function(args, code) Creates an anonymous function. String red, green, blue)

244 245
PHP PHP FUNCTIONS QUICK REFERENCE 12
IMAGE FUNCTIONS (CONTINUED)

Function Description Returns


imageloadfont(filename) Loads a new bitmap font. Integer
PHP FUNCTIONS QUICK REFERENCE imagepng(im [, filename]) Outputs a PNG image to a browser or file. Integer
imagepolygon(im, points, Draws a polygon. Integer
num_points, col)
IMAGE FUNCTIONS (CONTINUED) imagepsbbox(text, font, Returns the bounding box of text using a PostScript Array
size [, space [, tightness Type1 font.
[, angle]]])
Function Description Returns
imagepsencodefont Changes the character-encoding vector of a PostScript Integer
imagecolorsforindex(im, index) Returns the color values for an index. Array (font_index, encodingfile) Type1 font.
imagecolorstotal(im) Returns the number of colors in an image's palette. Integer imagepsextendfont Extends or condenses a font. Boolean
imagecolortransparent(im Defines a color as transparent. Integer (font_index, extend)
[, col]) imagepsfreefont(fontindex) Frees memory used by a PostScript Type1 font. Void
imagecopy(dst_im, src_im, Copies part of an image. Integer imagepsloadfont(filename) Loads a PostScript Type1 font from a file. Integer
dstX, dstY, srcX, srcY,
srcW, srcH) imagepsslantfont(font_index, Slants a PostScript Type1 font. Boolean
imagecopyresized(dst_im, Copies and resizes part of an image. Integer slant)
src_im, dstX, dstY, srcX, imagepstext(im, text, Draws a text string on an image using a PostScript Type1 font. Array
srcY, dstW, dstH, srcW, srcH) font, size, foreground,
imagecreate(width, height) Creates an image. Integer background, x, y [, space
[, tightness [, angle
imagecreatefromgif(filename) Creates an image from a GIF file. Integer [,antialias_steps]]]])
imagecreatefromjpeg(filename) Creates an image from a JPEG file. Integer imagerectangle(im, x1, y1, Draws a rectangle. Integer
x2, y2, col)
imagecreatefrompng(filename) Creates an image from a PNG file. Integer
imagesetpixel(im, x, y, col) Draws a pixel. Integer
imagecreatefromstring(image) Creates an image from the image stream in a string. Integer
imagestring(im, font, x, y, Draws a string horizontally. Integer
imagecreatefromwbmp(filename) Creates an image from a WBMP file. Integer s, col)
imagedashedline(im, x1, y1, Draws a dashed line. Integer imagestringup(im, font, x, y, Draws a string vertically. Integer
x2, y2, col) s, col)
imagedestroy(im) Destroys an image. Integer imagesx(im) Returns the width of an image. Integer
imagefill(im, x, y, col) Flood fills an image. Integer imagesy(im) Returns the height of an image. Integer
imagefilledpolygon(im, Draws a filled polygon. Integer imagettfbbox(size, angle, Returns the bounding box of text using a TrueType font. Array
points, num_points, col) fontfile, text)
imagefilledrectangle(im, x1, Draws a filled rectangle. Integer imagettftext(im, size, angle, Writes text to an image using a TrueType font. Array
y1, x2, y2, col) x, y, col, fontfile, text)
imagefilltoborder(im, x, y, Flood fills an image with a specified border color. Integer imagetypes() Returns the image types supported by this PHP build. Integer
border, col)
imagewbmp(im [, filename]) Outputs a WBMP image to a browser or file. Integer
imagefontheight(font) Returns the height of a font. Integer
read_exif_data(filename) Returns the EXIF headers from a JPEG image. Array
imagefontwidth(font) Returns the width of a font. Integer
imagegammacorrect(im, Applies a gamma correction to a GD image. Integer
inputgamma, outputgamma)
IMAP, POP3 AND NNTP FUNCTIONS
imagegif(im [, filename]) Outputs a GIF image to a browser or file. Integer
imageinterlace(im Turns interlacing on or off for an image. Integer Function Description Returns
[, interlace])
imap_8bit(string) Converts an 8-bit string to a quoted-printable string. String
imagejpeg(im [, filename Outputs a JPEG image to a browser or file. Integer
[, quality]]) imap_alerts() Returns all IMAP alert messages for this page request. Array
imageline(im, x1, y1, x2, Draws a line. Integer imap_append(imap_stream, Appends a string message to a mailbox. Integer
y2, col) mbox, message [, flags])

246 247
PHP PHP FUNCTIONS QUICK REFERENCE 12
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED)
PHP FUNCTIONS QUICK REFERENCE Function Description Returns
imap_headers(imap_stream) Returns the headers for all messages in a mailbox. Array
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED) imap_last_error() Returns the last IMAP error for this page request. String
imap_listmailbox Returns a list of mailboxes. Array
Function Description Returns (imap_stream, ref, pattern)
imap_base64(text) Decodes base64 encoded text. String imap_listsubscribed Returns a list of all the subscribed mailboxes. Array
imap_binary(string) Converts an 8-bit string to a base64 string. String (imap_stream, ref, pattern)
imap_body(imap_stream, Returns a message body. String imap_mail(to, subject, Sends an e-mail message. String
msg_number [, flags]) message [,additional_headers
[, cc [, bcc [, rpath]]]])
imap_check(imap_stream) Checks the current mailbox. Object
imap_mail_compose(envelope, Creates a MIME message using the provided envelope String
imap_clearflag_full(stream, Clears message flags. String body) and body.
sequence, flag, options)
imap_mail_copy(imap_stream, Copies messages to a mailbox. Integer
imap_close(imap_stream Closes an IMAP stream. Integer msglist, mbox [, flags])
[, flags])
imap_mail_move(imap_stream, Moves messages to a mailbox. Integer
imap_createmailbox Creates a new mailbox. Integer msglist, mbox [, flags])
(imap_stream, mbox)
imap_mailboxmsginfo Returns information about the current mailbox. Object
imap_delete(imap_stream, Marks a message for deletion from the current mailbox. Integer (imap_stream)
msg_number [, flags])
imap_mime_header_decode(text) Decodes MIME header elements. Array
imap_deletemailbox Deletes a mailbox. Integer
(imap_stream, mbox) imap_msgno(imap_stream, uid) Returns the message sequence number for a UID. Integer
imap_errors() Returns all IMAP errors for this page request. Array imap_num_msg(imap_stream) Returns the number of messages in the current mailbox. Integer
imap_expunge(imap_stream) Deletes all messages marked for deletion. Integer imap_num_recent(imap_stream) Returns the number of recent messages in the current mailbox. Integer
imap_fetch_overview Returns an overview of header information for a message. Array imap_open(mbox, username, Opens an IMAP stream to a mailbox. Integer
(imap_stream, sequence password [, flags])
[, flags]) imap_ping(imap_stream) Checks if an IMAP stream is still active. Integer
imap_fetchbody(imap_stream, Fetches a section of the body of a message. String imap_qprint(string) Converts a quoted-printable string to an 8-bit string. String
msg_number, part_number
[, flags]) imap_renamemailbox Renames a mailbox. Integer
(imap_stream, old_mbox,
imap_fetchheader(imap_stream, Returns the header for a message. String new_mbox)
msg_number, flags)
imap_fetchstructure Returns the structure of a message. Object imap_reopen(imap_stream, Re-opens an IMAP stream to a new mailbox. Integer
mbox [, flags])
(imap_stream, msg_number
[, flags]) imap_rfc822_parse_adrlist Parses an address string. Array
(address, default_host)
imap_get_quota(imap_stream, Returns the quota level settings and usage statistics Array
quota_root) for a mailbox. imap_rfc822_parse_headers Parses mail headers from a string. Object
(headers [, defaulthost])
imap_getmailboxes Returns detailed information about each mailbox. Array
(imap_stream, ref, pattern) imap_rfc822_write_address Returns a formatted e-mail address from the provided String
imap_getsubscribed Returns a list of all the subscribed mailboxes. Array (mbox, host, personal) mailbox, host and personal information.
(imap_stream, ref, pattern) imap_scanmailbox(imap_stream, Searches the names of mailboxes for a specified string. Array
ref, pattern, content)
imap_header(imap_stream, Returns the header of a message. Object
msg_number [, fromlength imap_search(imap_stream, Returns messages matching the provided criteria. Array
[, subjectlength criteria, flags)
[, defaulthost]]])
imap_set_quota(imap_stream, Sets a quota for a mailbox. Integer
imap_headerinfo(imap_stream, Returns the header of a message. Object quota_root, quota_limit)
msg_number [, fromlength
[, subjectlength imap_setflag_full(stream, Sets flags on messages. String
[, defaulthost]]]) 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 Description Returns Function Description Returns


imap_sort(stream, criteria, Sorts message headers. Array bindec(binary_string) Converts a binary value to decimal. Integer
reverse, options)
ceil(number) Rounds fractions up to the next highest integer. Integer
imap_status(imap_stream, Returns status information on a mailbox other than the Object
mbox, options) current mailbox. cos(arg) Returns the cosine of an argument in radians. Float
imap_subscribe(imap_stream, Subscribes to a mailbox. Integer decbin(number) Converts a decimal number to binary. String
mbox) dechex(number) Converts a decimal number to hexadecimal. String
imap_uid(imap_stream, Returns the UID for a message sequence number. Integer decoct(number) Converts a decimal number to octal. String
msg_number)
deg2rad(number) Converts the number in degrees to the radian equivalent. Double
imap_undelete(imap_stream, Unmarks a message for deletion. Integer
msg_number) exp(arg) Returns e to the power of an argument. Float
imap_unsubscribe Unsubscribes from a mailbox. Integer floor(number) Rounds fractions down to the next lowest integer. Integer
(imap_stream, mbox)
getrandmax() Returns the largest possible random value. Integer
imap_utf7_decode(text) Decodes a modified UTF-7 encoded string. String
hexdec(hex_string) Converts a hexadecimal value to decimal. Integer
imap_utf7_encode(data) Converts 8-bit data to modified UTF-7 text. String
lcg_value() Returns a pseudo random number between 0 and 1. Double
imap_utf8(text) Converts text to UTF8. String
log(arg) Returns the natural logarithm of an argument. Float
log10(arg) Returns the base-10 logarithm of an argument. Float
max(arg1, arg2, ...) Finds the highest value of the specified arguments. Mixed
MAIL FUNCTIONS
min(arg1, arg2, ...) Finds the lowest value of the specified arguments. Mixed
mt_getrandmax() Returns the largest possible random value that can be Integer
Function Description Returns returned by mt_rand().
ezmlm_hash(addr) Calculates the hash value required by EZMLM mailing lists. Integer
mt_rand([min [, max]]) Returns a Mersenne Twister random value. Integer
mail(to, subject, message Sends mail. Boolean
[, additional_headers mt_srand(seed) Seeds the Mersenne Twister random number generator. Void
[, additional_parameters]]) number_format(number, Formats a number to a specified number of decimal places String
decimals, dec_point, using the provided decimal point and thousands separator.
thousands_sep)
octdec(octal_string) Converts an octal value to decimal. Integer
MATHEMATICAL FUNCTIONS pi() Returns the value of pi. Double
pow(base, exp) Returns a base to the power of an exponent. Float
Function Description Returns
rad2deg(number) Converts a radian number to degrees. Double
abs(number) Returns the absolute value of a number. Mixed
rand([min [, max]]) Generates a random value. Integer
acos(arg) Returns the arc cosine of an argument in radians. Float
round(number [, precision]) Rounds a float number to the nearest integer. Double
asin(arg) Returns the arc sine of an argument in radians. Float
sin(arg) Returns the sine of an argument in radians. Float
atan(arg) Returns the arc tangent of an argument in radians. Float
sqrt(arg) Returns the square root of an argument. Float
atan2(y, x) Returns the arc tangent of two variables. Float
srand(seed) Seeds the random number generator. Void
base_convert(number, Converts a number between bases. String
frombase, tobase) tan(arg) Returns the tangent of an argument in radians. Float

250 251
PHP PHP FUNCTIONS QUICK REFERENCE 12
NETWORK FUNCTIONS (CONTINUED)
PHP FUNCTIONS QUICK REFERENCE Function Description Returns
fsockopen([udp://]hostname, Opens a socket connection. Integer
MISCELLANEOUS FUNCTIONS port [, errno [, errstr
[, timeout]]])

Function Description Returns gethostbyaddr(ip_address) Finds the host name corresponding to an IP address. String
connection_aborted() Indicates whether a client has disconnected. Integer gethostbyname(hostname) Finds the IP address corresponding to a host name. String
connection_status() Returns the status of a connection. Integer gethostbynamel(hostname) Returns a list of IP addresses corresponding to a host name. Array
connection_timeout() Indicates whether a script has timed out. Integer getmxrr(hostname, mxhosts Finds the MX records corresponding to a host name. Integer
[, weight])
constant(name) Returns the value of a constant. Mixed
getprotobyname(name) Finds the protocol number associated with a protocol name. Integer
define(name, value Defines a named constant. Integer
[, case_insensitive]) getprotobynumber(number) Finds the protocol name associated with a protocol number. String
defined(name) Checks whether a named constant exists. Integer getservbyname(service, Finds the port number associated with a service and protocol. Integer
protocol)
die(message) Outputs a message and terminates the current script. Void
getservbyport(port, protocol) Finds the Internet service associated with a port and protocol. String
eval(string) Evaluates a string as PHP code. Mixed
ip2long(ip_address) Converts an IP address into the name of a computer. Integer
exit() Terminates the current script. Void
long2ip(proper_address) Converts the name of a computer into an IP address. String
get_browser([user_agent]) Determines the capabilities of a user's browser. Object
openlog(ident, option, Opens a connection to the system logger. Integer
highlight_file(filename) Prints a syntax highlighted version of a file. Boolean facility)
highlight_string(string) Prints a syntax highlighted version of a string. Boolean pfsockopen(hostname, port Opens a persistent socket connection. Integer
[, errno [, errstr
ignore_user_abort([setting]) Sets whether a client disconnecting will terminate the Integer [, timeout]]])
execution of a script.
socket_get_status Returns information about a socket resource. Array
iptcparse(iptcblock) Parses an IPTC block into its single tags. Array (socket_get_status)
leak(bytes) Leaks a specified amount of memory. Void socket_set_blocking Sets the blocking mode for a socket. Integer
(socket_descriptor, mode)
pack(format [, args...]) Packs arguments into a binary string using a specified format. String
socket_set_timeout Sets the timeout period on a socket. Boolean
show_source(filename) Prints a syntax highlighted version of a file. Boolean (socket_descriptor, seconds,
sleep(seconds) Delays execution of a script for a specified number of seconds. Void microseconds)
uniqid(prefix [, lcg]) Generates a prefixed unique ID based on the current time Integer syslog(priority, message) Writes a message to the system log. Integer
in microseconds.
unpack(format, data) Unpacks data from a binary string using a specified format. Array OUTPUT CONTROL FUNCTIONS
usleep(microseconds) Delays execution of a script for a specified number of Void
microseconds.
Function Description Returns
NETWORK FUNCTIONS flush() Flushes an output buffer. Void
ob_end_clean() Erases the contents of an output buffer and turns off output Void
buffering.
Function Description Returns
ob_end_flush() Sends the contents of an output buffer and turns off output Void
checkdnsrr(host [, type]) Searches the DNS for records of a specified type Integer buffering.
corresponding to a host.
ob_get_contents() Returns the contents of an output buffer. String
closelog() Closes a connection to the system logger. Integer
ob_get_length() Returns the length of the contents of an output buffer. String
debugger_off() Disables the internal PHP debugger. Integer
ob_gzhandler(buffer) Facilitates sending gz-encoded data to Web browsers. String
debugger_on(address) Enables the internal PHP debugger and connects it to Integer
an address. ob_implicit_flush([flag]) Turns implicit flushing on or off. Void
define_syslog_variables() Initializes all syslog related constants. Void ob_start([output_callback]) Turns on output buffering. Void

252 253
PHP PHP FUNCTIONS QUICK REFERENCE 12
PHP OPTIONS AND INFORMATION (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE Function Description Returns


set_magic_quotes_runtime Sets the current configuration setting of Long
(new_setting) magic_quotes_runtime.
PHP OPTIONS AND INFORMATION
set_time_limit(seconds) Sets the number of seconds a script can take to execute. Void
zend_logo_guid() Returns the Zend GUID. String
Function Description Returns
assert(assertion) Checks if an assertion is false. Integer zend_version() Returns the version of the current Zend engine. String
assert_options(what [, value]) Gets or sets assert control options. Mixed
dl(library) Loads a PHP extension library at runtime. Integer POSIX FUNCTIONS
extension_loaded(name) Indicates whether an extension is loaded. Boolean
Function Description Returns
get_cfg_var(varname) Returns the value of a PHP configuration option. String
posix_ctermid() Returns the path name of the controlling terminal. String
get_current_user() Returns the name of the owner of the current PHP script. String
posix_getcwd() Returns the pathname of the current directory. String
get_extension_funcs Returns the names of the functions of a module. Array
(module_name) posix_getegid() Returns the effective group ID of the current process. Integer
get_included_files() Returns the names of all the files that have been loaded Array posix_geteuid() Returns the effective user ID of the current process. Integer
into a script using include_once().
posix_getgid() Returns the real group ID of the current process. Integer
get_loaded_extensions() Returns the names of all compiled and loaded modules. Array
posix_getgrgid(gid) Returns information about a group by group ID. Array
get_magic_quotes_gpc() Returns the current setting for magic_quotes_gpc. Long
posix_getgrnam(name) Returns information about a group by name. Array
get_magic_quotes_runtime() Returns the current setting for magic_quotes_runtime. Long
posix_getgroups() Returns the group set of the current process. Array
get_required_files() Returns the names of all the files that have been loaded Array
into a script using require_once(). posix_getlogin() Returns the login name of the user owning the current process. String
getenv(varname) Returns the value of an environment variable. String posix_getpgid(pid) Returns the process group identifier for a process. Integer
getlastmod() Returns the time the current page was last modified. Integer posix_getpgrp() Returns the current process group identifier. Integer
getmyinode() Returns the inode of the current script. Integer posix_getpid() Returns the process identifier of the current process. Integer
getmypid() Returns the current PHP process ID. Integer posix_getppid() Returns the parent process identifier of the current process. Integer
getmyuid() Returns the user ID for the current script's owner. Integer posix_getpwnam(username) Returns information about a user by username. Array
getrusage([who]) Returns the current resource usages. Array posix_getpwuid(uid) Returns information about a user by user ID. Array
ini_alter(varname, newvalue) Changes the value of a configuration option. String posix_getrlimit() Returns information about system resource limits. Array
ini_get(varname) Returns the value of a configuration option. String posix_getsid(pid) Returns the sid of a process. Integer
ini_restore(varname) Restores the value of a configuration option. String posix_getuid() Returns the real user ID of the current process. Integer
ini_set(varname, newvalue) Sets the value of a configuration option. String posix_isatty(fd) Indicates whether a file descriptor is an interactive terminal. Boolean
php_logo_guid() Returns the logo GUID. String posix_kill(pid, sig) Sends a signal to a process. Boolean
php_sapi_name() Returns the type of interface between a Web server and PHP. String posix_mkfifo(pathname, mode) Creates a fifo special file. Boolean
php_uname() Returns information about the operating system PHP is String posix_setgid(gid) Sets the effective group ID of the current process. Boolean
built on. posix_setpgid(pid, pgid) Lets a process join a process group. Integer
phpcredits(flag) Prints the credits for PHP. Void posix_setsid() Makes the current process a session leader. Integer
phpinfo([what]) Outputs information about the current state and configuration Integer posix_setuid(uid) Sets the effective user ID of the current process. Boolean
of PHP.
posix_times() Returns process times. Array
phpversion() Returns the current version of PHP. String
posix_ttyname(fd) Returns the terminal device name. String
putenv(setting) Sets the value of an environment variable by adding a setting Void
to the server environment. posix_uname() Returns system information. Array

254 255
PHP PHP FUNCTIONS QUICK REFERENCE 12
PHP FUNCTIONS QUICK REFERENCE PSPELL FUNCTIONS (CONTINUED)

Function Description Returns


PROGRAM EXECUTION FUNCTIONS
pspell_save_wordlist Saves a personal wordlist to a file. Integer
(dictionary_link)
Function Description Returns
pspell_store_replacement Stores a replacement pair for a word. Integer
escapeshellarg(arg) Escapes a string to be used as a shell argument. String (dictionary_link, misspelled,
correct)
escapeshellcmd(command) Escapes shell metacharacters in a command. String
pspell_suggest Suggests spellings for a word. Array
exec(command [, array Executes a command and returns the last line from the result. String (dictionary_link, word)
[, return_var]])
passthru(command Executes a command and displays the raw output. Void
[, return_var])
REGULAR EXPRESSION FUNCTIONS
system(command [, return_var]) Executes a command and displays any output. String
Perl-Compatible

PSPELL FUNCTIONS Function Description Returns


preg_grep(pattern, input) Returns the entries from an input array that match Array
Function Description Returns a regular expression.
pspell_add_to_personal Adds a word to a personal wordlist. Integer preg_match(pattern, subject Searches for a match to a regular expression. Integer
(dictionary_link, word) [, matches])

pspell_add_to_session Adds a word to a wordlist in the current session. Integer preg_match_all(pattern, Searches for all matches to a regular expression, putting Integer
(dictionary_link, word) subject, matches [, order]) the results in matches.
pspell_check(dictionary_link, Checks the spelling of a word. Boolean preg_quote(string Puts a backslash in front of every regular expression character String
word) [, delimiter]) in a string.
pspell_clear_session Clears the current session and makes the current wordlist Integer preg_replace(pattern, Replaces matches to a regular expression. Mixed
(dictionary_link) blank. replacement, subject
[, limit])
pspell_config_create(language Creates a config used to open a dictionary. Integer
[, spelling [, jargon preg_replace_callback(pattern, Replaces matches to a regular expression using a callback. Mixed
[, encoding]]]) callback, subject [, limit])

pspell_config_ignore Ignores words shorter than a specified length. Integer preg_split(pattern, subject Splits a string using a regular expression. Array
(dictionary_link, n) [, limit [, flags]])

pspell_config_mode Changes the mode number of suggestions returned. Integer


(dictionary_link, mode)
POSIX Extended
pspell_config_personal Sets a file that contains a personal wordlist. Integer
(dictionary_link, file) Function Description Returns
pspell_config_repl Sets a file that contains replacement pairs. Integer ereg(pattern, string [, regs]) Searches for matches to a regular expression. Integer
(dictionary_link, file)
ereg_replace(pattern, Replaces matches to a regular expression. String
pspell_config_runtogether Considers run-together words as valid compounds. Integer replacement, string)
(dictionary_link, flag)
eregi(pattern, string Performs a case-insensitive search for matches to a regular Integer
pspell_config_save_repl Determines whether to save a replacement pairs list with Integer [, regs]) expression.
(dictionary_link, flag) a wordlist.
eregi_replace(pattern, Performs a case-insensitive search and replaces matches String
pspell_new(language Loads a new dictionary. Integer replacement, string) to a regular expression.
[, spelling [, jargon
[, encoding [, mode]]]]) split(pattern, string Splits a string into an array using a regular expression. Array
[, limit])
pspell_new_config(config) Loads a new dictionary with settings based on a specified config. Integer
spliti(pattern, string Splits a string into an array using a regular expression and Array
pspell_new_personal(personal, Loads a new dictionary with a personal wordlist. Integer [, limit]) is case-insensitive.
language [, spelling [, jargon
[, encoding [, mode]]]]) sql_regcase(string) Returns a regular expression for a case-insensitive match. String

256 257
PHP PHP FUNCTIONS QUICK REFERENCE 12
STRING FUNCTIONS (CONTINUED)

PHP FUNCTIONS QUICK REFERENCE Function Description Returns


convert_cyr_string Converts a string from one Cyrillic character set to another. String
(string, from, to)
SESSION HANDLING FUNCTIONS count_chars(string [, mode]) Returns information about characters used in a string. Mixed
crc32(string) Calculates the crc32 polynomial of 32-bit lengths of a string. Integer
Function Description Returns
crypt(string [, salt]) Encrypts a string using the DES encryption method. String
session_cache_limiter Returns or sets the current cache limiter. String
([cache_limiter]) explode(separator, string Splits a string into smaller strings. Array
[, limit])
session_decode(string) Decodes session data. Boolean
get_html_translation_ Returns the translation table used by htmlspecialchars() String
session_destroy() Destroys all registered session data. Boolean table(table [, quote_style]) and htmlentities().
session_encode() Encodes the data for the current session as a string. String get_meta_tags(filename Returns all the <meta> tag content attributes from a file. Array
session_get_cookie_params() Returns the current session cookie information. Array [, use_include_path])

session_id([id]) Returns or sets the current session ID. String hebrev(hebrew_text Converts logical Hebrew text to visual text. String
[, max_chars_per_line])
session_is_registered(name) Indicates whether a session variable is registered with the Boolean hebrevc(hebrew_text Converts logical Hebrew text to visual text with newline String
current session. [, max_chars_per_line]) conversion.
session_module_name([module]) Returns or sets the name of the current session module. String htmlentities(string Converts all applicable characters in a string to HTML entities. String
session_name([name]) Returns or sets the name of the current session. String [, quote_style])
session_register(name [, ...]) Registers one or more variables with the current session. Boolean htmlspecialchars(string Converts any special characters in a string to HTML entities. String
[, quote_style])
session_save_path([path]) Returns or sets the path where data for the current session String
is saved. implode(glue, pieces) Joins array elements into a single string. String
session_set_cookie_params Sets the session cookie parameters. Void join(glue, pieces) Joins array elements into a single string. String
(lifetime [, path [, domain]]) levenshtein(string1, string2) Calculates the Levenshtein distance between two strings. Integer
session_set_save_handler Sets user-level session storage functions. Void localeconv() Returns numeric formatting information based on the Array
(open, close, read, write, current locale.
destroy, gc)
session_start() Initializes a session. Boolean ltrim(string) Removes whitespace from the beginning of a string. String
session_unregister(name) Unregisters a session variable. Boolean md5(string) Calculates the MD5 hash of a string. String
session_unset() Frees all registered session variables. Void metaphone(string) Calculates the metaphone key of a string. String
nl2br(string) Inserts <br> before all line breaks in a string. String
ord(string) Returns the ASCII value of the first character of a string. Integer
parse_str(string [, arr]) Parses a string into variables as if it were a query string. Void
STRING FUNCTIONS
print(string) Outputs a string. Boolean
Function Description Returns printf(format [, args...]) Outputs a formatted string. Integer
addcslashes(string, charlist) Adds C style backslashes before characters in a string. String quoted_printable_decode Converts a quoted-printable string to an 8-bit string. String
(string)
addslashes(string) Adds backslashes before characters in a string that need String
to be quoted in database queries. quotemeta(string) Escapes metacharacters in a string. String
bin2hex(string) Converts binary data into hexadecimal representation. String rtrim(string) Removes trailing whitespace from a string. String
chop(string) Removes trailing whitespace from a string. String setlocale(category, locale) Sets locale information for functions of a category. String
chr(ascii) Returns the character for an ASCII value. String similar_text(string1, string2 Calculates the similarity between two strings. Integer
[, percent])
chunk_split(string Splits a string into smaller pieces. String
[, chunklen [, end]]) soundex(string) Calculates the soundex key of a string. String

258 259
PHP PHP FUNCTIONS QUICK REFERENCE 12

PHP FUNCTIONS QUICK REFERENCE STRING FUNCTIONS (CONTINUED)

Function Description Returns


STRING FUNCTIONS (CONTINUED)
strrpos(string, character) Finds the numeric position of the last occurrence of a Integer
specified character in a string.
Function Description Returns strspn(string1, string2) Finds the number of characters at the beginning of one string Integer
sprintf(format [, args...]) Formats a string. String that match another string.
sscanf(string, format Parses input from a string using a specified format. Mixed strstr(string, character) Returns a string from the first occurrence of a specified String
[, var1...]) character to the end.
str_pad(input, pad_length Pads a string to a specified length with another string. String strtok(string1, string2) Breaks down a string into segments separated by another String
[, pad_string [, pad_type]]) string.
str_repeat(input, multiplier) Repeats a string. String strtolower(string) Converts a string to lowercase. String
str_replace(string, Replaces all occurrences of a string in a subject. String strtoupper(string) Converts a string to uppercase. String
replacement, subject)
strtr(string, from, to) Changes all occurrences of a character to another character. String
strcasecmp(string1, string2) Performs a binary safe case-insensitive string comparison. Integer
substr(string, start Extracts a substring from a string. String
strchr(string, character) Returns a string from the first occurrence of a specified String [, length])
character to the end.
substr_count(string, substr) Returns the number of times a substring occurs in a string. Integer
strcmp(string1, string2) Performs a binary safe case-sensitive string comparison. Integer
substr_replace(string, Replaces text within a specific portion of a string. String
strcoll(string1, string2) Performs a locale-based comparison of two strings. Integer replacement, start [, length])
strcspn(string1, string2) Finds the number of characters at the beginning of one string Integer trim(string) Strips whitespace from the beginning and end of a string. String
that do not match another string.
ucfirst(string) Converts the first character of a string to uppercase. String
strip_tags(string Removes HTML and PHP tags from a string. String
[, allowable_tags]) ucwords(string) Converts the first character of each word in a string to String
uppercase.
stripcslashes(string) Removes C style backslashes from a string. String
wordwrap(string [, width Wraps a string to a specified number of characters using String
stripslashes(string) Removes backslashes from a string. String [, break [, cut]]]) a string break character.
stristr(string, character) Returns a string from the first occurrence of a specified String
character to the end, in a case-insensitive manner.
URL FUNCTIONS
strlen(string) Finds the length of a string. Integer
strnatcasecmp(string1, Performs a case-insensitive string comparison using a Integer Function Description Returns
string2) "natural order."
base64_decode(string) Decodes a MIME base64 encoded string. String
strnatcmp(string1, string2) Performs a case-sensitive string comparison using a Integer
"natural order." base64_encode(string) Encodes a string with MIME base64. String
strncasecmp(string1, string2, Performs a binary safe case-insensitive comparison of a Integer parse_url(url) Parses a URL into its components. Array
length) specified number of characters.
rawurldecode(string) Decodes a URL-encoded string. String
strncmp(string1, string2, Performs a binary safe case-sensitive comparison of a Integer
length) specified number of characters. rawurlencode(string) URL-encodes a string, replacing all alphanumeric characters String
except - _ and . with a % symbol and the hex code for the
strpos(string, character Returns the numeric position of the first occurrence of a Integer character.
[, offset]) specified character in a string.
urldecode(string) Decodes a URL-encoded string. String
strrchr(string, character) Returns a string from the last occurrence of a specified String
character to the end. urlencode(string) URL-encodes a string, replacing all alphanumeric characters String
except - _ and . with a % symbol and the hex code for the
strrev(string) Returns a string in reverse order. String character and replacing all spaces with a + symbol.

260 261
PHP PHP FUNCTIONS QUICK REFERENCE 12

PHP FUNCTIONS QUICK REFERENCE


VARIABLE FUNCTIONS WDDX FUNCTIONS

Function Description Returns Function Description Returns


doubleval(variable) Returns the double value of a variable. Double wddx_add_vars(packet_id, Adds a variable to a WDDX packet. Void
empty(variable) Indicates whether a variable has been set and has a Integer variable [, ...])
non-zero value. wddx_deserialize(packet) Deserializes a WDDX packet. Mixed
get_defined_vars() Returns all defined variables. Array wddx_packet_end(packet_id) Ends a WDDX packet. String
get_resource_type($handle) Finds the type of a resource. String wddx_packet_start([comment]) Starts a new WDDX packet. Integer
gettype(variable) Finds the data type of a variable. String wddx_serialize_value(var Serializes a single value into a WDDX packet. String
intval(variable [, base]) Returns the integer value of a variable using a specified base. Integer [, comment])
is_array(variable) Indicates whether a variable is an array. Boolean wddx_serialize_vars(var_name Serializes multiple variables into a WDDX packet. String
[, ...])
is_bool(variable) Indicates whether a variable is a boolean. Boolean
is_double(variable) Indicates whether a variable is a double. Boolean
is_float(variable) Indicates whether a variable is a floating-point number. Boolean
XML PARSER FUNCTIONS
is_int(variable) Indicates whether a variable is an integer. Boolean
is_integer(variable) Indicates whether a variable is an integer. Boolean Function Description Returns
is_long(variable) Indicates whether a variable is an integer. Boolean utf8_decode(string) Converts a UTF-8 encoded string to ISO-8859-1. String
is_null(variable) Indicates whether a variable is null. Boolean utf8_encode(string) Encodes an ISO-8859-1 string to UTF-8. String
is_numeric(variable) Indicates whether a variable is a number or a numeric string. Boolean xml_error_string(code) Returns the error message associated with an error code. String
is_object(variable) Indicates whether a variable is an object. Boolean xml_get_current_byte_index Returns the current byte index for an XML parser. Integer
is_real(variable) Indicates whether a variable is a real number. Boolean (parser)

is_resource(variable) Indicates whether a variable is a resource. Boolean xml_get_current_column_number Returns the current column number for an XML parser. Integer
(parser)
is_scalar(variable) Indicates whether a variable is a scalar. Boolean
xml_get_current_line_number Returns the current line number for an XML parser. Integer
is_string(variable) Indicates whether a variable is a string. Boolean (parser)
isset(variable) Indicates whether a value has already been assigned to Integer xml_get_error_code(parser) Returns the error code for the last occurring XML parser error. Integer
a variable.
xml_parse(parser, data Parses specified XML data. Integer
print_r(expression) Prints human-readable information about a variable. Void [, is_final])
serialize(value) Generates a storable representation of a value. String xml_parse_into_struct(parser, Parses XML data into two arrays. Integer
data, values, index)
settype(variable, type) Converts a variable to a specified data type. Integer
xml_parser_create([encoding]) Creates an XML parser. Integer
strval(variable) Returns the string value of a variable. String
xml_parser_free(parser) Frees an XML parser. String
unserialize(string) Creates a PHP value from a stored representation. Mixed
xml_parser_get_option(parser, Returns the value of an option for an XML parser. Mixed
unset(variable Destroys a variable. Integer option)
[, variable [, ...]])
xml_parser_set_option(parser, Sets an option for an XML parser to a specified value. Integer
var_dump(expression) Dumps information about an expression. Void option, value)

262 263
PHP PHP FUNCTIONS QUICK REFERENCE 12

PHP FUNCTIONS QUICK REFERENCE


XML PARSER FUNCTIONS (CONTINUED) ZLIB FUNCTIONS (CONTINUED)

Function Description Returns Function Description Returns


xml_set_character_data_handler Sets a character data handler function for an XML parser. Integer gzgetss(zp, length Returns a line of a specified length from a gz-file pointer String
(parser, handler) [, allowable_tags]) and strips any HTML and PHP tags.
xml_set_default_handler Sets a default handler function for an XML parser. Integer gzinflate(data [, length]) Uncompresses data compressed using the DEFLATE data String
(parser, handler) format.
xml_set_element_handler Sets the start and end element handler functions for an Integer gzopen(filename, mode Opens a gz-file pointer. Integer
(parser, startElementHandler, XML parser. [, use_include_path])
endElementHandler)
gzpassthru(zp) Outputs all remaining data on a gz-file pointer. Integer
xml_set_external_entity_ref_ Sets an external entity reference handler function for an Integer
handler(parser, handler) XML parser. gzputs(zp, string [, length]) Writes a string to a gz-file pointer. Integer
xml_set_notation_decl_handler Sets a notation declaration handler function for an XML parser. Integer gzread(zp, length) Reads a specified number of bytes from a gz-file pointer. String
(parser, handler)
gzrewind(zp) Rewinds the position of a gz-file pointer to the beginning Integer
xml_set_object(parser, object) Allows the use of an XML parser inside an object. Void of a file stream.
xml_set_processing_ Sets a processing instruction handler function for an Integer gzseek(zp, offset) Seeks on a gz-file pointer. Integer
instruction_handler(parser, XML parser.
handler) gztell(zp) Determines the position of a gz-file pointer. Integer
xml_set_unparsed_entity_decl_ Sets an unparsed entity declaration handler function for an Integer gzuncompress(data [, length]) Uncompresses gz-compressed data. String
handler(parser, handler) XML parser. gzwrite(zp, string Writes a string to a gz-file pointer. Integer
[, length])
readgzfile(filename Outputs a gz-file. Integer
ZLIB FUNCTIONS [, use_include_path])

Function Description Returns


gzclose(zp) Closes a gz-file pointer. Integer
gzcompress(data [, level]) Returns a gzip-compressed version of data. String
gzdeflate(data [, level]) Returns a compressed version of data using the DEFLATE String
data format.
gzencode(data [, level]) Creates a gzip-compressed string. String
gzeof(zp) Tests for end-of-file on a gz-file pointer. Integer
gzfile(filename Reads a gz-file into an array. Array
[, use_include_path])
gzgetc(zp) Returns a character from a gz-file pointer. String
gzgets(zp, length) Returns a line of a specified length from a gz-file pointer. String

264 265

You might also like