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