Language Reference

What is PHP3?

PHP Version 3.0 is a server-side HTML-embedded scripting language.

What can PHP3 do?

Perhaps the strongest and most significant feature in PHP3 is its database integration layer. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

Oracle Adabas D

Sybase FilePro

mSQL Velocis

MySQL Informix

Solid dBase

ODBC Unix dbm

PostgreSQL

A Brief History of PHP

PHP was conceived sometime in the fall of 1994 by Rasmus Lerdorf. Early non-released versions were used on his home page to keep track of who was looking at his online resume. The first version used by others was available sometime in early 1995 and was known as the Personal Home Page Tools. It consisted of a very simplistic parser engine that only understood a few special macros and a number of utilities that were in common use on home pages back then. A guestbook, a counter and some other stuff. The parser was rewritten in mid-1995 and named PHP/FI Version 2. The FI came from another package Rasmus had written which interpreted html form data. He combined the Personal Home Page tools scripts with the Form Interpreter and added mSQL support and PHP/FI was born. PHP/FI grew at an amazing pace and people started contributing code to it.

It is hard to give any hard statistics, but it is estimated that by late 1996 PHP/FI was in use on at least 15,000 web sites around the world. By mid-1997 this number had grown to over 50,000. Mid-1997 also saw a change in the development of PHP. It changed from being Rasmus' own pet project that a handful of people had contributed to, to being a much more organized team effort. The parser was rewritten from scratch by Zeev Suraski and Andi Gutmans and this new parser formed the basis for PHP Version 3. A lot of the utility code from PHP/FI was ported over to PHP3 and a lot of it was completely rewritten.

Today (mid-1998) either PHP/FI or PHP3 ships with a number of commercial products such as C2's StrongHold web server and RedHat Linux and a conservative estimate based on an extrapolation from numbers provided by NetCraft would be that PHP is in use on 150,000 sites around the world. To put that in perspective, that is more sites than run Netscape's flagship Enterprise server on the Internet.

HTTP authentication with PHP

The HTTP Authentication hooks in PHP are only available when it is running as an Apache module. In an Apache module PHP script, it is possible to use the Header function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the variables, $PHP_AUTH_USER, $PHP_AUTH_PW and $PHP_AUTH_TYPE set to the user name, password and authentication type respectively. Only "Basic" authentication is supported at this point.

An example script fragment which would force client authentication on a page would be the following:

Example 2-1. HTTP Authentication example

<?php

if(!isset($PHP_AUTH_USER)) {

Header("WWW-Authenticate: Basic realm=\"My Realm\""); Header("HTTP/1.0 401 Unauthorized");

echo "Text to send if user hits Cancel button\n"; exit;

} else {

echo "Hello $PHP_AUTH_USER.<P>";

echo "You entered $PHP_AUTH_PW as your password.<P>";

}

?>

Instead of simply printing out the $PHP_AUTH_USER and $PHP_AUTH_PW, you would probably want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.

In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page.

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

GIF creation with PHP

PHP is not limited to creating just HTML output. It can also be used to create GIF image files, or even more convenient GIF image streams. You will need to compile PHP with the GD library of image functions for this to work.

Example 2-2. GIF creation with PHP

<?php

Header("Content-type: image/gif");

$string=implode($argv," ");

$im = imagecreatefromgif("images/button1.gif");

$orange = ImageColorAllocate($im, 220, 210, 60); px = (imagesx($im)-7.5*strlen($string))/2; ImageString($im,3,$px,9,$string,$orange); ImageGif($im);

ImageDestroy($im);

?>

This example would be called from a page with a tag like: <img src="button.php?text"> The above button.php3 script then takes this "text" string an overlays it on top of a base image which in this case is "images/button1.gif" and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.

File upload support

PHP is capable of receiving file uploads from any RFC-1867 compliant browser. This feature lets people upload both text and binary files. With PHP's authentication and logical functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.

A file upload screen can be built by creating a special form which looks something like this:

Example 2-3. File Upload Form

<FORM ENCTYPE="multipart/form-data" ACTION="_URL_" METHOD=POST>

<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000"> Send this file: <INPUT NAME="userfile" TYPE="file">

<INPUT TYPE="submit" VALUE="Send File">

</FORM>

The _URL_ should point to a php html file. The MAX_FILE_SIZE hidden field must precede the file input field and its value is the maximum filesize accepted. The value is in bytes. In this destination file, the following variables will be defined upon a successful upload:

  • $userfile - The temporary filename in which the uploaded file was stored on the server machine.

  • $userfile_name - The original name of the file on the sender's system.

  • $userfile_size - The size of the uploaded file in bytes.

  • $userfile_type - The mime type of the file if the browser provided this information. An example would be "image/gif".

Note that the "$userfile" part of the above variables is whatever the name of the INPUT field of TYPE=file is in the upload form. In the above upload form example, we chose to call it "userfile".

Files will by default be stored in the server's default temporary directory. This can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using a PutEnv() call from within a PHP script will not work though.

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can for example use the $file_size variable to throw away any files that are either too small or too big. You could use the $file_type variable to throw away any files that didn't match a certain type criteria. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature.

HTTP cookie support

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie function. Cookies are part of the HTTP header, so the SetCookie() function must be called before any output is sent to the browser. This is the same restriction as for the Header function.

Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data. If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For more details see the setcookie function.

Database support

PHP supports a number of different databases in both native mode and through ODBC.

Regular expressions

Regular expressions are used for complex string manipulation in PHP. The functions that support regular expressions are:

  • ereg

  • ereg_replace

  • eregi

  • eregi_replace

  • split

These functions all take a regular expression string as their first argument. PHP uses the Posix extended regular expressions as defined by Posix 1003.2. For a full description of Posix regular expressions see the regex man pages included in the regex directory in the PHP distribution.

Example 2-4. Regular expression examples

ereg("abc",$string); /* Returns true if "abc" is found anywhere in $string.

*/

ereg("^abc",$string); /* Returns true if "abc" is found at the beginning of

$string. */

ereg("abc$",$string); /* Returns true if "abc" is found at the end of

$string. */

eregi("(ozilla.[23]|MSIE.3)",$HTTP_USER_AGENT); /* Returns true if client browser is Netscape 2, 3 or MSIE 3. */

ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)",$string,$regs); /* Places three space separated words into $regs[1], $regs[2] and $regs[3]. */ ereg_replace("^","<BR>",$string); /* Put a <BR> tag at the beginning of

