PHP A Visual Blueprint
PHP A Visual Blueprint
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
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.
⁄ 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
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
⁄ 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.
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
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
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
⁄ 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
⁄ 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
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,
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
⁄ 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.
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
⁄ 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
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
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.
⁄ 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
⁄ 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.
www.company.com
jsmith
⁄ 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
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
⁄ 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:
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 <[email protected]>
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
⁄ 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
⁄ 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.
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
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
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
⁄ 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)
{
⁄ 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--)
}
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>";
}
⁄ 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.
⁄ 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
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
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
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:
⁄ 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
⁄ 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
⁄ 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";
⁄ 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?");
⁄ 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);
⁄ 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 }
⁄ 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
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,
⁄ 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
⁄ 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
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>";
⁄ 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
⁄ 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 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. }
⁄ 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
⁄ 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  ";
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 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
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 }
⁄ 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
⁄ 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.
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";
⁄ 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,
⁄ 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);
⁄ 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
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 = "[email protected]"; @maran.com
counting the number of characters from the end of same length as the substring. $domain = strstr($email, "@");
print $domain;
⁄ 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.
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;
}
⁄ 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
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;
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.
⁄ 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.
⁄ 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
⁄ 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.
⁄ 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
⁄ 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
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®ion=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.";
}
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
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
⁄ 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
⁄ 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";
}
⁄ 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
⁄ 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.
⁄ 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
⁄ 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
⁄ 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
⁄ 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
⁄ 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
⁄ 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
⁄ 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
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. }
⁄ 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
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
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.
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
⁄ 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
⁄ 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
⁄ 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.
⁄ 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)
⁄ 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
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
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.
⁄ 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:
⁄ 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");
⁄ 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. }
⁄ 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
⁄ Type the code that ¤ To have the PHP page › Type a comma Á Type the code that ‡ Type the code that ° Type the code you want · In a Web browser, — Click the submit button
connects the PHP page accept and process an SQL followed by the name of determines if the result determines if the result of to process when the result display the form you to pass the SQL statement
to the MySQL server statement passed by a form, the variable that stores of the mysql_query the mysql_query function of the mysql_query created to issue SQL to the PHP page.
and selects the database type mysql_query(). the link identifier. function is of the boolean is of the boolean data type function is of a data type statements to the database.
you want to work with. data type and is false. Then and is true. Then type the other than boolean. ■ The PHP page that
‹ Between the parentheses, ˇ Type the code that type the code you want to code you want to process ‚ Enter an SQL statement processes the SQL statement
type $ followed by the value assigns the result of the process in this situation. in this situation. into the form. will appear and the database
assigned to the name attribute mysql_query function will be modified.
of the <textarea> tag in to a variable.
206 the form. 207
PHP TROUBLESHOOTING PHP SCRIPTS 11
When specifying the information you want to To view the error information saved to the
LOG ERRORS TO A FILE display in the error log, you may want to append
a newline character (\n) to the end of the error
operating system's log with Windows NT,
2000 or XP, open the Control Panel and
message you specify in the error_log function. double-click Administrative Tools. Then
W
hen an error is generated in a PHP script, you The first argument specifies the message you want to The newline character will help ensure that each double-click Event Viewer and click
may want to save information about the error display in the error log when an error occurs. The second entry in the error log is placed on its own line, Application Log. For more information
in a file for later review. Saving error information argument indicates the message type, which determines making the error log easier to read when viewed about logging errors and the location
to a file is useful for keeping track of non-critical errors how the message will be stored. To specify that you want in a text editor. of system logs, consult your operating
that do not require immediate attention, such as an error a message to be stored in an error log, you use a message system's documentation.
generated when a user forgets to enter a user name. type of 0.
If you are using Windows NT, 2000 or XP, you
Before you can log errors to a file, you must make changes When a PHP script encounters an error, PHP will use a can add error information to the operating
to the php.ini configuration file. To specify that you want to built-in error-handling function to save the date and time system's log instead of logging errors to a file.
log errors, change the value of the log_errors directive of the error and the message you specified to the error In the php.ini configuration file, remove the
in the php.ini file to "On." To specify a file to which you log. You can create a custom error-handling function to semicolon preceding the error_log directive
want to log errors, you enter the location and name of the keep track of additional details about errors. For more that specifies the syslog value. If you previously
file as the value for the error_log directive. If the file information about creating a custom error-handling specified a file to which error information was
you specify does not exist, PHP will create the file when function, see page 214. to be saved, place a semicolon in front of that
the first error occurs. For more information about the error_log line to have the php.ini file ignore
php.ini file, see page 26. The error log is a simple text file that can be viewed the command.
at any time using a text editor or word processor.
To pass error information from a PHP page to an error log, log_errors = On
;error_log = c:\php\error.log
you include the error_log function in the PHP code for error_log = syslog
the page. The error_log function takes two arguments.
LOG ERRORS TO A FILE
CHANGE THE PHP.INI SETTINGS ‹ To activate the SET UP THE PHP PAGE ‹ To specify that the ˇ Display the PHP page ■ When an error is DISPLAY THE ERROR LOG ■ The error log displays
⁄ In the php.ini file, select error_log directive, ⁄ In the PHP page for message should be stored in a Web browser. generated, the message ⁄ Locate and open the the date and time an
the value of the log_errors delete the semicolon which you want to save error in an error log, type a you specified will be error log in a text editor. error was generated and
directive and type On. preceding the directive. information, type error_log(). comma followed by 0. written to the error log. the error message you
specified.
¤ To specify a file in which to › Save the file. ¤ Between the parentheses, › Type the code that
log errors, select the value of type the message you want uses the error_log
the error_log directive and to display in the error log, function.
type the location and name of enclosed in quotation marks.
the file you want to use.
208 209
PHP TROUBLESHOOTING PHP SCRIPTS 11
SEND AN ERROR MESSAGE Before you can use the error_log function
to send an error message to an e-mail address,
you must configure PHP to work with the
On Unix-based systems, such as computers
running the Linux operating system,
Sendmail is the universally accepted program
TO AN E-MAIL ADDRESS mail system available to the Web server. On
Windows computers, you must ensure that the
used to process e-mail messages. You must
use the php.ini file to specify the location of
php.ini file specifies the name of the mail server the Sendmail program on the Web server.
T
he error_log function allows you to send a message To send an error message to an e-mail address, you use used to send mail, often referred to as the SMTP The e-mail account on the Web server used
to an e-mail address when an error occurs in a PHP a message type of 1. You must also specify the e-mail server. You must also specify an e-mail address to send messages will be used when the
page. This is useful when a critical error occurs that address to which you want to send the message. that is authorized to send mail using the mail error_log function is processed. Locate
requires the immediate attention of support personnel, such server. In the php.ini file, locate the [mail the [mail function] section heading in
as an error generated by a database that is not responding Although not required, you can also specify new header
function] section heading and then change the php.ini file and then change the value of
or a failed attempt to log on as the administrator. information for the e-mail message. E-mail message headers
the value of the SMTP directive to reflect the the sendmail_path directive to reflect the
contain information such as the name of the person who
With the advent of telecommunication devices that can name of the outgoing mail server. Then change location of the Sendmail program.
sent the message, the subject of the message and the date
receive e-mail messages, such as pagers and mobile the value of the sendmail_from directive to
the message was sent. You can alter an existing header Example:
telephones, sending error messages to an e-mail address reflect a valid e-mail address.
or you can add a new header to the e-mail message. For [mail function]
is an efficient way for Webmasters to stay informed about example, you may want to change the 'From:' header to Example:
the status of their Web servers. reflect the name of the computer that generated the error. [mail function] sendmail_path = usr/bin/sendmail
If you specify a header that does not exist, the new header SMTP = mail.c1.us
To use the error_log function to send an error message will be created and sent with the e-mail message. Creating sendmail_from = [email protected]
to an e-mail address, you must specify the error message a new header is useful for support departments that
you want to send. You must also specify the message type, organize error messages according to the value of a
which determines where the error message will be sent. customized header.
⁄ To send a message ¤ Between the parentheses, ‹ To specify that the › To specify the e-mail ˇ To specify new header Á Type the code that ‡ Display the PHP page ■ When an error occurs,
to an e-mail address type the message you want to message should be sent address you want to send information for the e-mail uses the error_log in a Web browser. the message you created
when an error occurs, send, enclosed in quotation to an e-mail address, the message to, type a message, type a comma function. is sent to the specified
type error_log(). marks. type a comma followed comma followed by the followed by the header e-mail address.
by 1. e-mail address enclosed information enclosed in
in quotation marks. quotation marks.
210 211
PHP TROUBLESHOOTING PHP SCRIPTS 11
Besides E_NOTICE, E_WARNING and E_ERROR, If you do not want to report any
two other commonly used error reporting errors in a PHP script, you can turn
level constants are E_CORE_ERROR and off error reporting. To turn off error
CHANGE THE ERROR REPORTING LEVEL E_CORE_WARNING. These two constants are
similar to E_ERROR and E_WARNING, except
reporting, set the argument for the
error_reporting function to
that E_CORE_ERROR and E_CORE_WARNING zero (0).
W
hen PHP encounters an error in a section of constants include E_NOTICE, E_WARNING and E_ERROR.
detect errors generated by the PHP program
code, the program generates an error message You can use the E_NOTICE constant as the argument for Example:
itself and not by a script. Other error reporting
that is displayed in the user's Web browser. the error_reporting function when you want PHP to error_reporting(0);
levels include E_PARSE, E_COMPILE_ERROR,
You can change the error reporting level of PHP to specify detect inconsistencies that could be errors, but you do not
E_COMPILE_WARNING, E_USER_ERROR,
which errors PHP should generate an error message for. want PHP to print error messages for the inconsistencies.
E_USER_WARNING and E_USER_NOTICE.
You can use the E_WARNING constant to detect more
PHP can detect several different types of errors. Simple serious types of errors that may require attention and print
errors, such as dividing a number by zero, are the most error messages for the errors. The E_ERROR constant When using the error_reporting function to
common type of error. PHP can also identify and report reports only fatal errors in a script. If a fatal error occurs, change the error reporting level, you can assign
more serious errors, such as calling a function without the script is terminated after the error_reporting the function to a variable. You can then use the
passing the correct number or type of arguments. Some function is called. value of the variable later in your script to return
errors, called fatal errors, force PHP to terminate the to the original error reporting level.
processing of a script. Fatal errors are caused by critical You can specify more than one constant in the
problems, such as memory allocation problems. error_reporting function. This allows you to specify Type this:
more than one error reporting level. To use more than $oldLevel = error_reporting(E_NOTICE | E_ERROR);
The error_reporting function allows you to specify one constant, use the OR operator (|) to separate each
which errors PHP should report. The error reporting level constant in the error_reporting function. To return to the original level, type:
is specified using predefined constants. Commonly used error_reporting($oldLevel);
⁄ Type the code that ¤ To change the error ‹ Between the parentheses, › To specify another ˇ Type the constant that ■ You can repeat steps 4 ‡ Display the PHP page in ■ In this example,
will generate an error. reporting level, type type the constant that error reporting level, represents another error and 5 for each error a Web browser. an error message is
error_reporting(). represents the error reporting type |. reporting level you want reporting level you want displayed only for
level you want to use. to use. to specify. ■ When an error occurs, PHP the first error.
uses the specified reporting
Á Type the code that will level to determine if an error
generate another error. message should be displayed.
212 213
PHP TROUBLESHOOTING PHP SCRIPTS 11
⁄ To create an error-handling ¤ Between the parentheses, ‹ Type the code that uses › To specify that you ˇ Between the parentheses, Á Display the PHP page ■ When an error occurs,
function, type function type a variable name for each the variables that store the want to use the custom type the name of the in a Web browser. the Web browser displays
followed by the name of value PHP will pass to the error information. Enclose error-handling function error-handling function, the result of using a
the function. Then type (). function when an error the code in braces. you created, type enclosed in quotation marks. custom error-handling
occurs. Separate each set_error_handler(). function.
variable name with a comma.
214 215
PHP TROUBLESHOOTING PHP SCRIPTS 11
You can use the show_source function to display a
EMBED DEBUGGING MESSAGES syntax-highlighted version of the source code for a PHP
page in the same Web browser window that displays the
PHP page. Viewing the output and source code on the same
mbedding debugging information into the HTML code You include debugging information within HTML code by
⁄ To create a function that ‹ Type the braces {} ˇ Between the opening and Á Type the code ‡ Type the code that ° Repeat step 7 at each · Display the PHP page ■ The HTML source code
generates an HTML comment, that will hold the body closing delimiters, type the that will display the calls the function and location in the PHP code in a Web browser. displays the debugging
type function followed by a name of the function. message you want the function debugging message in passes the information where you want to generate messages generated
for the function. Then type (). to embed in the HTML code. the HTML source code. you want to display in a debugging message. ‚ Display the source when the PHP page was
› In the body of the The message can include text, the debugging message code of the PHP page. processed.
¤ Between the parentheses, type function, type <!– – HTML or PHP code, as well to the function.
the name of a variable that will and – –>. as the variable that stores the
store the debugging message. information passed to the
216 function. 217
PHP TROUBLESHOOTING PHP SCRIPTS 11
USING TELNET TO
CONNECT TO A WEB SERVER Using troubleshooting features may increase the processing time of a PHP
script. As a result, the processing time may exceed the maximum execution
time allowed by PHP. You can change the maximum execution time allowed
nce a PHP page is stored on a Web server, you may commands you can issue to a Web server are part of the
RETRIEVE A PHP PAGE ¤ Type the URL or IP › Type GET /. ■ The HTML code for the VIEW HTTP HEADERS ¤ Type the URL or IP › Type HEAD /. ■ The HTTP header
⁄ At the command address of the Web server PHP page is displayed in ⁄ At the command address of the Web server information for the PHP
you want to connect to. ˇ Type the name of the the telnet window. you want to connect to. ˇ Type the name of the page is displayed.
prompt, type telnet. PHP page you want to prompt, type telnet. PHP page for which you
Then type the port number Then type the port number
used by the Web server. retrieve and then press Note: The HTML code may be used by the Web server. want to view the HTTP Note: The information may be
Enter. formatted differently, depending header information. formatted differently, depending
‹ Press Enter to start the on the Web server and telnet ‹ Press Enter to start the on the Web server and telnet
telnet program and connect telnet program and connect Á Type http/1.0 and then
program you are using. press Enter twice. program you are using.
to the Web server. to the Web server.
218 219
PHP PHP FUNCTIONS QUICK REFERENCE 12
ARRAY FUNCTIONS (CONTINUED)
220 221
PHP PHP FUNCTIONS QUICK REFERENCE 12
CLASS/OBJECT FUNCTIONS
CALENDAR FUNCTIONS
CLIENT URL LIBRARY (CURL) FUNCTIONS
Function Description Returns
easter_date([year]) Returns a UNIX timestamp for midnight on Easter Integer Function Description Returns
in a specified year. curl_close(handle) Closes a CURL session. Void
easter_days([year]) Returns the number of days after March 21 that Easter Integer curl_exec(handle) Executes a CURL session. Boolean
falls in a specified year.
curl_init([url]) Initializes a CURL session. Integer
frenchtojd(french) Converts a French Republican Calendar date to Integer
Julian Day Count. curl_setopt(handle, option, Sets an option for a CURL session. Boolean
value)
gregoriantojd(gregorian) Converts a Gregorian Calendar date to Julian Day Count. Integer
curl_version() Returns the current CURL version. String
jddayofweek(julianday, mode) Returns the day of the week. Mixed
jdmonthname(julianday, mode) Returns the month of the year. String
DATABASE FUNCTIONS
jdtofrench(julianday) Converts a Julian Day Count to a French Republican String
Calendar date.
jdtogregorian(julianday) Converts a Julian Day Count to a Gregorian Calendar date. String Database Abstraction Layer Functions
jdtojewish(julianday) Converts a Julian Day Count to a Jewish Calendar date. String Function Description Returns
jdtojulian(julianday) Converts a Julian Day Count to a Julian Calendar date. String dba_close(handle) Closes a database. Void
jdtounix(julianday) Converts a Julian Day Count to a UNIX timestamp. Integer dba_delete(key, handle) Deletes an entry in a database. String
jewishtojd(jewish) Converts a Jewish Calendar date to Julian Day Count. Integer dba_exists(key, handle) Checks if a key exists in a database. Boolean
juliantojd(julian) Converts a Julian Calendar date to Julian Day Count. Integer dba_fetch(key, handle) Returns the requested data. String
unixtojd(timestamp) Converts a UNIX timestamp to Julian Day Count. Integer dba_firstkey(handle) Returns the first key in a database. String
222 223
PHP PHP FUNCTIONS QUICK REFERENCE 12
224 225
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)
InterBase Functions
226 227
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)
228 229
PHP PHP FUNCTIONS QUICK REFERENCE 12
PHP FUNCTIONS QUICK REFERENCE DATABASE FUNCTIONS (CONTINUED)
mysql_affected_rows(link_id) Returns the number of rows affected by the last query. Integer mysql_free_result(result_id) Frees the memory used by a result set. Integer
mysql_change_user(user, Changes the logged in user of the connection. Integer mysql_insert_id([link_id]) Returns the ID generated from the last INSERT operation. Integer
password [, database mysql_list_dbs([link_id]) Lists the databases on a MySQL server. Integer
[, link_id]])
mysql_list_fields(database, Lists the fields in a table. Integer
mysql_close([link_id]) Closes the connection to a MySQL database. Integer table [, link_id])
mysql_connect([hostname Opens a connection to a MySQL database. Integer mysql_list_tables(database) Lists the tables in a MySQL database. Integer
[:port] [:/path/to/socket]
[,username [,password]]]) mysql_num_fields(result_id) Returns the number of fields in a result set. Integer
mysql_create_db(database Creates a MySQL database. Integer mysql_num_rows(result_id) Returns the number of rows in a result set. Integer
[, link_id])
mysql_pconnect([hostname Opens a persistent connection to a MySQL database. Integer
mysql_data_seek(result_id, Moves to a specified row in a result set. Integer [:port] [:/path/to/socket]
row_number) [, username [, password]]])
mysql_db_name(result_id, row Returns result data. Integer mysql_query(query [, link_id]) Executes a query. Integer
[, field])
mysql_result(result_id, row Returns the contents of a cell in a result set. Mixed
mysql_db_query(database, Executes a query. Integer [, field])
query [, link_id])
mysql_select_db(database Makes a MySQL database the current database. Integer
mysql_drop_db(database_name Deletes a MySQL database. Integer [, link_id])
[, link_id])
mysql_tablename(result_id, Returns the name of the table for a field. String
mysql_errno([link_id]) Returns the error number from the last MySQL operation. Integer index)
230 231
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)
232 233
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)
234 235
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATABASE FUNCTIONS (CONTINUED)
odbc_columns(connection_id Lists all column names in a specified range. Integer odbc_prepare(connection_id, Prepares an SQL statement for execution. Integer
[, qualifier [, owner query)
[, table_name odbc_primarykeys Gets the column names that make up the primary key Integer
[, column_name]]]]) (connection_id, qualifier, for a table.
odbc_commit(connection_id) Commits the ODBC transactions on a connection. Integer owner, table)
236 237
PHP PHP FUNCTIONS QUICK REFERENCE 12
DATE AND TIME FUNCTIONS (CONTINUED)
Function Description Returns domxml_dumpmem(doc) Creates an XML document from the DOM representation. String
checkdate(month, day, year) Validates a date. Integer domxml_get_attribute(node, Returns an attribute of a node. Object
name)
date(format [, timestamp]) Formats a local time/date. String
domxml_new_child(name, Adds a new child to a node. Resource
getdate([timestamp]) Returns date/time information. Array content)
gettimeofday() Returns the current time. Array domxml_new_xmldoc(version) Creates a DOM document from scratch. Object
gmdate(format [, timestamp]) Formats a local date/time and returns a GMT date/time. String domxml_root(doc) Returns the root element node of a DOM document. Object
gmmktime(hour, minute, second, Returns the UNIX timestamp for a GMT time/date. Integer domxml_set_attribute(node, Sets an attribute of a node. Object
month, day, year [, is_dst]) name, value)
238 239
PHP PHP FUNCTIONS QUICK REFERENCE 12
FILESYSTEM FUNCTIONS (CONTINUED)
user_error(error_msg Generates a user-level error message. Void fopen(filename, mode Opens a file. Integer
[, error_type]) [, use_include_path])
fpassthru(file_pointer) Outputs all remaining data from a file. Integer
fputs(file_pointer, string Writes a string of a specific length to a file. Integer
FILESYSTEM FUNCTIONS [, length])
fread(file_pointer, length) Reads a specific number of characters from a file. String
Function Description Returns fscanf(handle, format Parses input from a file according to a specified format. Mixed
basename(path) Returns the filename from a path. String [, var1...])
chgrp(filename, group) Assigns a file to a group. Integer fseek(file_pointer, offset Moves the pointer in a file. Integer
[, whence])
chmod(filename, mode) Changes the mode of a file. Integer
fstat(file_pointer) Returns information about a file. Array
chown(filename, user) Changes the owner of a file. Integer
ftell(file_pointer) Returns the position of the pointer in a file. Integer
clearstatcache() Clears the file stat cache. Void
ftruncate(file_pointer, size) Truncates a file to a specific length. Integer
copy(source, destination) Copies a file. Integer
fwrite(file_pointer, string Writes a string of a specific length to a file. Integer
dirname(path) Returns the directory from a path. String [, length])
diskfreespace(directory) Returns the available space in a directory. Float is_dir(filename) Indicates whether a file is a directory. Boolean
240 241
PHP PHP FUNCTIONS QUICK REFERENCE 12
FORMS DATA FORMAT FUNCTIONS
242 243
PHP PHP FUNCTIONS QUICK REFERENCE 12
FUNCTION HANDLING FUNCTIONS (CONTINUED)
244 245
PHP PHP FUNCTIONS QUICK REFERENCE 12
IMAGE FUNCTIONS (CONTINUED)
246 247
PHP PHP FUNCTIONS QUICK REFERENCE 12
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED)
PHP FUNCTIONS QUICK REFERENCE Function Description Returns
imap_headers(imap_stream) Returns the headers for all messages in a mailbox. Array
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED) imap_last_error() Returns the last IMAP error for this page request. String
imap_listmailbox Returns a list of mailboxes. Array
Function Description Returns (imap_stream, ref, pattern)
imap_base64(text) Decodes base64 encoded text. String imap_listsubscribed Returns a list of all the subscribed mailboxes. Array
imap_binary(string) Converts an 8-bit string to a base64 string. String (imap_stream, ref, pattern)
imap_body(imap_stream, Returns a message body. String imap_mail(to, subject, Sends an e-mail message. String
msg_number [, flags]) message [,additional_headers
[, cc [, bcc [, rpath]]]])
imap_check(imap_stream) Checks the current mailbox. Object
imap_mail_compose(envelope, Creates a MIME message using the provided envelope String
imap_clearflag_full(stream, Clears message flags. String body) and body.
sequence, flag, options)
imap_mail_copy(imap_stream, Copies messages to a mailbox. Integer
imap_close(imap_stream Closes an IMAP stream. Integer msglist, mbox [, flags])
[, flags])
imap_mail_move(imap_stream, Moves messages to a mailbox. Integer
imap_createmailbox Creates a new mailbox. Integer msglist, mbox [, flags])
(imap_stream, mbox)
imap_mailboxmsginfo Returns information about the current mailbox. Object
imap_delete(imap_stream, Marks a message for deletion from the current mailbox. Integer (imap_stream)
msg_number [, flags])
imap_mime_header_decode(text) Decodes MIME header elements. Array
imap_deletemailbox Deletes a mailbox. Integer
(imap_stream, mbox) imap_msgno(imap_stream, uid) Returns the message sequence number for a UID. Integer
imap_errors() Returns all IMAP errors for this page request. Array imap_num_msg(imap_stream) Returns the number of messages in the current mailbox. Integer
imap_expunge(imap_stream) Deletes all messages marked for deletion. Integer imap_num_recent(imap_stream) Returns the number of recent messages in the current mailbox. Integer
imap_fetch_overview Returns an overview of header information for a message. Array imap_open(mbox, username, Opens an IMAP stream to a mailbox. Integer
(imap_stream, sequence password [, flags])
[, flags]) imap_ping(imap_stream) Checks if an IMAP stream is still active. Integer
imap_fetchbody(imap_stream, Fetches a section of the body of a message. String imap_qprint(string) Converts a quoted-printable string to an 8-bit string. String
msg_number, part_number
[, flags]) imap_renamemailbox Renames a mailbox. Integer
(imap_stream, old_mbox,
imap_fetchheader(imap_stream, Returns the header for a message. String new_mbox)
msg_number, flags)
imap_fetchstructure Returns the structure of a message. Object imap_reopen(imap_stream, Re-opens an IMAP stream to a new mailbox. Integer
mbox [, flags])
(imap_stream, msg_number
[, flags]) imap_rfc822_parse_adrlist Parses an address string. Array
(address, default_host)
imap_get_quota(imap_stream, Returns the quota level settings and usage statistics Array
quota_root) for a mailbox. imap_rfc822_parse_headers Parses mail headers from a string. Object
(headers [, defaulthost])
imap_getmailboxes Returns detailed information about each mailbox. Array
(imap_stream, ref, pattern) imap_rfc822_write_address Returns a formatted e-mail address from the provided String
imap_getsubscribed Returns a list of all the subscribed mailboxes. Array (mbox, host, personal) mailbox, host and personal information.
(imap_stream, ref, pattern) imap_scanmailbox(imap_stream, Searches the names of mailboxes for a specified string. Array
ref, pattern, content)
imap_header(imap_stream, Returns the header of a message. Object
msg_number [, fromlength imap_search(imap_stream, Returns messages matching the provided criteria. Array
[, subjectlength criteria, flags)
[, defaulthost]]])
imap_set_quota(imap_stream, Sets a quota for a mailbox. Integer
imap_headerinfo(imap_stream, Returns the header of a message. Object quota_root, quota_limit)
msg_number [, fromlength
[, subjectlength imap_setflag_full(stream, Sets flags on messages. String
[, defaulthost]]]) sequence, flag, options)
248 249
PHP PHP FUNCTIONS QUICK REFERENCE 12
PHP FUNCTIONS QUICK REFERENCE
IMAP, POP3 AND NNTP FUNCTIONS (CONTINUED) MATHEMATICAL FUNCTIONS (CONTINUED)
250 251
PHP PHP FUNCTIONS QUICK REFERENCE 12
NETWORK FUNCTIONS (CONTINUED)
PHP FUNCTIONS QUICK REFERENCE Function Description Returns
fsockopen([udp://]hostname, Opens a socket connection. Integer
MISCELLANEOUS FUNCTIONS port [, errno [, errstr
[, timeout]]])
Function Description Returns gethostbyaddr(ip_address) Finds the host name corresponding to an IP address. String
connection_aborted() Indicates whether a client has disconnected. Integer gethostbyname(hostname) Finds the IP address corresponding to a host name. String
connection_status() Returns the status of a connection. Integer gethostbynamel(hostname) Returns a list of IP addresses corresponding to a host name. Array
connection_timeout() Indicates whether a script has timed out. Integer getmxrr(hostname, mxhosts Finds the MX records corresponding to a host name. Integer
[, weight])
constant(name) Returns the value of a constant. Mixed
getprotobyname(name) Finds the protocol number associated with a protocol name. Integer
define(name, value Defines a named constant. Integer
[, case_insensitive]) getprotobynumber(number) Finds the protocol name associated with a protocol number. String
defined(name) Checks whether a named constant exists. Integer getservbyname(service, Finds the port number associated with a service and protocol. Integer
protocol)
die(message) Outputs a message and terminates the current script. Void
getservbyport(port, protocol) Finds the Internet service associated with a port and protocol. String
eval(string) Evaluates a string as PHP code. Mixed
ip2long(ip_address) Converts an IP address into the name of a computer. Integer
exit() Terminates the current script. Void
long2ip(proper_address) Converts the name of a computer into an IP address. String
get_browser([user_agent]) Determines the capabilities of a user's browser. Object
openlog(ident, option, Opens a connection to the system logger. Integer
highlight_file(filename) Prints a syntax highlighted version of a file. Boolean facility)
highlight_string(string) Prints a syntax highlighted version of a string. Boolean pfsockopen(hostname, port Opens a persistent socket connection. Integer
[, errno [, errstr
ignore_user_abort([setting]) Sets whether a client disconnecting will terminate the Integer [, timeout]]])
execution of a script.
socket_get_status Returns information about a socket resource. Array
iptcparse(iptcblock) Parses an IPTC block into its single tags. Array (socket_get_status)
leak(bytes) Leaks a specified amount of memory. Void socket_set_blocking Sets the blocking mode for a socket. Integer
(socket_descriptor, mode)
pack(format [, args...]) Packs arguments into a binary string using a specified format. String
socket_set_timeout Sets the timeout period on a socket. Boolean
show_source(filename) Prints a syntax highlighted version of a file. Boolean (socket_descriptor, seconds,
sleep(seconds) Delays execution of a script for a specified number of seconds. Void microseconds)
uniqid(prefix [, lcg]) Generates a prefixed unique ID based on the current time Integer syslog(priority, message) Writes a message to the system log. Integer
in microseconds.
unpack(format, data) Unpacks data from a binary string using a specified format. Array OUTPUT CONTROL FUNCTIONS
usleep(microseconds) Delays execution of a script for a specified number of Void
microseconds.
Function Description Returns
NETWORK FUNCTIONS flush() Flushes an output buffer. Void
ob_end_clean() Erases the contents of an output buffer and turns off output Void
buffering.
Function Description Returns
ob_end_flush() Sends the contents of an output buffer and turns off output Void
checkdnsrr(host [, type]) Searches the DNS for records of a specified type Integer buffering.
corresponding to a host.
ob_get_contents() Returns the contents of an output buffer. String
closelog() Closes a connection to the system logger. Integer
ob_get_length() Returns the length of the contents of an output buffer. String
debugger_off() Disables the internal PHP debugger. Integer
ob_gzhandler(buffer) Facilitates sending gz-encoded data to Web browsers. String
debugger_on(address) Enables the internal PHP debugger and connects it to Integer
an address. ob_implicit_flush([flag]) Turns implicit flushing on or off. Void
define_syslog_variables() Initializes all syslog related constants. Void ob_start([output_callback]) Turns on output buffering. Void
252 253
PHP PHP FUNCTIONS QUICK REFERENCE 12
PHP OPTIONS AND INFORMATION (CONTINUED)
254 255
PHP PHP FUNCTIONS QUICK REFERENCE 12
PHP FUNCTIONS QUICK REFERENCE PSPELL FUNCTIONS (CONTINUED)
pspell_add_to_session Adds a word to a wordlist in the current session. Integer preg_match_all(pattern, Searches for all matches to a regular expression, putting Integer
(dictionary_link, word) subject, matches [, order]) the results in matches.
pspell_check(dictionary_link, Checks the spelling of a word. Boolean preg_quote(string Puts a backslash in front of every regular expression character String
word) [, delimiter]) in a string.
pspell_clear_session Clears the current session and makes the current wordlist Integer preg_replace(pattern, Replaces matches to a regular expression. Mixed
(dictionary_link) blank. replacement, subject
[, limit])
pspell_config_create(language Creates a config used to open a dictionary. Integer
[, spelling [, jargon preg_replace_callback(pattern, Replaces matches to a regular expression using a callback. Mixed
[, encoding]]]) callback, subject [, limit])
pspell_config_ignore Ignores words shorter than a specified length. Integer preg_split(pattern, subject Splits a string using a regular expression. Array
(dictionary_link, n) [, limit [, flags]])
256 257
PHP PHP FUNCTIONS QUICK REFERENCE 12
STRING FUNCTIONS (CONTINUED)
session_id([id]) Returns or sets the current session ID. String hebrev(hebrew_text Converts logical Hebrew text to visual text. String
[, max_chars_per_line])
session_is_registered(name) Indicates whether a session variable is registered with the Boolean hebrevc(hebrew_text Converts logical Hebrew text to visual text with newline String
current session. [, max_chars_per_line]) conversion.
session_module_name([module]) Returns or sets the name of the current session module. String htmlentities(string Converts all applicable characters in a string to HTML entities. String
session_name([name]) Returns or sets the name of the current session. String [, quote_style])
session_register(name [, ...]) Registers one or more variables with the current session. Boolean htmlspecialchars(string Converts any special characters in a string to HTML entities. String
[, quote_style])
session_save_path([path]) Returns or sets the path where data for the current session String
is saved. implode(glue, pieces) Joins array elements into a single string. String
session_set_cookie_params Sets the session cookie parameters. Void join(glue, pieces) Joins array elements into a single string. String
(lifetime [, path [, domain]]) levenshtein(string1, string2) Calculates the Levenshtein distance between two strings. Integer
session_set_save_handler Sets user-level session storage functions. Void localeconv() Returns numeric formatting information based on the Array
(open, close, read, write, current locale.
destroy, gc)
session_start() Initializes a session. Boolean ltrim(string) Removes whitespace from the beginning of a string. String
session_unregister(name) Unregisters a session variable. Boolean md5(string) Calculates the MD5 hash of a string. String
session_unset() Frees all registered session variables. Void metaphone(string) Calculates the metaphone key of a string. String
nl2br(string) Inserts <br> before all line breaks in a string. String
ord(string) Returns the ASCII value of the first character of a string. Integer
parse_str(string [, arr]) Parses a string into variables as if it were a query string. Void
STRING FUNCTIONS
print(string) Outputs a string. Boolean
Function Description Returns printf(format [, args...]) Outputs a formatted string. Integer
addcslashes(string, charlist) Adds C style backslashes before characters in a string. String quoted_printable_decode Converts a quoted-printable string to an 8-bit string. String
(string)
addslashes(string) Adds backslashes before characters in a string that need String
to be quoted in database queries. quotemeta(string) Escapes metacharacters in a string. String
bin2hex(string) Converts binary data into hexadecimal representation. String rtrim(string) Removes trailing whitespace from a string. String
chop(string) Removes trailing whitespace from a string. String setlocale(category, locale) Sets locale information for functions of a category. String
chr(ascii) Returns the character for an ASCII value. String similar_text(string1, string2 Calculates the similarity between two strings. Integer
[, percent])
chunk_split(string Splits a string into smaller pieces. String
[, chunklen [, end]]) soundex(string) Calculates the soundex key of a string. String
258 259
PHP PHP FUNCTIONS QUICK REFERENCE 12
260 261
PHP PHP FUNCTIONS QUICK REFERENCE 12
is_resource(variable) Indicates whether a variable is a resource. Boolean xml_get_current_column_number Returns the current column number for an XML parser. Integer
(parser)
is_scalar(variable) Indicates whether a variable is a scalar. Boolean
xml_get_current_line_number Returns the current line number for an XML parser. Integer
is_string(variable) Indicates whether a variable is a string. Boolean (parser)
isset(variable) Indicates whether a value has already been assigned to Integer xml_get_error_code(parser) Returns the error code for the last occurring XML parser error. Integer
a variable.
xml_parse(parser, data Parses specified XML data. Integer
print_r(expression) Prints human-readable information about a variable. Void [, is_final])
serialize(value) Generates a storable representation of a value. String xml_parse_into_struct(parser, Parses XML data into two arrays. Integer
data, values, index)
settype(variable, type) Converts a variable to a specified data type. Integer
xml_parser_create([encoding]) Creates an XML parser. Integer
strval(variable) Returns the string value of a variable. String
xml_parser_free(parser) Frees an XML parser. String
unserialize(string) Creates a PHP value from a stored representation. Mixed
xml_parser_get_option(parser, Returns the value of an option for an XML parser. Mixed
unset(variable Destroys a variable. Integer option)
[, variable [, ...]])
xml_parser_set_option(parser, Sets an option for an XML parser to a specified value. Integer
var_dump(expression) Dumps information about an expression. Void option, value)
262 263
PHP PHP FUNCTIONS QUICK REFERENCE 12
264 265