$string. */

ereg_replace("$","<BR>",$string); /* Put a <BR> tag at the end of $string. */ ereg_replace("\n","",$string); /* Get rid of any carriage return characters in $string. */

Error handling

There are 4 types of errors and warnings in PHP. They are:

  • 1 - Normal Function Errors

  • 2 - Normal Warnings

  • 4 - Parser Errors

  • 8 - Notices (warnings you can ignore but which may imply a bug in your code)

The above 4 numbers are added up to define an error reporting level. The default error reporting level is 7 which is 1 + 2 + 4, or everything except notices. This level can be changed in the php3.ini file with the error_reporting directive. It can also be set in your Apache httpd.conf file with the php3_error_reporting directive or lastly it may be set at runtime within a script using the error_reporting function.

All PHP expressions can also be called with the "@" prefix, which turns off error reporting for that particular expression. If an error occurred during such an expression and the track_errors feature is enabled, you can find the error message in the global variable $php_errormsg.

PHP source viewer

Chapter 3. Installation

This chapter will guide you through the configuration and installation of PHP3. Prerequisite knowledge and software:

  • Basic UNIX skills (being able to operate "make" and a C compiler)

  • An ANSI C compiler

  • A web server (obviously)

Installing From Source on UNIX

Downloading Source

The source code for the latest version can be found at http://www.php.net.

Quick Installation Instructions (Apache Module Version)

  1. gunzip apache_1.3.x.tar.gz

  2. tar xvf apache_1.3.x.tar

  3. gunzip php-3.0.x.tar.gz

  4. tar xvf php-3.0.x.tar

  5. cd apache_1.3.x

  6. ./configure --prefix=/www 7. cd ../php-3.0.x

  1. ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track- vars

  2. make

  3. make install

  4. cd ../apache_1.3.x

  5. ./configure --prefix=/www

    --activate-module=src/modules/php3/libphp3.a

  6. make

  7. make install

Instead of this step you may prefer to simply copy the httpd binary overtop of your existing binary. Make sure you shut down your server first though.

15. cd ../php-3.0.x

  1. cp php3.ini-dist /usr/local/lib/php3.ini

You can edit /usr/local/lib/php3.ini file to set PHP options.

If you prefer this file in another location, use --with-config-file=/path in step 8.

  1. Edit your httpd.conf or srm.conf file and add: AddType

    application/x-httpd-php3 .php3

You can choose any extension you wish here. .php3 is simply the one we suggest.

  1. Use your normal procedure for starting the Apache server.

Configuration

There are two ways of configuring PHP3.

  • Using the "setup" script that comes with PHP3. This script asks you a series of questions (almost like the "install" script of PHP/FI 2.0) and runs "configure" in the end. To run this script, type ./setup.

This script will also create a file called "do-conf", this file will contain the options passed to configure. You can edit this file to change just a few options without having to re-run setup. Then type ./do-conf to run configure with the new options.

  • Running configure by hand. To see what options you have, type

    ./configure --help. Details about some of the different configuration options are listed below.

Apache module

To build PHP3 as an Apache module, answer "yes" to "Build as an Apache module?" (the --with- apache=DIR option to configure) and specify the Apache distribution base directory. If you have unpacked your Apache distribution in /usr/local/www/apache_1.2.4, this is your Apache distribution base directory. The default directory is /usr/local/etc/httpd.

fhttpd module

To build PHP3 as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with- fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is

/usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better

performance, more control and remote execution capability.

CGI version

The default is to build PHP3 as a CGI program. If you are running a web server PHP3 has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables Apache users to run different PHP3-enabled pages under different user-ids. Please make sure you read through the Security chapter if you are going to run PHP as a CGI.

Database Support Options

PHP3 has native support for a number of databases (as well as ODBC):

Adabas D

--with-adabas*=DIR*

Compiles with Adabas D support. The parameter is the Adabas D install directory and defaults to

/usr/local/adabasd.

Adabas home page

dBase

--with-dbase

Enables the bundled DBase support. No external libraries are required.

filePro

--with-filepro

Enables the bundled read-only filePro support. No external libraries are required.

mSQL

--with-msql*=DIR*

Enables mSQL support. The parameter to this option is the mSQL install directory and defaults to

/usr/local/Hughes. This is the default directory of the mSQL 2.0 distribution. configure automatically detects which mSQL version you are running and PHP3 supports both 1.0 and 2.0, but if you compile PHP3 with mSQL 1.0, you can only access mSQL 1.0 databases, and vice-versa.

See also mSQL Configuration Directives in the configuration file. mSQL home page

MySQL

--with-mysql*=DIR*

Enables MySQL support. The parameter to this option is the MySQL install directory and defaults to

/usr/local. This is the default installation directory of the MySQL distribution. See also MySQL Configuration Directives in the configuration file.

MySQL home page

iODBC

--with-iodbc*=DIR*

Includes iODBC support. This feature was first developed for iODBC Driver Manager, a freely redistributable ODBC driver manager which runs under many flavors of UNIX. The parameter to this option is the iODBC installation directory and defaults to /usr/local.

FreeODBC home page

OpenLink ODBC

--with-openlink*=DIR*

Includes OpenLink ODBC support. The parameter to this option is the OpenLink ODBC installation directory and defaults to /usr/local/openlink.

OpenLink Software's home page

Oracle

--with-oracle*=DIR*

Includes Oracle support. Has been tested and should be working at least with Oracle versions 7.0 through 7.3. The parameter is the ORACLE_HOME directory. You do not have to specify this parameter if your Oracle environment has been set up.

Oracle home page

PostgreSQL

--with-pgsql*=DIR*

Includes PostgreSQL support. The parameter is the PostgreSQL base install directory and defaults to

/usr/local/pgsql.

See also Postgres Configuration Directives in the configuration file. PostgreSQL home page

Solid

--with-solid*=DIR*

Includes Solid support. The parameter is the Solid install directory and defaults to /usr/local/solid. Solid home page

Sybase

--with-sybase*=DIR*

Includes Sybase support. The parameter is the Sybase install directory and defaults to /home/sybase. See also Sybase Configuration Directives in the configuration file.

Sybase home page

Sybase-CT

--with-sybase-ct*=DIR*

Includes Sybase-CT support. The parameter is the Sybase-CT install directory and defaults to

/home/sybase.

See also Sybase-CT Configuration Directives in the configuration file.

Velocis

--with-velocis*=DIR*

Includes Velocis support. The parameter is the Velocis install directory and defaults to

/usr/local/velocis. Velocis home page

A custom ODBC library

--with-custom-odbc*=DIR*

Includes support for an arbitrary custom ODBC library. The parameter is the base directory and defaults to /usr/local.

This option implies that you have defined CUSTOM_ODBC_LIBS when you run the configure script. You also must have a valid odbc.h header somewhere in your include path. If you don't have one, create it and include your specific header from there. Your header may also require some extra definitions, particularly when it is multiplatform. Define them in CFLAGS.

For example, you can use Sybase SQL Anywhere on QNX as following: CFLAGS=-DODBC_QNX LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc" ./configure --with-custom- odbc=/usr/lib/sqlany50

Unified ODBC

--disable-unified-odbc

Disables the Unified ODBC module, which is a common interface to all the databases with ODBC- based interfaces, such as Solid and Adabas D. It also works for normal ODBC libraries. Has been tested with iODBC, Solid, Adabas D and Sybase SQL Anywhere. Requires that one (and only one) of these modules or the Velocis module is enabled, or a custom ODBC library specified. This option is only applicable if one of the following options is used: --with-iodbc, --with-solid, --with-adabas, --with- velocis, or --with-custom-odbc,

See also Unified ODBC Configuration Directives in the configuration file.

LDAP

--with-ldap*=DIR*

Includes LDAP (Lightweight Directory Access Protocol) support. The parameter is the LDAP base install directory, defaults to /usr/local/ldap.

More information about LDAP can be found in RFC1777 and RFC1778.

Other configure options

--with-xml

--with-xml

Include support for a non-validating XML parser using James Clark's expat library. See the XML function reference for details.

--enable-maintainer-mode

--enable-maintainer-mode

Turns on extra dependencies and compiler warnings used by some of the PHP3 developers.

--with-system-regex

--with-system-regex

Uses the system's regular expression library rather than the bundled one. If you are building PHP3 as a server module, you must use the same library when building PHP3 as when linking the server. Enable this if the system's library provides special features you need. It is recommended that you use the bundled library if possible.

--with-config-file-path

--with-config-file-path=DIR

The path used to look for the php3.ini file when PHP starts up.

--with-exec-dir

--with-exec-dir*=DIR*

Only allow running of executables in DIR when in safe mode. Defaults to /usr/local/bin. This option only sets the default, it may be changed with the safe_mode_exec_dir directive in the configuration file later.

--disable-debug

--disable-debug

Does not include debug information in the library or executable. The debug information makes it easier to pinpoint bugs, so it is a good idea to leave debug on as long as PHP3 is in alpha or beta state.

--enable-safe-mode

--enable-safe-mode

Enables "safe mode" by default. This imposes several restrictions on what PHP can do, such as opening only files within the document root. Read the Security chapter for more more information. CGI users should always enable secure mode. This option only sets the default, it may be enabled or disabled with the safe_mode directive in the configuration file later.

--enable-track-vars

--enable-track-vars

Makes PHP3 keep track of where GET/POST/cookie variables come from in the arrays HTTP_GET_VARS, HTTP_POST_VARS and HTTP_COOKIE_VARS. This option only sets the default, it may be enabled or disabled with the track_vars directive in the configuration file later.

--enable-magic-quotes

--enable-magic-quotes

Enable magic quotes by default. This option only sets the default, it may be enabled or disabled with the magic_quotes_runtime directive in the configuration file later. See also the magic_quotes_gpc and the magic_quotes_sybase directives.

--enable-debugger

--enable-debugger

Enables the internal PHP3 debugger support. This feature is still in an experimental state. See also the Debugger Configuration directives in the configuration file.

--enable-discard-path

--enable-discard-path

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security. Read the section in the security chapter about this option.

--enable-bcmath

--enable-bcmath

Enables bc style arbitrary precision math functions. See also the bcmath.scale option in the configuration file.

--enable-force-cgi-redirect

--enable-force-cgi-redirect

Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.

When using PHP as a CGI binary, PHP by default always first checks that it is used by redirection (for example under Apache, by using Action directives). This makes sure that the PHP binary cannot be used to bypass standard web server authentication procedures by calling it directly, like http://my.host/cgi-bin/php/secret/doc.html. This example accesses http://my.host/secret/doc.html but does not honour any security settings enforced by httpd for directory /secret.

Not enabling option disables the check and enables bypassing httpd security and authentication settings. Do this only if your server software is unable to indicate that a safe redirection was done and all your files under your document root and user directories may be accessed by anyone.

Read the section in the security chapter about this option.

--disable-short-tags

--disable-short-tags

Disables the short form <? ?> PHP3 tags. You must disable the short form if you want to use PHP3 with XML. With short tags disabled, the only PHP3 code tag is <?php ?>. This option only sets the default, it may be enabled or disabled with the short_open_tag directive in the configuration file later.

--enable-url-includes

--enable-url-includes

Makes it possible to run code on other HTTP or FTP servers directly from PHP3 with include(). See also the include_path option in the configuration file.

--disable-syntax-hl

--disable-syntax-hl

Turns off syntax highlighting.

CPPFLAGS and LDFLAGS

To make the PHP3 installation look for header or library files in different directories, modify the CPPFLAGS and LDFLAGS environment variables, respectively. If you are using a sensible shell, you should be able to do LDFLAGS=-L/my/lib/dir CPPFLAGS=-I/my/include/dir ./configure

Building

When PHP3 is configured, you are ready to build the CGI executable or the PHP3 library. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.

VPATH

Testing

If you have built PHP3 as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP3 on your platform early instead of having to struggle with it later.

Benchmarking

If you have built PHP3 as a CGI program, you may benchmark your build by typing make bench. Note that if safe mode is on by default, the benchmark may not be able to finish if it takes longer then the 30 seconds allowed. This is because the set_time_limit can not be used in safe mode. Use the max_execution_time to control this time for you own scripts. make bench ignores the configuration file.

Installing PHP on Windows95/NT

Apache/NT and Stronghold/NT

Follow the instructions for configuration under Unix.

IIS and MS-PWS

You can access php scripts simply by putting the php.exe file into your scripts directory and using a url such as: http://my.server/scripts/php.exe/page.php

Redirection If you would like to use a url like: http://my.server/page.php you will have to edit your registry.

Disclaimer: Be sure you make a backup of your registry before editing it. The PHP Development Team is not responsible for damaged registries. If you damage your registry, you may not be able to restart your computer without reinstalling your OS!

You can edit your registry by running regedit.exe. To do this, choose Run... from the Start menu, and type regedit then click on OK. The registry setting you need to edit is: HKEY_LOCAL_MACHINE:System:CurrentControlSet:Services:W3Svc:Parameters:ScriptMap. Add a

new string value here with the extension you would like to use for your php scripts, and make the value data the path to the php executable: .phtm3 "c:\webshare\scripts\php.exe"

For the ISAPI version of PHP, use something like: .phtm "c:\webshare\scripts\php3_isapi.dll"

You must also make any directories containing php scripts executable. This is done in the IIS administrator. Consult your IIS documentation for more information.

For other servers consult your server documentation.

PHP.INI File Under Windows, PHP will look for php3.ini automaticaly, first under the windows os directory (c:\windows or c:\winnt) then in the directory in which the PHP executable resides. Alternately, you can set the environment variable PHPRC=\pathto\php3.ini, though this does not work with all servers (apache for one).

Problems?

Read the FAQ

Some problems are more common than others. The most common ones are listed in the PHP3 FAQ, found at http://www.php.net/FAQ.php3

Bug reports

If you think you have found a bug in PHP3, please report it. The PHP3 developers probably don't know about it, and unless you report it, chances are it won't be fixed. A form for reporting bugs is available on the PHP3 network of sites, the main form is at http://ca.php.net/bugs.php3.

Other problems

If you are still stuck, someone on the PHP3 mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archive is available at http://www.tryc.on.ca/php3.html. To subscribe to the PHP3 mailing list, send an empty mail to php3-subscribe@lists.php.net. The mailing list address is php3@lists.php.net.

If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what PHP version, what web server, if you are running PHP as CGI or a server module, etc.), and preferably enough code to make others able to reproduce and test your problem.

Security

PHP is a powerful tool. As with many other powerful tools, it is possible to shoot yourself in the foot with it. PHP has functionality that, if carelessly used, may cause security problems on your system. The best way of preventing this is to always know what you are doing. Read the Security chapter for more information.

Chapter 4. Configuration

The php3.ini file

The php3.ini file is read when PHP's parser starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI version, it happens on every invocation.

Just about every directive listed here has a corresponding Apache httpd.conf directive. Simply prepend php3_ to the start of the directive names listed here.

General Configuration Directives

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the include function, so include_path is used.

The special value none disables auto-appending.

If the script is terminated with exit, auto-append will not occur.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the include function, so include_path is used.

The special value none disables auto-prepending.

cgi_ext string

display_errors boolean

This determines whether errors should be printed to the screen as part of the HTML output or not.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served.

engine boolean

This directive is really only useful in the Apache module version of PHP. It is used by sites that would like to turn PHP parsing on and off on a per-directory or per-virtual server basis. By putting php3_engine off in the appropriate places in the httpd.conf file, PHP can be enabled or disabled.

error_log string

Name of file where script errors should be logged. If the special value syslog is used, the errors are sent to the system logger instead. On UNIX, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95.

error_reporting integer

Set the error reporting level. The parameter is an integer representing a bit field. Add the values of the error reporting levels you want.

Table 4-1. Error Reporting Levels

value

bled reporting

mal errors
mal warnings

er errors

-critical style-related warnings

The default value for this directive is 7 (normal errors, normal warnings and parser errors are shown).

open_basedir string

Limit the files that can be opened by PHP to the specified directory-tree.

When a script tries to open a file with, for example, fopen or gzopen, the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink.

The special value . indicates that the directory in which the script is stored will be used as base- directory.

The default is to allow all files to be opened.

gpc_order string

Set the order of GET/POST/COOKIE variable parsing. The default setting of this directive is "GPC". Setting this to "GP", for example, will cause PHP to completely ignore cookies and to overwrite any GET method variables with POST-method variables of the same name.

include_path string

Specifies a list of directories where the require, include and fopen_with_path functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in UNIX or semicolon in Windows.

Example 4-1. UNIX include_path

include_path=.:/home/httpd/php-lib

Example 4-2. Windows include_path

include_path=.;c:\www\phplib

The default value for this directive is . (only the current directory).

isapi_ext string

log_errors boolean

Tells whether script error messages should be logged to the server's error log. This option is thus server-specific.

magic_quotes_gpc boolean

Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \
(backslash) and NUL's are escaped with a backslash automatically. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

magic_quotes_runtime boolean

If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

magic_quotes_sybase boolean

If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime is enabled.

max_execution_time integer

This sets the maximum time in seconds a script is allowed to take before it is terminated by the parser. This helps prevent poorly written scripts from tieing up the server.

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server.

nsapi_ext string

short_open_tag boolean

Tells whether the short form (<? ?>of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you have to disable this option. If disabled, you must use the long form of the open tag (<?php ?>).

sql.safe_mode boolean

track_errors boolean

If enabled, the last error message will always be present in the global variable $php_errormsg.

track_vars boolean

If enabled, GET, POST and cookie input can be found in the global associative arrays

$HTTP_GET_VARS, $HTTP_POST_VARS and $HTTP_COOKIE_VARS, respectively.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as.

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example

public_html.

warn_plus_overloading boolean

If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).

Mail Configuration Directives

SMTP string

DNS name or IP address of the SMTP server PHP under Windows should use for mail sent with the

mail function.

sendmail_from string

Which "From:" mail address should be used in mail sent from PHP under Windows.

sendmail_path string

Where the sendmail program can be found, usually /usr/sbin/sendmail or

/usr/lib/sendmail configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if any. For example, Qmail users can normally set it to

/var/qmail/bin/sendmail.

Safe Mode Configuration Directives

safe_mode boolean

Whether to enable PHP's safe mode.

safe_mode_exec_dir string

If PHP is used in safe mode, system and the other functions executing system programs refuse to start programs that are not in this directory.

Debugger Configuration Directives

debugger.host string

DNS name or IP address of host used by the debugger.

debugger.port string

Port number used by the debugger.

debugger.enabled boolean Whether the debugger is enabled.

Extension Loading Directives

enable_dl boolean

This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl on and off per virtual server or per directory.

The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all the safe_mode and open_basedir restrictions.

The default is to allow dynamic loading, except when using safe-mode. In safe-mode, it's always imposible to use dl.

extension_dir string

In what directory PHP should look for dynamically loadable extensions.

extension string

Which dynamically loadable extensions to load when PHP starts up.

MySQL Configuration Directives

mysql.allow_persistent boolean

Whether to allow persistent MySQL connections.

mysql.max_persistent integer

The maximum number of persistent MySQL connections per process.

mysql.max_links integer

The maximum number of MySQL connections per process, including persistent connections.

mSQL Configuration Directives

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

The maximum number of mSQL connections per process, including persistent connections.

Postgres Configuration Directives

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

pgsql.max_links integer

The maximum number of Postgres connections per process, including persistent connections.

Sybase Configuration Directives

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process.

sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections.

Sybase-CT Configuration Directives

sybct.allow_persistent boolean

Whether to allow persistent Sybase-CT connections.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections.

BC Math Configuration Directives

bcmath.scale integer

Number of decimal digits for all bcmath functions.

Browser Capability Configuration Directives

browscap string

Name of browser capabilities file.

Unified ODBC Configuration Directives

uodbc.default_db string

ODBC data source to use if none is specified in odbc_connect or odbc_pconnect.

uodbc.default_user string

User name to use if none is specified in odbc_connect or odbc_pconnect.

uodbc.default_pw string

Password to use if none is specified in odbc_connect or odbc_pconnect.

uodbc.allow_persistent boolean

Whether to allow persistent ODBC connections.

uodbc.max_persistent integer

The maximum number of persistent ODBC connections per process.

uodbc.max_links integer

The maximum number of ODBC connections per process, including persistent connections.

Apache Module

Apache module configuration directives CGI redirection module/action module CGI

Virtual hosts

Security

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options it gives you exactly the combination of freedom and security you need.

As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup. This chapter explains the different configuration option combinations and the situations they can be safely used.

CGI binary

Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory CA-96.11 recommends agains placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd

The query information in an url after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.

When invoked as a CGI binary, PHP refuses to interpret the command line arguments.

The path information part of the url after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php3 to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php3. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file

/secret/script.php3, but only for the /cgi-bin/php file. This way any user able to access

/cgi-bin/php is able to access any protected document on the web server.

In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full explanation of different combinations.

Case 1: only public files served

If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate with the PHP binary that the request is a safely redirected request, you can specify the option --disable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php3 nor by redirection http://my.host/dir/script.php3.

Redirection can be configured for example in apache by directives AddHandler and Action (see below).

Case 2: using --enable-force-cgi-redirect

This compile-time option prevents anyone from calling PHP directly with a url like http://my.host/cgi-bin/php/secretdir/script.php3. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.

Usually the redirection in the Apache configuration is done with the following directives:

Action php3-script /cgi-bin/php AddHandler php3-script .php3

This option has only been tested with the Apache web server, and relies on Apache to set the non- standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.

Case 3: setting doc_root or user_dir

To include active content, like scripts and executables, in the web server document directories is sometimes consider an insecure practice. If for some configuration mistake the scripts are not executed but displayed as usual HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that is only accessible through the PHP CGI, and therefore always interpreted and not displayed as such.

Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.

You can set the PHP script document root by the configuration directive doc_root in the php3.ini file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).

Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root. Opening an url like http://my.host/~user/doc.php3 does not result in opening a file under users home directory, but a file called ~user/doc.php3 under doc_root (yes, a directory name starting with a tilde [~]).

If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php3 will open a file called doc.php3 under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is

/home/user/public_php/doc.php3.

user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.

Case 4: PHP parser outside of web tree

A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In

/usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

#!/usr/local/bin/php

as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.

To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the php parser should be compiled with the --enable-discard-path configure option.

Apache module

When PHP is used as an Apache module it inherits Apache's security setup. A request for a file will have to go through Apache's regular checks and only if these are passed successfully does the request make it way to PHP.

Chapter 5. Syntax and grammar

PHP's syntax is borrowed primarily from C. Java and Perl have also influenced the syntax.

Escaping from HTML

There are three ways of escaping from HTML and entering "PHP code mode":

Example 5-1. Ways of escaping from HTML
  1. <? echo("this is the simplest, an SGML processing instruction\n"); ?>

  2. <?php echo("if you want to serve XML documents, do like this\n"); ?>

  3. <script language="php">

echo("some editors (like FrontPage) don't like processing instructions");

</script>

  1. <% echo("As of PHP 3.0.4 you may optionally use ASP-style tags"); %>

Instruction separation Variable types Variable initialization

To initialize a variable in PHP, you simply assign a value to it. For most types, this is straightforward; arrays and objects, however, can use slightly different mechanisms.

Initializing Arrays

An array may be initialized in one of two ways: by the sequential assigning of values, and by using the

array construct (which is documented in the Array functions section).

To sequentially add values to an array, you simply assign to the array variable using an empty subscript. The value will be added as the last element of the array.

$names[] = "Jill"; // $names[0] = "Jill"

$names[] = "Jack"; // $names[1] = "Jack"

Initializing objects

To initialize an object, you use the new statement to instantiate the object to a variable.

class foo {

function do_foo() { echo "Doing foo.";

}

}

$bar = new foo;

$bar->do_foo();

Variable Scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

$a=1; /* global scope */ Function Test() {

echo $a; /* reference to local scope variable */

}

Test();

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function. An example:

$a=1;

$b=2;

Function Sum() { global $a,$b;

$b = $a + $b;

}

Sum(); echo $b;

The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

$a=1;

$b=2;

Function Sum() {

$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];

}

Sum(); echo $b;

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element.

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

Function Test() {

$a=0; echo $a;

$a++;

}

This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Function Test() { static $a=0; echo $a;

$a++;

}

Now, every time the Test() function is called it will print the value of $a and increment it.

Static variables are also essential when functions are called recursively. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10:

Function Test() { static $count=0;

$count++; echo $count;

if($count < 10) { Test();

}

}

Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

$a = "hello";

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. ie.

$$a = "world";

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

echo "$a ${$a}";

produces the exact same output as:

echo "$a $hello";

ie. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is:

${$a[1]} for the first case and ${$a}[1] for the second.

Variables from outside PHP

HTML Forms (GET and POST)

IMAGE SUBMIT variable names

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type=image src="image.gif" name="sub">

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

HTTP Cookies

PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the SetCookie function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the Header function. Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data.

If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For example:

SetCookie("MyCookie[]","Testing", time()+3600);

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example 5-2. SetCookie Example

$Count++;

SetCookie("Count",$Count, time()+3600); SetCookie("Cart[$Count]",$item, time()+3600);

Environment variables

PHP automatically makes environment variables available as normal PHP variables.

echo $HOME; /* Shows the HOME environment variable, if set. */

Since information coming in via GET, POST and Cookie mechanisms also automatically create PHP variables, it is sometimes best to explicitly read a variable from the environment in order to make sure that you are getting the right version. The getenv function can be used for this. You can also set an environment variable with the putenv function.

Server configuration directives

Type juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a double, then all operands are evaluated as doubles, and the result will be a double. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

$foo = "0"; // $foo is a string (ASCII 48)

$foo++; // $foo is the string "1" (ASCII 49)

$foo += 1; // $foo is now an integer (2)

$foo = $foo + 1.3; // $foo is now a double (3.3)

$foo = 5 + "10 Little Piggies"; // $foo is a double (15)

$foo = 5 + "10 Small Pigs"; // $foo is an integer (15)

If the last two examples above seem odd, see String conversion.

If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype.

Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is. They are gettype, is_long, is_double, is_string, is_array, and is_object.

Type casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

$foo = 10; // $foo is an integer

$bar = (double) $foo; // $bar is a double

The casts allowed are:

  • (int), (integer) - cast to integer

  • (real), (double), (float) - cast to double

  • (string) - cast to string

  • (array) - cast to array

  • (object) - cast to object

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

$foo = (int) $bar;

$foo = ( int ) $bar;

String conversion

When a string is evaluated as a numeric value, the resulting value and type are determined as follows.

The string will evaluate as a double if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

$foo = 1 + "10.5"; // $foo is a double (11.5)

$foo = 1 + "-1.3e3"; // $foo is a double (-1299)

$foo = 1 + "bob-1.3e3"; // $foo is a double (1)

$foo = 1 + "bob3"; // $foo is an integer (1)

$foo = 1 + "10 Small Pigs"; // $foo is an integer (11)

$foo = 1 + "10 Little Piggies"; // $foo is a double (11); the string contains 'e'

For more information on this conversion, see the Unix manual page for strtod(3).

Array manipulation

PHP supports both scalar and associative arrays. In fact, there is no difference between the two. You can create an array using the array function, or you can explicitly set each array element value.

$a[0] = "abc";

$a[1] = "def";

$b["foo"] = 13;

Arrays may be sorted using the sort, ksort and asort functions depending on the type of sort you want.

You can count the number of items in an array using the count function.

You can traverse an array using next and prev functions. Another common way to traverse an array is to use the each

Chapter 6. Language constructs

Any PHP 3 script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement of even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.

Expressions

Expressions are the most important building stones of PHP. In PHP 3.0, almost anything you write is an expression. The simplest yet most accurate way to define an expressions is "anything that has a value".

Simple examples that come in mind are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function:

function foo()

{

return 5;

}

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports 3 scalar value types: integer values, floating point values and string values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

So far, users of PHP/FI 2 shouldn't feel any change. However, PHP 3 takes expressions much further, in the same way many other languages do. PHP 3 is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5.

Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP/FI 2 and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP 3 enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP 3, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is idential. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either 0 or 1, meaning FALSE or TRUE (respectively). PHP supports > (bigger than), >= (bigger than or equal to), == (equal), < (smaller than) and <= (smaller than or equal to). These expressions are most commonly used inside conditional execution, such as IF statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing

$a by 3. In PHP 3, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of

$a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator- assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of

$b by 7), etc.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

function double($i)

{

return $i*2;

}

$b = $a = 5; /* assign the value five into the variable $a and $b */

$c = $a++; /* post-increment, assign original value of $a (5) to $c

*/

$e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++); /* assign twice the value of $d before the increment, 2*6

= 12 to $f */

$g = double($++e); /* assign twice the value of $e after the increment, 2*7

= 14 to $f */

$h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24.

$h,

the value of the assignment (24) is then assigned into and $h ends with the value of 24 as well. */

In the beginning of the chapter we said that we'll be describing the various statement types, and as

promised, expressions can be statements. However, not every expression is a statement. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE (PHP doesn't have a dedicated boolean type). The truth value of expressions in PHP is calculated in a similar way to perl. Any numeric non-zero numeric value is TRUE, zero is FALSE. Be sure to note that negative values are non-zero and are thus considered TRUE! The empty string and the string "0" are FALSE; all other strings are TRUE. With non-scalar values (arrays and objects) - if the value contains no elements it's considered FALSE, otherwise it's considered TRUE.

PHP 3 provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write 'expr' to mark any valid PHP3 expression.

IF

The IF construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an IF sentence that is similar to that of C:

if (expr) statement

As described in the section about expressions, expr is evaluated to its truth value. If expr evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

The following example would display 'a is bigger than b' if $a is bigger than $b:

if ($a > $b)

print "a is bigger than b";

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an IF clause. Instead, you can group several statements into a statement group. For example, this code would display 'a is bigger than b' if $a is bigger than $b, and would then assign the value of $a into $b:

if ($a>$b) {

print "a is bigger than b";

$b = $a;

}

ELSE

If statements can be nested indefinitely within other IF statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what ELSE is for. ELSE extends an IF statement to execute a statement in case the expression in the IF statement evaluates to FALSE. For example, the following code would display 'a is bigger than b' if $a is bigger than $b, and 'a is NOT bigger than b' otherwise:

if ($a>$b) {

print "a is bigger than b";

} else {

print "a is NOT bigger than b";

}

The ELSE statement is only executed if the IF expression evaluated to FALSE, and if there were any ELSEIF expressions - only if they evaluated to FALSE as well (see below).

ELSEIF

ELSEIF, as its name suggests, is a combination of IF and ELSE. Like ELSE, it extends an IF statement to execute a different statement in case the original IF expression evaluates to FALSE. However, unlike ELSE, it will execute that alternative expression only if the ELSEIF expression evaluates to TRUE. For example, the following code would display 'a is bigger than b' if $a>$b, 'a is equal to b' if $a==$b, and 'a is smaller than b' if $a<$b:

if ($a > $b) {

print "a is bigger than b";

} elseif ($a == $b) {

print "a is equal to b";

} else {

print "a is smaller than b";

}

There may be several ELSEIFs within the same IF statement. The first ELSEIF expression (if any) that evaluates to TRUE would be executed. In PHP 3, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The ELSEIF statement is only executed if the IF expression and any previous ELSEIF expressions evaluated to FALSE, and the current ELSEIF expression evaluated to TRUE.

Alternative syntax for IF statements: IF(): ... ENDIF;

PHP 3 offers a different way to group statements within an IF statement. This is most commonly used when you nest HTML blocks inside IF statements, but can be used anywhere. Instead of using curly braces, the IF(expr) should be followed by a colon, the list of one or more statements, and end with ENDIF;. Consider the following example:

<?php if ($a==5): ?> A = 5

<?php endif; ?>

In the above example, the HTML block "A = 5" is nested within an IF statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to ELSE and ELSEIF (expr) as well. The following is an IF statement with ELSEIF and ELSE in the alternative format:

if ($a==5):

print "a equals 5"; print "...";

elseif ($a==6):

print "a equals 6"; print "!!!";

else:

print "a is neither 5 nor 6"; endif;

WHILE

WHILE loops are the simplest type of loop in PHP 3. They behave just like their C counterparts. The basic form of a WHILE statement is:

WHILE(expr) statement

The meaning of a WHILE statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the WHILE expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the WHILE expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the IF statement, you can group multiple statements within the same WHILE loop by surrounding a group of statements with curly braces, OR by using the alternate syntax:

WHILE(expr): statement ... ENDWHILE;

The following examples are identical, and both print numbers from 1 to 10:

/* example 1 */

$i=1;

while ($i<=10) {

print $i++; /* the printed value would be $i before the increment (post- increment) */

}

/* example 2 */

$i=1;

while ($i<=10): print $i;

$i++;

endwhile;

DO..WHILE

DO..WHILE loops are very similar to WHILE loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular WHILE loops is that the first iteration of a DO..WHILE loop is guarenteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular WHILE loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for DO..WHILE loops:

$i = 0; do {

print $i;

} while ($i>0);

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the DO..WHILE loop, to allow stopping execution in the middle of code blocks, by encapsulating them with DO..WHILE(0), and using the BREAK statement. The following code fragment demonstrates this:

do {

if ($i < 5) {

print "i is not big enough"; break;

}

$i *= $factor;

if ($i < $minimum_limit) { break;

}

print "i is ok";

...process i...

} while(0);

FOR

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this `feature'.

FOR loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a FOR loop is:

FOR (expr1; expr2; expr3) statement

The first expression (expr1) is evaluated (executed) unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional BREAK statement instead of using the FOR truth expression.

Consider the following examples. All of them display numbers from 1 to 10:

/* example 1 */

for ($i=1; $i<=10; $i++) { print $i;

}

/* example 2 */

for ($i = 1;;$i++) { if ($i > 10) {

break;

}

print $i;

}

/* example 3 */

$i = 1; for (;;) {

if ($i > 10) { break;

}

print $i;

$i++;

}

Of course, the first example appears to be the nicest one, but you may find that being able to use empty expressions in FOR loops comes in handy in many occasions.

There is only one format for FOR loops in PHP 3.

FOR(expr): ... ENDFOR; is NOT supported.

Other languages have a foreach statement to traverse an array or hash. PHP uses the while statement and the list and each functions for this. See the documentation for these functions for an example.

SWITCH

The SWITCH statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the SWITCH statement is for.

The following two examples are two different ways to write the same thing, one using a series of IF statements, and the other using the SWITCH statement:

/* example 1 */

if ($i == 0) {

print "i equals 0";

}

if ($i == 1) {

print "i equals 1";

}

if ($i == 2) {

print "i equals 2";

}

/* example 2 */ switch ($i) {

case 0:

print "i equals 0"; break;

case 1:

print "i equals 1"; break;

case 2:

print "i equals 2"; break;

}

It is important to understand how the SWITCH statement is executed in order to avoid messups. The SWITCH statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a CASE statement is found with a value that matches the value of the SWITCH expression, PHP begins to execute the statements. PHP continues to execute the statements until the end of the SWITCH block, or the first time it sees a BREAK statement. If you don't write a BREAK statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

/* example 3 */ switch ($i) {

case 0:

print "i equals 0"; case 1:

print "i equals 1"; case 2:

print "i equals 2";

}

Here, if $i equals to 0, PHP would execute all of the print statements! If $i equals to 1, PHP would execute the last two print statements, and only if $i equals to 2, you'd get the 'expected' behavior and only 'i equals 2' would be displayed. So, it's important not to forget BREAK statements (even though you may want to avoid supplying them on purpose under certain circumstances).

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

/* example 4 */ switch ($i) {

case 0:

print "i equals 0";

break; case 1:

print "i equals 1"; break;

case 2:

print "i equals 2"; break;

default:

print "i is not equal to 0, 1 or 2";

}

Another fact worth mentioning is that the CASE expression may be any expression that evaluates to a scalar type, that is, integer or real numbers and strings. Arrays or objects won't crash PHP, but they're meaningless in that context.

REQUIRE

The REQUIRE statement replaces itself with the specified file, much like the C preprocessor's #include works.

This means that you can't put a require() statement inside of a loop structure and expect it to include the contents of a different file on each iteration. To do that, use an INCLUDE statement.

require('header.inc');

INCLUDE

The INCLUDE statement includes the specified file.

This happens each time the INCLUDE statement is encountered, so you can use an INCLUDE statement within a looping structure to include a number of different file.

$files = array('first.inc', 'second.inc', 'third.inc'); for ($i = 0; $i < count($files); $i++) {

include($files[$i]);

}

FUNCTION

A function may be defined using syntax such as the following:

function foo( $arg_1, $arg_2, ..., $arg_n ) { echo "Example function.\n";

return $retval;

}

Any valid PHP3 code may appear inside a function, even other functions and class definitions.

Returning values

Values are returned by using the optional return statement. Any type may be returned, including lists and objects.

function my_sqrt( $num ) { return $num * $num;

}

echo my_sqrt( 4 ); // outputs '16'.

Multiple values may not be returned, but the same effect can be achieved by returning a list:

function foo() {

return array( 0, 1, 2 );

}

list( $zero, $one, $two ) = foo();

Arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of variables and/or constants.

PHP3 supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are not supported, but a similar effect may be achieved by passing arrays.

Passing by reference

By default, function arguments are passed by value. If you wish to allow a function to modify its arguments, you may pass them by reference.

If you wish a function's argument to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition:

function foo( &$bar ) {

$bar .= ' and something extra.';

}

$str = 'This is a string, '; foo2( $str );

echo $str; // outputs 'This is a string, and something extra.'

If you wish to pass a variable by reference to a function which does not do this by default, you may prepend an ampersand to the argument name in the function call:

function foo( $bar ) {

$bar .= ' and something extra.';

}

$str = 'This is a string, '; foo2( $str );

echo $str; // outputs 'This is a string, '

foo2( &$str );

echo $str; // outputs 'This is a string, and something extra.'

Default values

A function may define C++-style default values for scalar arguments as follows:

function makecoffee( $type = "cappucino" ) { echo "Making a cup of $type.\n";

}

echo makecoffee();

echo makecoffee( "espresso" );

The output from the above snippet is:

Making a cup of cappucino. Making a cup of espresso.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

function makeyogurt( $type = "acidophilus", $flavour ) { return "Making a bowl of $type $flavour.\n";

}

echo makeyogurt( "raspberry" ); // won't work as expected

The output of the above example is:

Warning: Missing argument 2 in call to makeyogurt() in

/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41 Making a bowl of raspberry .

Now, compare the above with this:

function makeyogurt( $flavour, $type = "acidophilus" ) { return "Making a bowl of $type $flavour.\n";

}

echo makeyogurt( "raspberry" ); // works as expected

The output of this example is:

Making a bowl of acidophilus raspberry.

OLD_FUNCTION

The OLD_FUNCTION statement allows you to declare a function using a syntax identical to PHP/FI2 (except you must replace 'function' with 'old_function'.

This is a deprecated feature, and should only be used by the PHP/FI2->PHP3 convertor.

Functions declared as OLD_FUNCTION cannot be called from PHP's internal code. Among other things, this means you can't use them in functions such as usort, array_walk, and register_shutdown_function. You can get around this limitation by writing a wrapper function (in normal PHP3 form) to call the OLD_FUNCTION.

CLASS

A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:

<?php

class Cart {

var $items; // Items in our shopping cart

// Add $num articles of $artnr to the cart function add_item($artnr, $num) {

$this->items[$artnr] += $num;

}

// Take $num articles of $artnr out of the cart function remove_item($artnr, $num) {

if ($this->items[$artnr] > $num) {

$this->items[$artnr] -= $num; return true;

} else {

return false;

}

}

}

?>

This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.

Classes are types, that is, they are blueprints for actual variables. You have to create a variables of the desired type with the new operator.

$cart = new Cart;

$cart->add_item("10", 1);

This creates an object $cart of the class Cart. The function add_item() of that object is being called to add 1 item of article number 10 to the cart.

Classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class and what you add in the extended defintion. This is done using the extends keyword.

class Named_Cart extends Cart { var $owner;

function set_owner($name) {

$this->owner = $name;

}

}

This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable

$owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts:

$ncart = new Named_Cart; // Create a named cart

$ncart->set_owner("kris"); // Name that cart

print $ncart->owner; // print the cart owners name

$ncart->add_item("10", 1); // (inherited functionality from cart)

Within functions of a class the variable $this means this object. You have to use $this->something to access any variable or function named something within your current object.

Constructors are functions in a class that are automatically called when you create a new instance of a class. A function becomes a constructur when it has the same name as the class.

class Auto_Cart extends Cart { function Auto_Cart() {

$this->add_item("10", 1);

}

}

This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can also take arguments and these arguments can be optional, which makes them much more useful.

class Constructor_Cart {

function Constructor_Cart($item = "10", $num = 1) {

$this->add_item($item, $num);

}

}

// Shop the same old boring stuff.

$default_cart = new Constructor_Cart;

// Shop for real...

$different_cart = new Constructor_Cart("20", 17);

Chapter 7. Expressions

Operators

Arithmetic Operators

Remember basic arithmetic from school? These work just like those.

Table 7-1. Arithmetic Operators
example name result
$a + $b Addition

Sum of $a and $b.

$a - $b Subtraction Remainder of $b subtracted from $a.
$a * $b Multiplication

Product of $a and $b.

$a / $b Division Dividend of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.

The division operator ("/") returns an integer value (the result of an integer division) if the two operands are integers (or strings that get converted to integers). If either operand is a floating-point value, floating-point division is performed.

String Operators

There is only really one string operator -- the concatenation operator (".").

$a = "Hello ";

$b = $a . "World!"; // now $b = "Hello World!"

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the the left operand gets set to the value of the expression on the rights (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

$a = 3;

$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;

$b = "Hello ";

$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

Bitwise Operators

Bitwise operators allow you to turn specific bits within an integer on or off.

Table 7-2. Bitwise Operators

example name result
$a & $b And

Bits that are set in both $a and

$b are set.

$a | $b

Or

Bits that are set in either $a or

$b are set.

~ $a Not Bits that are set in $a are not set, and vice versa.

Logical Operators

Table 7-3. Logical Operators
example name result
$a and $b And True of both $a and $b are true.
$a or $b

Or

True if either $a or $b is true.

$a xor $b Or True if either $a or $b is true, but not both.
! $a Not

True if $a is not true.

$a && $b And True of both $a and $b are true.
$a || $b Or True if either $a or $b is true.

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See below.)

Comparison Operators

Comparison operators, as their name imply, allow you to compare two values.

Table 7-4. Comparson Operators

example name result
$a == $b

Equal

True if $a is equal to $b.
example name result
$a != $b Not equal True if $a is not equal to $b.
$a < $b Less than

True if $a is strictly less than

$b.

$a > $b

Greater than

True if $a is strictly greater than

$b.

$a <= $b

Less than or equal to

True if $a is less than or equal to $b.
$a >= $b

Greater than or equal to

True if $a is greater than or equal to $b.

Precedence