PHP3 Manual

by Stig Sæther Bakken, Alexander Aulbach, Egon Schmid, Jim Winstead, Lars Torben Wilson, Rasmus Lerdorf, and Zeev Suraski

Edited by Stig Sæther Bakken

Table of Contents
Preface
About this Manual
I. Language Reference
1. An introduction to PHP3
2. PHP3 features
3. Installation
4. Configuration
5. Syntax and grammar
6. Language constructs
7. Expressions
II. Function Reference
1. Adabas D Functions
2. Array Functions
3. BC (Arbitrary Precision) Functions
4. Calendar Functions
5. Date/Time Functions
6. dBase Functions
7. dbm Functions
8. Directory Functions
9. Dynamic Loading Functions
10. Program Execution Functions
11. filePro Functions
12. Filesystem Functions
13. Functions related to HTTP
14. Image functions
15. IMAP Functions
16. PHP options & information
17. LDAP Functions
18. Mail Functions
19. Mathematical Functions
20. Miscellaneous Functions
21. mSQL Functions
22. MySQL Functions
23. Sybase Functions
24. Network Functions
25. ODBC Functions
26. Oracle functions
27. PostgreSQL functions
28. Regular expression functions
29. Solid Functions
30. SNMP Functions
31. String functions
32. URL functions
33. Variable functions
34. Gz-file Functions
III. Appendixes
A. Migrating from PHP/FI 2.0 to PHP 3.0
B. PHP development
C. The PHP Debugger

Preface

PHP Version 3.0 is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.


About this Manual

This manual is written in SGML using the DocBook DTD, using DSSSL (Document Style and Semantics Specification Language) for formatting. The tools used for formatting HTML, TeX and RTF versions are Jade, written by James Clark and The Modular DocBook Stylesheets written by Norman Walsh. PHP3's documentation framework was assembled by Stig Sæther Bakken.


I. Language Reference

Table of Contents
1. An introduction to PHP3
2. PHP3 features
3. Installation
4. Configuration
5. Syntax and grammar
6. Language constructs
7. Expressions

Chapter 1. An introduction to PHP3


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:

OracleAdabas D
SybaseFilePro
mSQL 1.x and 2.xVelocis
MySQLAll database systems with ODBC interface
SoliddBase
Generic ODBCUnix dbm
PostgreSQL 


PHP3 Concepts


Some examples


Chapter 2. PHP3 features


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(!$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 authetication 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:

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:

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

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


Supressing errors


PHP source viewer


Chapter 3. Installation

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


Installing From Source on UNIX


Downloading Source

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


Configuration

There are two ways of configuring PHP3.

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


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


--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.

NOTE: 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 [email protected]. The mailing list address is [email protected].

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.

NOTE: 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

bit valueenabled reporting
1normal errors
2normal warnings
4parser errors
8non-critical style-related warnings
The default value for this directive is 7 (normal errors, normal warnings and parser errors are shown).

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

magic_quotes_sybase boolean

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

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:


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>


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)


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:

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, the value assigned to $c is the original value of $a, which is 5 */
$e = $d = ++$b;     /* pre-increment, the value assigned into $d and $e is the incremented value of $b, which is 6 */
/* at this point, both $d and $e are equal to 6 */
$f = double($d++);  /* $f would be assigned twice the value of $d *before* the increment, 2*6 = 12 */
$g = double($++e);  /* $g would be assigned twice the value of $e *after* the increment, 2*7 = 14 */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the value of 24.
                       the value of the assignment (24) is then assigned into $h,
                       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;
}

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.


ELSE

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);

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

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.


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.


CLASS


Chapter 7. Expressions


Mathematical expressions


Operators


=


+=, -=


++, --


Overloaded operators


II. Function Reference

Table of Contents
1. Adabas D Functions
2. Array Functions
3. BC (Arbitrary Precision) Functions
4. Calendar Functions
5. Date/Time Functions
6. dBase Functions
7. dbm Functions
8. Directory Functions
9. Dynamic Loading Functions
10. Program Execution Functions
11. filePro Functions
12. Filesystem Functions
13. Functions related to HTTP
14. Image functions
15. IMAP Functions
16. PHP options & information
17. LDAP Functions
18. Mail Functions
19. Mathematical Functions
20. Miscellaneous Functions
21. mSQL Functions
22. MySQL Functions
23. Sybase Functions
24. Network Functions
25. ODBC Functions
26. Oracle functions
27. PostgreSQL functions
28. Regular expression functions
29. Solid Functions
30. SNMP Functions
31. String functions
32. URL functions
33. Variable functions
34. Gz-file Functions

Adabas D Functions

The Adabas D functions are deprecated, you probably want to use the Unified ODBC functions instead.

ada_afetch

ada_afetch -- fetch a result row into an array

Description

See odbc_fetch_into()

ada_autocommit

ada_autocommit -- toggle autocommit behaviour

Description

See odbc_autocommit().

ada_close

ada_close -- close a connection to an Adabas D server

Description

See odbc_close().

ada_commit

ada_commit -- commit a transaction

Description

See odbc_commit()

ada_connect

ada_connect -- connect to an Adabas D datasource

Description

See odbc_connect().

ada_exec

ada_exec -- prepare and execute a SQL statement

Description

See odbc_exec() or odbc_do().

ada_fetchrow

ada_fetchrow -- fetch a row from a result

Description

See odbc_fetch_row().

ada_fieldname

ada_fieldname -- get the columnname

Description

See odbc_field_name().

ada_fieldnum

ada_fieldnum -- get column number

Description

See odbc_field_num().

ada_fieldtype

ada_fieldtype -- get the datatype of a field

Description

See odbc_field_type().

ada_freeresult

ada_freeresult -- >free resources associated with a result

Description

See odbc_free_result().

ada_numfields

ada_numfields -- get the number of columns in a result

Description

See odbc_num_fields().

ada_numrows

ada_numrows -- number of rows in a result

Description

See odbc_num_rows().

ada_result

ada_result -- get data from results

Description

See odbc_result().

ada_resultall

ada_resultall -- print result as HTML table

Description

See odbc_result_all().

ada_rollback

ada_rollback -- rollback a transaction

Description

See odbc_rollback().


Array Functions

array

array -- Create an array

Description

array array(...);

Returns an array of the parameters. The parameters can be given an index with the => operator.

Note that array() really is a language construct used to represent literal arrays, and not a regular function.

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example 1. array() example

$fruits = array(
    "fruits"  => array("a"=>"orange","b"=>"banana","c"=>"apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6)
    "holes"   => array("first", 5 => "second", "third")
);

See also: list().

arsort

arsort -- Sort an array in reverse order and maintain index association

Description

void arsort(array array);

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Example 1. arsort() example

$fruits = array("d"=>"lemon","a"=>"orange","b"=>"banana","c"=>"apple");
arsort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}
This example would display: fruits[a] = orange fruits[d] = lemon fruits[b] = banana fruits[c] = apple The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

See also: asort(), rsort(), ksort(), and sort().

asort

asort -- Sort an array and maintain index association

Description

void asort(array array);

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Example 1. asort() example

$fruits = array("d"=>"lemon","a"=>"orange","b"=>"banana","c"=>"apple");
asort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}
This example would display: fruits[c] = apple fruits[b] = banana fruits[d] = lemon fruits[a] = orange The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.

See also arsort(), rsort(), ksort(), and sort().

count

count -- count elements in a variable

Description

int count(mixed var);

Returns the number of elements in var, which is typically an array (since anything else will have one element).

Returns 0 if the variable is not set.

Returns 1 if the variable is not an array.

See also: sizeof(), isset(), and is_array().

current

current -- return the current element in an array

Description

mixed current(array array);

Each array variable has an internal pointer that points to one of its elements. In addition, all of the elements in the array are linked by a bidirectional linked list for traversing purposes. The internal pointer points to the first element that was inserted to the array until you run one of the functions that modify that pointer on that array.

The current() function simply returns the array element that's currently being pointed by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list, current() returns false.

See also: end(), next(), prev() and reset().

each

each -- return next key/value pair from an array

Description

array each(array array);

Returns the current key/value pair from the array array and advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key each contain the key name of the array element, and 1 and value contain the data.

Example 1. each() examples

$foo = array( "bob", "fred", "jussi", "jouni" );
$bar = each( $foo );
      

$bar now contains the following key/value pairs:

  • 0 => 0

  • 1 => 'bob'

  • key => 0

  • value => 'bob'

$foo = array( "Robert", => "Bob", "Seppo" => "Sepi" );
$bar = each( $foo );
       

$bar now contains the following key/value pairs:

  • 0 => 'Robert'

  • 1 => 'Bob'

  • key => 'Robert'

  • value => 'Bob'

each() is typically used in conjunction with list() to traverse an array; for instance, $HTTP_POST_VARS:

Example 2. Traversing $HTTP_POST_VARS with each()

echo "Values submitted via POST method:<br>";
while ( list( $key, $val ) = each( $HTTP_POST_VARS ) ) {
   echo "$key => $val<br>";
}
      

See also key(), current(), reset(), next(), and prev().

end

end -- set internal pointer of array to last element

Description

end(array array);

end() advances array's internal pointer to the last element.

See also: current(), end() next() and reset()

key

key -- fetch a key from an associative array

Description

mixed prev(array array);

key() returns the index element of the current array position.

See also: current() next()

ksort

ksort -- Sort an array by key.

Description

int ksort(array array);

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Example 1. ksort() example

$fruits = array("d"=>"lemon","a"=>"orange","b"=>"banana","c"=>"apple");
ksort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}
This example would display: fruits[a] = orange fruits[b] = banana fruits[c] = apple fruits[d] = lemon

See also asort(), arsort(), sort(), and rsort().

list

list -- assign variables as if they were an array

Description

void list(...);

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Example 1. list() example

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>
<?php

$result = mysql($conn, "SELECT id, name, salary FROM employees");
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    print(" <tr>\n".
          "  <td><a href=\"info.php3?id=$id\">$name</a></td>\n".
          "  <td>$salary</td>\n".
          " </tr>\n");
}

?></table>

See also: array().

next

next -- advance the internal array pointer

Description

mixed next(array array);

Returns the array element in the next place that's pointed by the internal array pointer, or false if there are no more elements.

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element. That means it returns the next array element and advances the internal array pointer by one. If advancing the internal array pointer results in going beyond the end of the element list, next() returns false.

See also: current(), end() prev() and reset()

pos

pos -- return the current element in an array

Description

mixed pos(array array);

This is an alias for current().

See also: end(), next(), prev() and reset().

prev

prev -- rewind internal array pointer

Description

mixed prev(array array);

Returns the array element in the previous place that's pointed by the internal array pointer, or false if there are no more elements.

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.

See also: current(), end() next() and reset()

reset

reset -- set internal pointer of array to first element

Description

reset(array array);

reset() rewinds array's internal pointer to the first element.

See also: current(), next() prev() and reset()

rsort

rsort -- Sort an array in reverse order

Description

void rsort(array array);

This function sorts an array in reverse order (highest to lowest).

Example 1. rsort() example

    $fruits = array("lemon","orange","banana","apple");
    rsort($fruits);
    for(reset($fruits); $key = key($fruits); next($fruits)) {
        echo "fruits[$key] = ".$fruits[$key]."\n";
    }
	
This example would display: fruits[0] = orange fruits[1] = lemon fruits[2] = banana fruits[3] = apple The fruits have been sorted in reverse alphabetical order.

See also arsort(), asort(), ksort(), and sort().

sizeof

sizeof -- get size of array

Description

int sizeof(array array);

Returns the number of elements in the array.

See also: count()

sort

sort -- Sort an array

Description

void sort(array array);

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

Example 1. sort() example

$fruits = array("lemon","orange","banana","apple");
sort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}
This example would display: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange The fruits have been sorted in alphabetical order.

See also arsort(), asort(), ksort(), and rsort().


BC (Arbitrary Precision) Functions

These BC functions are only available if PHP was compiled with the --enable-bcmath configure option.

bcadd

bcadd -- Add two arbitrary precision numbers.

Description

string bcadd(string left operand, string right operand, int scale);

Adds the left operand to the right operand and returns the sum in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

See also bcsub().

bccomp

bccomp -- Compare two arbitrary precision numbers.

Description

int bccomp(string left operand, string right operand, int scale);

Compares the left operand to the right operand and returns the result as an integer. The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparion. The return value is 0 if the two operands are equal. If the left operand is larger than the right operand the return value is +1 and if the left operand is less than the right operand the return value is -1.

bcdiv

bcdiv -- Divide two arbitrary precision numbers.

Description

string bcdiv(string left operand, string right operand, int scale);

Divides the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.

See also bcmul().

bcmod

bcmod -- Get modulus of an arbitrary precision number.

Description

string bcmod(string left operand, string modulus, int scale);

Get the modulus of the left operand using modulus. The scale parameter sets the number of digits after the decimal place in the result.

See also bcdiv().

bcmul

bcmul -- Multiply two arbitrary precision number.

Description

string bcmul(string left operand, string right operand, int scale);

Multiply the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.

See also bcdiv().

bcpow

bcpow -- Raise an arbitrary precision number to another.

Description

string bcpow(string x, string y, int scale);

Raise x to the power y. The scale can be used to set the number of digits after the decimal place in the result.

See also bcsqrt().

bcscale

bcscale -- Set default scale parameter for all bc math functions.

Description

string bcscale(int scale);

This function sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.

bcsqrt

bcsqrt -- Get the square root of an arbitray precision number.

Description

string bcsqrt(string operand, int scale);

Return the square root of the operand. The optional scale parameter sets the number of digits after the decimal place in the result.

See also bcpow().

bcsub

bcsub -- Subtract one arbitrary precision number from another.

Description

string bcsub(string left operand, string right operand, int scale);

Subtracts the right operand from the left operand and returns the result in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

See also bcadd().


Calendar Functions

The Calendar extension in PHP presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting way earlier than any date most people would need to track (somewhere around 4000bc). To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on calendar systems visit http://genealogy.org/~scottlee/cal-overview.html. Excerpts from this page are included in these instructions, and are in quotes

JDToGregorian

JDToGregorian -- Converts Julian Day Count to Gregorian date

Description

string jdtogregorian(int julianday);

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year"

GregorianToJD

GregorianToJD -- Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd(int month, int day, int year);

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this software can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Example 1. Calendar functions

<?php
$jd = GregorianToJD(10,11,1970);
echo("$jd\n");
$gregorian = JDToGregorian($jd);
echo("$gregorian\n");
?>

JDToJulian

JDToJulian -- Converts a Julian Calendar date to Julian Day Count

Description

string jdtojulian(int julianday);

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

JulianToJD

JulianToJD -- Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd(int month, int day, int year);

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this software can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

JDToJewish

JDToJewish -- Converts a Julian Day Count to the Jewish Calendar

Description

string jdtojewish(int julianday);

Converts a Julian Day Count the the Jewish Calendar.

JewishToJD

JewishToJD -- Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd(int month, int day, int year);

Valid Range Although this software can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful.

The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

JDToFrench

JDToFrench -- Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench(int month, int day, int year);

Converts a Julian Day Count to the French Republican Calendar.

FrenchToJD

FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd(int month, int day, int year);

Converts a date from the French Republican Calendar to a Julian Day Count

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

JDMonthName

JDMonthName -- Returns a month name

Description

string jdmonthname(int julianday, int mode);

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

Table 1. Calendar modes

ModeMeaning
0Gregorian - apreviated
1Gregorian
2Julian - apreviated
3Julian
4Jewish
5French Republican

JDDayOfWeek

JDDayOfWeek -- Returns the day of the week

Description

mixed jddayofweek(int julianday, int mode);

Returns the day of the week. Can return a string or an int depending on the mode.

Table 1. Calendar week modes

ModeMeaning
0returns the day number as an int (0=sunday, 1=monday, etc)
1returns string containing the day of week (english-gregorian)
2returns a string containing the abreviated day of week (english-gregorian)


Date/Time Functions

checkdate

checkdate -- validate a date/time

Description

int checkdate(int month, int day, int year);

Returns true if the date given is valid; otherwise returns false. Checks the validity of the date formed by the arguments. A date is considered valid if:

date

date -- format a local time/date

Description

string date(string format, int timestamp);

Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given.

The following characters are recognized in the format string:

Unrecognized characters in the format string will be printed as-is.

Example 1. date() example

print(date( "l dS of F Y h:i:s A" ));
print("July 1, 2000 is on a " . date("l", mktime(0,0,0,7,1,2000)));
See also gmdate() and mktime().

getdate

getdate -- get date/time information

Description

array getdate(int timestamp);

Returns an associative array containing the date information of the timestamp as the following array elements:

gmdate

gmdate -- format a GMT/CUT date/time

Description

string gmdate(string format, int timestamp);

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT). For example, when run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".

Example 1. gmdate() example

echo date( "M d Y H:i:s",mktime(0,0,0,1,1,1998) );
echo gmdate( "M d Y H:i:s",mktime(0,0,0,1,1,1998) );

See also date(), mktime() and gmmktime().

mktime

mktime -- get UNIX timestamp for a date

Description

int mktime(int hour, int minute, int second, int month, int day, int year);

Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970) and the time specified.

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

MkTime is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998".

Example 1. mktime() example

echo date( "M-d-Y", mktime(0,0,0,12,32,1997) );
echo date( "M-d-Y", mktime(0,0,0,13,1,1997) );
echo date( "M-d-Y", mktime(0,0,0,1,1,1998) );

See also date() and time().

gmmktime

gmmktime -- get UNIX timestamp for a GMT date

Description

int gmmktime(int hour, int minute, int second, int month, int day, int year);

Identical to mktime() except the passed parameters represents a GMT date.

time

time -- return current UNIX timestamp

Description

int time(void);

Returns the current time measured in the number of seconds since the Unix Epoch (January 1, 1970).

See also date().

microtime

microtime -- return current UNIX timestamp with microseconds

Description

string microtime(void);

Returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. This function is only available on operating systems that support the gettimeofday() system call.

See also time().

set_time_limit

set_time_limit -- limit execution time

Description

void set_time_limit(int seconds);

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in php3.ini. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit( 20 ) is made, the script will run for a total of 45 seconds before timing out.


dBase Functions

These functions allow you to access records stored in dBase-format (dbf) databases.

There is no support for indexes or memo fields.

dbase_create

dbase_create -- creates a dBase database

Description

int dbase_create(string filename, array fields);

The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.

The types of fields available are:

L

Boolean. These do not have a length or precision.

M

Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.

D

Date (stored as YYYYMMDD). These do not have a length or precision.

N

Number. These have both a length and a precision (the number of digits after the decimal point).

C

String.

If the database is successfully created, a dbase_identifier is returned, otherwise false is returned.

dbase_open

dbase_open -- opens a dBase database

Description

int dbase_open(string filename, int flags);

The flags correspond to those for the open() system call. (Typically 0 means read-only, 1 means write-only, and 2 means read and write.)

Returns a dbase_identifier for the opened database, or false if the database couldn't be opened.

dbase_close

dbase_close -- close a dBase database

Description

bool dbase_close(int dbase_identifier);

Closes the database associated with dbase_identifier.

dbase_pack

dbase_pack -- packs a dBase database

Description

bool dbase_pack(int dbase_identifier);

Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record().

dbase_add_record

dbase_add_record -- add a record to a dBase database

Description

bool dbase_add_record(int dbase_identifier, array record);

Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and false will be returned.

dbase_delete_record

dbase_delete_record -- deletes a record from a dBase database

Description

bool dbase_delete_record(int dbase_identifier, int record);

Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().

dbase_get_record

dbase_get_record -- gets a record from a dBase database

Description

array dbase_get_record(int dbase_identifier, int record);

Returns the data from record in an array. The array is indexed starting at 0, and includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record().

Each field is converted to the appropriate PHP type. (Dates are left as strings.)

dbase_numfields

dbase_numfields -- find out how many fields are in a dBase database

Description

int dbase_numfields(int dbase_identifier);

Returns the number of fields (columns) in the specified database.

dbase_numrecords

dbase_numrecords -- find out how many records are in a dBase database

Description

int dbase_numrecords(int dbase_identifier);

Returns the number of records (rows) in the specified database.


dbm Functions

These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley db, gdbm, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).

dbmopen

dbmopen -- opens a dbm database

Description

int dbmopen(string filename, int flags);

The first argument is the full-path filename of the dbm file to be opened and the second is the file open mode which is one of "r", "n" or "w" for read, new (implies write) and write respectively.

Returns an identifer to be passed to the other dbm functions on success, or false on failure.

If ndbm support is used, ndbm will actually create filename.dir and filename.pag files. gdbm only uses one file, as does the internal flat-file support, and Berkeley db creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the dbm library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on dbm files, see your Unix man pages, or obtain GNU's gdbm from ftp://prep.ai.mit.edu/pub/gnu.

dbmclose

dbmclose -- closes a dbm database

Description

bool dbmclose(int dbm_identifier);

Unlocks and closes the specified database.

dbmexists

dbmexists -- tells if a value exists for a key in a dbm database

Description

bool dbmexists(int dbm_identifier, string key);

Returns true if there is a value associated with the key.

dbmfetch

dbmfetch -- fetches a value for a key from a dbm database

Description

string dbmfetch(int dbm_identifier, string key);

Returns the value associated with key.

dbminsert

dbminsert -- inserts a value for a key in a dbm database

Description

int dbminsert(int dbm_identifier, string key, string value);

Adds the value to the database with the specified key.

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

dbmreplace

dbmreplace -- replaces the value for a key in a dbm database

Description

bool dbmreplace(int dbm_identifier, string key, string value);

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

dbmdelete

dbmdelete -- deletes the value for a key from a dbm database

Description

bool dbmdelete(int dbm_identifier, string key);

Deletes the value for key in the database.

Returns false if the key didn't exist in the database.

dbmfirstkey

dbmfirstkey -- retrieves the first key from a dbm database

Description

string dbmfirstkey(int dbm_identifier);

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

dbmnextkey

dbmnextkey -- retrieves the next key from a dbm database

Description

string dbmnextkey(int dbm_identifier, string key);

Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

Example 1. Visiting every key/value pair in a dbm database.

$key = dbmfirstkey($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch($dbm_id, $key) . "\n";
    $key = dbmnextkey($dbm_id, $key);
}
     

dblist

dblist -- describes the dbm-compatible library being used

Description

string dblist(void);

Directory Functions

chdir

chdir -- change directory

Description

int chdir(string directory);

Changes PHP's current directory to directory. Returns FALSE if unable to change directory, TRUE otherwise.

dir

dir -- directory class

Description

new dir(string directory);

A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.

Example 1. Dir() Example

$d = dir("/etc");
echo "Handle: ".$d->handle."<br>\n";
echo "Path: ".$d->path."<br>\n";
while($entry=$d->read()) {
    echo $entry."<br>\n";
}
$d->close();
	

closedir

closedir -- close directory handle

Description

void closedir(int dir_handle);

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

opendir

opendir -- open directory handle

Description

int opendir(string path);

Returns a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

readdir

readdir -- read entry from directory handle

Description

string readdir(int dir_handle);

Returns the filename of the next file from the directory. The filenames are not returned in any particular order.

rewinddir

rewinddir -- rewind directory handle

Description

void rewinddir(int dir_handle);

Resets the directory stream indicated by dir_handle to the beginning of the directory.


Dynamic Loading Functions

dl

dl -- load a PHP extension at runtime

Description

int dl(string library);

Loads the PHP extension defined in library. See also the extension_dir configuration directive.


Program Execution Functions

escapeshellcmd

escapeshellcmd -- escape shell metacharacters

Description

string escapeshellcmd(string command);

EscapeShellCmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions. A standard use would be:

system(EscapeShellCmd($cmd))
      

exec

exec -- Execute an external program

Description

string exec(string command, string array, int return_var);

Exec executes the given command, however it does not output anything. It simply returns the last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the PassThru() function.

If the array argument is present, then the specified array will be filled with every line of output from the command. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

If the return_var argument is present along with the array argument, then the return status of the executed command will be written to this variable.

Note that if you are going to allow data coming from user input to be passed to this function, then you should be using EscapeShellCmd() to make sure that users cannot trick the system into executing arbitrary commands.

See also system(), PassThru(), popen() and EscapeShellCmd().

system

system -- Execute an external program and display output

Description

string system(string command, int return_var);

System() is just like the C version of the function in that it executes the given command and outputs the result. If a variable is provided as the second argument, then the return status code of the executed command will be written to this variable.

Note, that if you are going to allow data coming from user input to be passed to this function, then you should be using the EscapeShellCmd() function to make sure that users cannot trick the system into executing arbitrary commands.

The System() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the PassThru() function. See also the exec() and popen() functions.

passthru

passthru -- Execute an external program and display raw output

Description

string passthru(string command, int return_var);

The PassThru() function is similar to the Exec() function in that it executes a command. If the return_var argument is present, the return status of the Unix command will be placed here. This function should be used in place of Exec() or System() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

See also exec() and fpassthru().

virtual

virtual -- Perform an Apache sub-request

Description

int virtual(string filename);

virtual() is an Apache-specific function which is equivalent to <!--#include virtual...--> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-type header. For PHP files, you should use include() or require().


filePro Functions

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark by Fiserv, Inc. You can find more information about filePro at http://www.fileproplus.com/.

filepro

filepro -- read and verify the map file

Description

bool filepro(string directory);

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

filepro_fieldname

filepro_fieldname -- gets the name of a field

Description

string filepro_fieldname(int field_number);

Returns the name of the field corresponding to field_number.

filepro_fieldtype

filepro_fieldtype -- gets the type of a field

Description

string filepro_fieldtype(int field_number);

Returns the edit type of the field corresponding to field_number.

filepro_fieldwidth

filepro_fieldwidth -- gets the width of a field

Description

int filepro_fieldwidth(int field_number);

Returns the width of the field corresponding to field_number.

filepro_retrieve

filepro_retrieve -- retrieves data from a filePro database

Description

string filepro_retrieve(int row_number, int field_number);

Returns the data from the specified location in the database.

filepro_fieldcount

filepro_fieldcount -- find out how many fields are in a filePro database

Description

int filepro_fieldcount(void);

Returns the number of fields (columns) in the opened filePro database.

See also filepro().

filepro_rowcount

filepro_rowcount -- find out how many rows are in a filePro database

Description

int filepro_rowcount(void);

Returns the number of rows in the opened filePro database.

See also filepro().


Filesystem Functions

basename

basename -- return file name part of path

Description

string basename(string path);

Given a string containing a path to a file, this function will return the base name of the file.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

Example 1. basename() example

$path = "/home/httpd/html/index.php3";
$file = basename($path); // $file is set to "index.php3"

See also: dirname()

chgrp

chgrp -- change file group

Description

int chgrp(string filename, mixed group);

Attempts to change the group of the file filename to group. Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Returns true on success; otherwise returns false.

On Windows, does nothing and returns true.

See also chown() and chmod().

chmod

chmod -- change file mode

Description

int chmod(string filename, int mode);

Attempts to change the mode of the file specified by filename to that given in mode.

Note that mode is not automatically assumed to be an octal value. To ensure the expected operation, you need to prefix mode with a zero (0):

chmod( "/somedir/somefile", 755 );   // decimal; probably incorrect       
chmod( "/somedir/somefile", 0755 );  // octal; correct value of mode
      

Returns true on success and false otherwise.

See also chown() and chgrp().

chown

chown -- change file owner

Description

int chown(string filename, mixed user);

Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Returns true on success; otherwise returns false.

NOTE: On Windows, does nothing and returns true.

See also chown() and chmod().

clearstatcache

clearstatcache -- clear file stat cache

Description

void clearstatcache(void);

Invoking the stat() system call on most systems is quite expensive. Therefore, the result of the last call to any of the status functions (listed below) is stored for use on the next such call using the same filename. If you wish to force a new status check, for instance if the file is being checked many times and may change or disappear, use this function to clear the results of the last call from memory.

Affected functions include stat(), file_exists(), filectime(), fileatime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

copy

copy -- copy file

Description

int copy(string source, string dest);

Makes a copy of a file. Returns true if the copy succeeded, false otherwise.

Example 1. copy() example

if (!copy($file, $file.'.bak')) {
    print("failed to copy $file...<br>\n");
}

See also: rename()

dirname

dirname -- return file name part of path

Description

string dirname(string path);

Given a string containing a path to a file, this function will return the name of the directory.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

Example 1. dirname() example

$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"

See also: basename()

fclose

fclose -- close an open file pointer

Description

int fclose(int fp);

The file pointed to by fp is closed.

Returns true on success and false on failure.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

feof

feof -- test for end-of-file on a file pointer

Description

int feof(int fp);

Returns true if the file pointer is at EOF or an error occurs; otherwise returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

fgetc

fgetc -- get character from file pointer

Description

string fgetc(int fp);

Returns a string containing a single character read from the file pointed to by fp. Returns FALSE on EOF (as does feof()).

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

See also fopen(), popen(), fsockopen(), and fgets().

fgets

fgets -- get line from file pointer

Description

string fgets(int fp, int length);

Returns a string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

If an error occurs, returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

See also fopen(), popen(), fgetc(), and fsockopen().

fgetss

fgetss -- get line from file pointer and strip HTML tags

Description

string fgetss(int fp, int length);

Identical to fgets(), except that fgetss attempts to strip any HTML and PHP tags from the text it reads.

See also fgets(), fopen(), fsockopen(), and popen().

file

file -- read entire file into an array

Description

array file(string filename);

Identical to readfile(), except that file() returns the file in an array.

See also readfile(), fopen(), and popen().

file_exists

file_exists -- Check whether a file exists.

Description

int file_exists(string filename);

Returns true if the file specified by filename exists; false otherwise.

See also clearstatcache().

fileatime

fileatime -- get last access time of file

Description

int fileatime(string filename);

Returns the time the file was last accessed, or false in case of an error.

filectime

filectime -- get inode modification time of file

Description

int filectime(string filename);

Returns the time the file was last changed, or false in case of an error.

filegroup

filegroup -- get file group

Description

int filegroup(string filename);

Returns the group ID of the owner of the file, or false in case of an error.

fileinode

fileinode -- get file inode

Description

int fileinode(string filename);

Returns the inode number of the file, or false in case of an error.

filemtime

filemtime -- get file modification time

Description

int filemtime(string filename);

Returns the time the file was last modified, or false in case of an error.

fileowner

fileowner -- get file owner

Description

int fileowner(string filename);

Returns the user ID of the owner of the file, or false in case of an error.

fileperms

fileperms -- get file permissions

Description

int fileperms(string filename);

Returns the permissions on the file, or false in case of an error.

filesize

filesize -- get file size

Description

int filesize(string filename);

Returns the size of the file, or false in case of an error.

filetype

filetype -- get file type

Description

string filetype(string filename);

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, and unknown.

Returns false if an error occurs.

fileumask

fileumask -- get file umask

Description

int fileumask(int umask);

Sets the umask to umask & 0777.

Returns the old umask.

fopen

fopen -- open file or URL

Description

int fopen(string filename, string mode);

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and a file pointer is returned to the beginning of the text of the response.

Does not handle HTTP redirects, so you must include trailing slashes on directories.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and a pointer to the requested file is returned. If the server does not support passive mode ftp, this will fail.

If filename begins with anything else, the file will be opened from the filesystem, and a file pointer to the file opened is returned.

If the open fails, the function returns false.

Example 1. fopen() example

$fp = fopen( "/home/rasmus/file.txt", "r" );
$fp = fopen( "http://www.php.net/", "r" );

See also fclose(), fsockopen(), and popen().

fpassthru

fpassthru -- output all remaining data on a file pointer

Description

int fpassthru(int fp);

Reads to EOF on the given file pointer and writes the results to standard output.

If an error occurs, fpassthru() returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

The file is closed when fpassthru() is done reading it (leaving fp useless).

fputs

fputs -- write to a file pointer

Description

int fputs(int fp, string str, int length);

fputs() is an alias to fwrite(), and is identical in every way.

fread

fread -- Binary-safe file read

Description

string fread(int fp, int length);

fread() reads up to length bytes from the file pointer referenced by fp. Reading stops when length bytes have been read or EOF is reached, whichever comes first.

// get contents of a file into a string
$filename = "/usr/local/something.txt";
$fd = fopen( $filename, "r" );
$contents = fread( $fd, filesize( $filename ) );
fclose( $fd );
      

See also fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), file(), and fpassthru().

fseek

fseek -- seek on a file pointer

Description

int fseek(int fp, int offset);

Sets the file position indicator for the file referenced by fp to offset bytes into the file stream. Equivalent to calling (in C) fseek( fp, offset, SEEK_SET ).

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.

See also ftell() and rewind().

ftell

ftell -- tell file pointer read/write position

Description

int ftell(int fp);

Returns the position of the file pointer referenced by fp; i.e., its offset into the file stream.

If an error occurs, returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen().

See also fopen(), popen(), fseek() and rewind().

fwrite

fwrite -- Binary-safe file write

Description

int fwrite(int fp, string string, int length);

fwrite() writes the contents of string to the file stream pointed to by fp. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

See also fread(), fopen(), fsockopen(), popen(), and fputs().

is_dir

is_dir -- tells whether the filename is a directory

Description

bool is_dir(string filename);

Returns true if the filename exists and is a directory.

See also is_file() and is_link().

is_executable

is_executable -- tells whether the filename is executable

Description

bool is_executable(string filename);

Returns true if the filename exists and is executable.

See also is_file() and is_link().

is_file

is_file -- tells whether the filename is a regular file

Description

bool is_file(string filename);

Returns true if the filename exists and is a regular file.

See also is_dir() and is_link().

is_link

is_link -- tells whether the filename is a symbolic link

Description

bool is_link(string filename);

Returns true if the filename exists and is a symbolic link.

See also is_dir() and is_file().

is_readable

is_readable -- tells whether the filename is readable

Description

bool is_readable(string filename);

Returns true if the filename exists and is readable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

See also is_writeable().

is_writeable

is_writeable -- tells whether the filename is writeable

Description

bool is_readable(string filename);

Returns true if the filename exists and is writeable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

See also is_readable().

link

link -- Create a hard link

Description

int link(string target, string link);

Link() creates a hard link.

See also the symlink() to create soft links, and readlink() along with linkinfo().

linkinfo

linkinfo -- Get information about a link

Description

int linkinfo(string path);

Linkinfo() returns the st_dev field of the UNIX C stat structure returned by the lstat system call. This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). Returns 0 or FALSE in case of error.

See also symlink(), link(), and readlink().

mkdir

mkdir -- make directory

Description

int mkdir(string pathname, int mode);

Attempts to create the directory specified by pathname.

Returns true on success and false on failure.

See also rmdir().

pclose

pclose -- close process file pointer

Description

int pclose(int fp);

Closes a file pointer to a pipe opened by popen().

The file pointer must be valid, and must have been returned by a successful call to popen().

Returns the termination status of the process that was run.

See also popen().

popen

popen -- open process file pointer

Description

int popen(string command, string mode);

Opens a pipe to a process executed by forking the command given by command.

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fputs().

If an error occurs, returns false.

       $fp = popen( "/bin/ls", "r" );
      

See also pclose().

readfile

readfile -- output a file

Description

int readfile(string filename);

Reads a file and writes it to standard output.

Returns the number of bytes read from the file. If an error occurs, false is returned and unless the function was called as @readfile, an error message is printed.

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and the text of the response is written to standard output.

Does not handle HTTP redirects, so you must include trailing slashes on directories.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and the requested file is written to standard output. If the server does not support passive mode ftp, this will fail.

If filename begins with neither of these strings, the file will be opened from the filesystem and its contents written to standard output.

See also fpassthru(), file(), and fopen().

readlink

readlink -- Return the target of a symbolic link

Description

int readlink(string path);

Readlink() does the same as the readlink C function and returns the contents of the symbolic link path or 0 in case of error.

See also symlink(), readlink() and linkinfo().

rename

rename -- rename a file

Description

int rename(string oldname, string newname);

Attempts to rename oldname to newname.

Returns true on success and false on failure.

rewind

rewind -- rewind the position of a file pointer

Description

int rewind(int fp);

Sets the file position indicator for fp to the beginning of the file stream.

If an error occurs, returns 0.

The file pointer must be valid, and must point to a file successfully opened by fopen().

See also fseek() and ftell().

rmdir

rmdir -- remove directory

Description

int rmdir(string dirname);

Attempts to remove the directory named by pathname. The directory must be empty, and the relevant permissions must permit this.

If an error occurs, returns 0.

See also mkdir().

stat

stat -- give information about a file

Description

array stat(string filename);

Gathers the statistics of the file named by filename.

Returns an array with the statistics of the file with the following elements:

  1. device

  2. inode

  3. number of links

  4. user id of owner

  5. group id owner

  6. device type if inode device *

  7. size in bytes

  8. time of last access

  9. time of last modification

  10. time of last change

  11. blocksize for filesystem I/O *

  12. number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1

symlink

symlink -- Create a symbolic link

Description

int symlink(string target, string link);

Symlink() creates a symbolic link.

See also link() to create hard links, and readlink() along with linkinfo().

tempnam

tempnam -- create unique file name

Description

string tempnam(string dir, string prefix);

Creates a unique temporary filename.

Returns the new temporary filename, or the null string on failure.

Example 1. tempnam() example

$tmpfname = tempnam( "/tmp", "FOO" );

touch

touch -- set modification time of file

Description

int touch(string filename, int time);

Attempts to set the modification time of the file named by filename to the value given by time. If the option time is not given, uses the present time.

If the file does not exist, it is created.

Returns true on success and false otherwise.

umask

umask -- changes the current umask

Description

int umask(int mask);

Umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

Umask() without arguments simply returns the current umask.

unlink

unlink -- Delete a file

Description

int unlink(string filename);

Deletes filename. Similar to the Unix C unlink() function.

Returns 0 or FALSE on an error.

See also rmdir() for removing directories.


Functions related to HTTP

These functions let you manipulate the output sent back to the remote browser right down to the HTTP protocol level.

getallheaders

getallheaders -- Fetch all HTTP request headers

Description

array getallheaders(void);

This function returns an associative array of all the HTTP headers in the current request.

Example 1. GetAllHeaders() Example

$headers = getallheaders();
while (list($header, $value) = each($headers)) {
    echo "$header: $value<br>\n";
}
This example will display all the request headers for the current request.

NOTE: GetAllHeaders() is currently only supported when PHP runs as an Apache module.

header

header -- Send a raw HTTP header

Description

int header(string string);

The Header() function is used at the top of an HTML file to send raw HTTP header strings. See the HTTP 1.1 Specification for more information on raw http headers. Remember that the Header() function must be called before any actual output is sent either by normal HTML tags or from PHP.

Header("Location: http://www.php.net");  /* Redirect browser to PHP web site */

setcookie

setcookie -- Send a cookie

Description

int setcookie(string name, string value, int expire, string path, string domain, int secure);

SetCookie() defines a cookie to be sent along with the rest of the header information. All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string ("") in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection. Some examples follow:

Example 1. SetCookie examples

SetCookie("TestCookie","Test Value");
SetCookie("TestCookie",$value,time()+3600);  /* expire in 1 hour */
SetCookie("TestCookie",$value,time()+3600,"/~rasmus/",".utoronto.ca",1);

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. ie. to see the contents of our test cookie in a script, simply do:

echo $TestCookie;

For more information on cookies, see Netscape's cookie specification at http://www.netscape.com/newsref/std/cookie_spec.html.


Image functions

You can use the image functions in PHP to get the size of JPEG, GIF, and PNG images, and if you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate GIF images.

GetImageSize

GetImageSize -- get the size of a GIF, JPG or PNG image

Description

array getimagesize(string filename);

The GetImageSize() function will determine the size of any GIF, JPG or PNG image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag.

Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 a flag indicating the type of the image. 1 = GIF, 2 = JPG, 3 = PNG. Index 3 is a text string with the correct "height=xxx width=xxx" string that can be used directly in an IMG tag.

Example 1. GetImageSize

<?php $size = GetImageSize("img/flag.jpg"); ?>
<IMG SRC="img/flag.jpg" <?php echo $size[3]; ?>>

NOTE: This function does not require the GD image library.

ImageArc

ImageArc -- draw a partial ellipse

Description

int imagearc(int im, int cx, int cy, int w, int h, int s, int e, int col);

ImageArc draws a partial ellipse centered at cx, cy (top left is 0,0) in the image represented by im. w and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments.

ImageChar

ImageChar -- draw a character horizontally

Description

int imagechar(int im, int font, int x, int y, string c, int col);

ImageChar draws the first character of c in the image identified by id at coordinates x, y (top left is 0,0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

ImageCharUp

ImageCharUp -- draw a character vertically

Description

int imagecharup(int im, int font, int x, int y, string c, int col);

ImageCharUp draws the character c vertically in the image identified by im at coordinates x, y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

ImageColorAllocate

ImageColorAllocate -- allocate a color for an image

Description

int imagecolorallocate(int im, int red, int green, int blue);

ImageColorAllocate returns a color identifier representing the color composed of the given RGB components. The im argument is the return from the imagecreate() function. ImageColorAllocate must be called to create each color that is to be used in the image represented by im.

ImageColorTransparent

ImageColorTransparent -- define a color as transparent

Description

int imagecolortransparent(int im, int col);

ImageColorTransparent sets the transparent color in the im image to col. im is the image identifier returned by imagecreate() and col is the color identifier returned by imagecolorallocate().

ImageCopyResized

ImageCopyResized -- copy and resize part of an image

Description

int imagecopyresized(int dst_im, int src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH);

ImageCopyResized copies a rectangular portion of one image to another image. dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

ImageCreate

ImageCreate -- create a new image

Description

int imagecreate(int x_size, int y_size);

ImageCreate returns an image identifier representing a blank image of size x_size by y_size.

ImageCreateFromGif

ImageCreateFromGif -- create a new image from file or URL

Description

int imagecreatefromgif(string filename);

ImageCreateFromGif returns an image identifier representing the image obtained from the given filename.

ImageDashedLine

ImageDashedLine -- draw a dashed line

Description

int imagedashedline(int im, int x1, int y1, int x2, int y2, int col);

ImageLine draws a dashed line from x1,y1 to x2,y2 (top left is 0,0) in image im of color col.

See also imageline().

ImageDestroy

ImageDestroy -- destroy an image

Description

int imagedestroy(int im);

ImageDestroy frees any memory associated with image im. im is the image identifier returned by the imagecreate() function.

ImageFill

ImageFill -- flood fill

Description

int imagefill(int im, int x, int y, int col);

ImageFill performs a flood fill starting at coordinate x, y (top left is 0,0) with color col in the image im.

ImageFilledPolygon

ImageFilledPolygon -- draw a filled polygon

Description

int imagefilledpolygon(int im, array points, int num_points, int col);

ImageFilledPolygon creates a filled polygon in image im. points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of vertices.

ImageFilledRectangle

ImageFilledRectangle -- draw a filled rectangle

Description

int imagefilledrectangle(int im, int x1, int y1, int x2, int y2, int col);

ImageFilledRectangle creates a filled rectangle of color col in image im starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.

ImageFillToBorder

ImageFillToBorder -- flood fill to specific color

Description

int imagefilltoborder(int im, int x, int y, int border, int col);

ImageFillToBorder performs a flood fill whose border color is defined by border. The starting point for the fill is x,y (top left is 0,0) and the region is filled with color col.

ImageFontHeight

ImageFontHeight -- get font height

Description

int imagefontheight(int font);

Returns the pixel width of a character in font.

See also imagefontwidth() and imageloadfont().

ImageFontWidth

ImageFontWidth -- get font width

Description

int imagefontwidth(int font);

Returns the pixel width of a character in font.

See also imagefontheight() and imageloadfont().

ImageGif

ImageGif -- output image to browser or file

Description

int imagegif(int im, string filename);

ImageGif creates the GIF file in filename from the image im. The im argument is the return from the imagecreate() function.

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using the header function, you can create a PHP script that outputs GIF images directly.

ImageInterlace

ImageInterlace -- enable or disable interlace

Description

int imageinterlace(int im, int interlace);

ImageInterlace turns the interlace bit on or off. If interlace is 1 the im image will be interlaced, and if interlace is 0 the interlace bit is turned off.

ImageLine

ImageLine -- draw a line

Description

int imageline(int im, int x1, int y1, int x2, int y2, int col);

ImageLine draws a line from x1,y1 to x2,y2 (top left is 0,0) in image im of color col.

See also imagecreate() and imagecolorallocate().

ImageLoadFont

ImageLoadFont -- load a new font

Description

int imageloadfont(string file);

ImageLoadFont loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts).

The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.

Table 1. Font file format

byte positionC data typedescription
byte 0-3intnumber of characters in the font
byte 4-7int value of first character in the font (often 32 for space)
byte 8-11intpixel width of each character
byte 12-15intpixel height of each character
byte 16-char array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

See also ImageFontWidth() and ImageFontHeight().

ImagePolygon

ImagePolygon -- draw a polygon

Description

int imagepolygon(int im, int points, int num_points, int col);

ImagePolygon creates a polygon in image id. points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of vertices.

See also imagecreate().

ImageRectangle

ImageRectangle -- draw a rectangle

Description

int imagerectangle(int im, int x1, int y1, int x2, int y2, int col);

ImageRectangle creates a rectangle of color col in image im starting at upper left coordinate x1,y1 and ending at bottom right coordinate x2,y2. 0,0 is the top left corner of the image.

ImageSetPixel

ImageSetPixel -- set a single pixel

Description

int imagesetpixel(int im, int x, int y, int col);

ImageSetPixel draws a pixel at x,y (top left is 0,0) in image im of color col.

See also imagecreate() and imagecolorallocate().

ImageString

ImageString -- draw a string horizontally

Description

int imagestring(int im, int font, int x, int y, string s, int col);

ImageString draws the string s in the image identified by im at coordinates x,y (top left is 0,0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

ImageStringUp

ImageStringUp -- draw a string vertically

Description

int imagestringup(int im, int font, int x, int y, string s, int col);

ImageStringUp draws the string s vertically in the image identified by im at coordinates x,y (top left is 0,0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

ImageSX

ImageSX -- get image width

Description

int imagesx(int im);

ImageSX returns the width of the image identified by im.

See also imagecreate() and imagesy().

ImageSY

ImageSY -- get image height

Description

int imagesy(int im);

ImageSY returns the height of the image identified by im.

See also imagecreate() and imagesx().

ImageTTFBBox

ImageTTFBBox -- give the bounding box of a text using TypeType fonts

Description

array ImageTTFBBox(int size, int angle, string fontfile, string text);

This function calculates and returns the bounding box in pixels a TrueType text.

text

The string to be measured.

size

The font size.

fontfile

The name of the TrueType font file. (Can also be an URL.)

angle

Angle in degrees in which text will be measured.

ImageTTFBBox() returns an array with 8 elements representing four points making the bounding box of the text:

0upper left corner, X position
1upper left corner, Y position
2upper right corner, X position
3upper right corner, Y position
4lower right corner, X position
5lower right corner, Y position
6lower left corner, X position
7lower left corner, Y position
The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontallty.

This function requires both the GD library and the Freetype library.

See also ImageTTFText().

ImageTTFText

ImageTTFText -- write text to the image using a TrueType fonts

Description

array ImageTTFText(int im, int size, int angle, int x, int y, int col, string fontfile, string text);

ImageTTFText draws the string text in the image identified by im, starting at coordinates x,y (top left is 0,0), at an angle of angle in color col, using the TrueType font file identified by fontfile.

The coordinates given by x,y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the ImageString(), where x,y define the upper-right corner of the first character.

angle is in degrees, with 0 degrees being left-to-right reading text (3 o'clock direction), and higher values representing a counter-clockwise rotation. (i.e., a value of 90 would result in bottom-to-top reading text).

fontfile is the path to the TrueType font you wish to use.

ImageTTFText() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is upper left, upper right, lower right, lower left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontallty.

This example script will produce a black GIF 400x30 pixels, with the words "Testing..." in white in the font Arial.

Example 1. ImageTTFText

<?php
Header("Content-type: image/gif");
$im = imagecreate(400,30);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
ImageTTFText($im, 20, 0, 10, 20, $white, "/path/arial.ttf", "Testing...");
ImageGif($im);
ImageDestroy($im);
?>

This function requires both the GD library and the Freetype library.

See also ImageTTFBBox().

ImageColorAt

ImageColorAt -- get the index of the color of a pixel

Description

int imagecolorat(int im, int x, int y);

Returns the index of the color of the pixel at the specified location in the image.

See also imagecolorset() and imagecolorsforindex().

ImageColorClosest

ImageColorClosest -- get the index of the closest color to the specified color

Description

int imagecolorclosest(int im, int red, int green, int blue);

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

See also imagecolorexact().

ImageColorExact

ImageColorExact -- get the index of the specified color

Description

int imagecolorexact(int im, int red, int green, int blue);

Returns the index of the specified color in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosest().

ImageColorSet

ImageColorSet -- set the color for the specified palette index

Description

bool imagecolorset(int im, int index, int red, int green, int blue);

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in paletted images without the overhead of performing the actual flood-fill.

See also imagecolorat().

ImageColorsForIndex

ImageColorsForIndex -- get the colors for an index

Description

array imagecolorsforindex(int im, int index);

This returns an associative array with red, green, and blue keys that contain the appropriate values for the specified color index.

See also imagecolorat() and imagecolorexact().

ImageColorsTotal

ImageColorsTotal -- find out the number of colors in an image's palette

Description

int imagecolorstotal(int im);

This returns the number of colors in the specified image's palette.

See also imagecolorat() and imagecolorsforindex().


IMAP Functions

imap_append

imap_append -- Append a string message to a specified mailbox

Description

int imap_append(int imap_stream, string mbox, string message);

Returns true on sucess, false on error.

imap_append() function appends a string message to the specified mailbox mbox.

imap_base64

imap_base64 -- Decode BASE64 encoded text

Description

string imap_base64(string text);

imap_base64() function decodes a BASE64 encoded text. The decoded message is retunred as a string.

Note: This function uses built in c-client base64 decoding, not an internal routine, so one must load the imap.so library to use this function.

imap_body

imap_body -- Read the message body

Description

string imap_body(int imap_stream, int msg_number);

imap_body() returns the body of the message, numbered msg_number in the current mailbox.

imap_check

imap_check -- Check current mailbox

Description

array imap_check(int imap_stream);

Returns false if there are no new messages, else returns information about the current mailbox.

imap_check() function checks the current mailbox status on the server and returns the information in an associative array with following elements.

Date : date of the message
Driver : driver
Mailbox : name of the mailbox
Nmsgs : number of messages
Recent : number of recent messages

imap_close

imap_close -- Close an IMAP stream

Description

int imap_close(int imap_stream);

Returns true on success and false on error.

Close the imap stream.

imap_createmailbox

imap_createmailbox -- Create a new mailbox

Description

int imap_createmailbox(int imap_stream, string mbox);

Returns true on success and false on error.

imap_createmailbox() creates a new mailbox specified by mbox.

imap_delete

imap_delete -- Mark a messge for deletion from current mailbox

Description

int imap_delete(int imap_stream, int msg_number);

Returns true on success and false on error.

imap_delete() function marks message pointed by msg_number for deletion. Actual deletion of the messages is done by imap_expunge ().

imap_deletemailbox

imap_deletemailbox -- Delete a mailbox

Description

int imap_deletemailbox(int imap_stream, string mbox);

Returns true on success and false on error.

imap_deletemailbox() deteles the specified mailbox.

imap_expunge

imap_expunge -- Delete all messages marked for deletion

Description

int imap_expunge(int imap_stream);

Returns true on success and false on error.

imap_expunge() deletes all the messages marked for deletion by imap_delete().

imap_fetchbody

imap_fetchbody -- Fetch a particular section of the body of the message

Description

string imap_fetchbody(int imap_stream, int msg_number, int part_number);

This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.

imap_fetchstructure

imap_fetchstructure -- Read the structure of a particular message

Description

array imap_fetchstructure(int imap_stream, int msg_number);

This function causes a fetch of all the structured information for the given msg_number. The returned value is an object with following elements.

type, encoding, ifsubtype, subtype, ifdescription, description, ifid,
id, lines, bytes, ifparameters

It also returns an array of objects called parameters[]. This object has following properties.

attribute, value

In case of multipart, it also returns an array of objects of all the properties, called parts[].

imap_header

imap_header -- Read the header of the message

Description

array imap_header(int imap_stream, int msg_number);

This function returns an associative array of various header elements of the specified message.

Date, From, From2, Subject, To, cc, ReplyTo, Recent, Unseen,
Flagged, Deleted, Msgno, MailDate, Size

imap_headerinfo

imap_headerinfo -- Read the header of the messsage

Description

array imap_headerinfo(int imap_stream, int msg_number);

Same as imap_header()

imap_headers

imap_headers -- Returns headers for all messages in a mailbox

Description

array imap_headers(int imap_stream);

Returns an array of string formatted with header info. One element per mail message.

imap_listmailbox

imap_listmailbox -- Read the list of mailboxes

Description

array imap_listmailbox(int imap_stream);

Returns an array containing the names of the mailboxes.

imap_listsubscribed

imap_listsubscribed -- List all the subscribed mailboxes

Description

array imap_listsubscribed(int imap_stream);

Returns an array of all the mailboxes that you have subscribed.

imap_mail_copy

imap_mail_copy -- Copy specified messages to a mailbox

Description

int imap_mail_copy(int imap_stream, string mbox, string msglist);

Returns true on success and false on error.

Copies mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers.

imap_mail_move

imap_mail_move -- Move specified messages to a mailbox

Description

int imap_mail_move(int imap_stream, string mbox, string msglist);

Returns true on success and false on error.

Moves mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers.

imap_num_msg

imap_num_msg -- Gives the number of messages in the current mailbox

Description

int imap_num_msg(void);

Return the number of messages in the current mailbox.

imap_num_recent

imap_num_recent -- Gives the number of recent messages in current mailbox

Description

int imap_num_recent(int imap_stream);

Returns the number of recent messages in the current mailbox.

imap_open

imap_open -- Open an IMAP stream to a mailbox

Description

int imap_open(string mailbox, string username, string password);

Returns an IMAP stream on success and false on error.

imap_ping

imap_ping -- Check if the IMAP stream is still active

Description

int imap_ping(int imap_stream);

Returns true if the stream is still alive, false otherwise.

imap_ping() function pings the stream to see it is still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout.

imap_renamemailbox

imap_renamemailbox -- Rename an old mailbox to new mailbox

Description

int imap_renamemailbox(int imap_stream, string old_mbox, string new_mbox);

Returns true on success and false on error.

This function renames on old mailbox to new mailbox.

imap_reopen

imap_reopen -- Reopen IMAP stream to new mailbox

Description

int imap_reopen(string imap_stream, string username, string password);

Returns true on success and false on error.

This function reopens the specified stream to new mailbox.

imap_subscribe

imap_subscribe -- Subscribe to a mailbox

Description

int imap_subscribe(int imap_stream, string mbox);

Returns true on success and false on error.

Subscribe to a new mailbox.

imap_undelete

imap_undelete -- Unmark the message which is marked deleted

Description

int imap_undelete(int imap_stream, int msg_number);

Returns true on success and false on error.

This function removes the deletion flag for a specified message, which is set by imap_delete().

imap_unsubscribe

imap_unsubscribe -- Unsubscribe from a mailbox

Description

int imap_unsubscribe(int imap_stream, string mbox);

Returns true on success and false on error.

Unsubscribe from a specified mailbox.

imap_qprint

imap_qprint -- Convert a quoted-printable string to an 8 bit string

Description

int imap_unsubscribe(string string);

Returns an 8 bit (binary) string

Convert a quoted-printable string to an 8 bit string

imap_8bit

imap_8bit -- Convert an 8bit string to a quoted-printable string.

Description

int imap_8bit(string string);

Returns a quoted-printable string

Convert an 8bit string to a quoted-printable string.


PHP options & information

error_log

error_log -- send an error message somewhere

Description

int error_log(string message, int message_type, string destination, string extra_headers);

Sends an error message to the web server's error log, a TCP port or to a file. The first parameter, message, is the error message that should be logged. The second parameter, message_type says where the message should go:

Table 1. error_log() log types

0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used. This message type uses the same internal function as Mail() does.
2 message is sent through the PHP debugging connection. This option is only available if remote debugging has been enabled. In this case, the destination parameter specifies the host name or IP address and optionally, port number, of the socket receiving the debug information.
3 message is appended to the file destination.

Example 1. error_log() examples

// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo()) {
    error_log("Big trouble, we're all out of FOOs!", 1,
              "[email protected]");
}

// other ways of calling error_log():
error_log("You messed up!", 2, "127.0.0.1:7000");
error_log("You messed up!", 2, "loghost");
error_log("You messed up!", 3, "/var/tmp/my-errors.log");

error_reporting

error_reporting -- set which PHP errors are reported

Description

int error_reporting(int level);

Sets PHP's error reporting level and returns the old level. The error reporting level is a bitmask of the following values (follow the links for the internal values to get their meanings):

Table 1. error_reporting() bit values

valueinternal name
1

E_ERROR

2

E_WARNING

4

E_PARSE

8

E_NOTICE

16

E_CORE_ERROR

32

E_CORE_WARNING

getenv

getenv -- Get the value of an environment variable.

Description

string getenv(string varname);

Returns the value of the environment variable varname, or false on an error.

get_cfg_var

get_cfg_var -- Get the value of a PHP configuration option.

Description

string get_cfg_var(string varname);

Returns the current value of the PHP configuration variable specified by varname, or false if an error occurs.

get_current_user

get_current_user -- Get the name of the owner of the current PHP script.

Description

string get_current_user(void);

Returns the name of the owner of the current PHP script.

See also getmyuid(), getmypid(), getmyinode(), and getlastmod().

getlastmod

getlastmod -- Get time of last page modification.

Description

int getlastmod(void);

Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns false on error.

Example 1. getlastmod() example

// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() );
      

See alse date(), getmyuid(), get_current_user(), getmyinode(), and getmypid().

getmyinode

getmyinode -- Get the inode of the current script.

Description

int getmyinode(void);

Returns the current script's inode, or false on error.

See also getmyuid(), get_current_user(), getmypid(), and getlastmod().

getmypid

getmypid -- Get PHP's process ID.

Description

int getmypid(void);

Returns the current PHP process ID, or false on error.

Note that when running as a server module, separate invocations of the script are not guaranteed to have distinct pids.

See also getmyuid(), get_current_user(), getmyinode(), and getlastmod().

getmyuid

getmyuid -- Get PHP script owner's UID.

Description

int getmyuid(void);

Returns the user ID of the current script, or false on error.

See also getmypid(), get_current_user(), getmyinode(), and getlastmod().

phpinfo

phpinfo -- Output lots of PHP information.

Description

int phpinfo(void);

Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the GNU Public License.

See also phpversion().

phpversion

phpversion -- Get the current PHP version.

Description

string phpversion(void);

Returns a string containing the version of the currently running PHP parser.

Example 1. phpversion() example

// prints e.g. 'Current PHP version: 3.0rel-dev'
echo "Current PHP version: ".phpversion();
      

See also phpinfo().

putenv

putenv -- Set the value of an environment variable.

Description

void putenv(string setting);

Adds setting to the environment.

Example 1. Setting an Environment Variable

putenv("UNIQID=$uniqid");
      


LDAP Functions

ldap_add

ldap_add -- Add entries to LDAP directory

Description

int ldap_add(int link_identifier, string dn, array entry);

returns true on success and false on error.

The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.

    entry["attribute1"] = value
    entry["attribute2"][0] = value1
    entry["attribute2"][1] = value2

ldap_bind

ldap_bind -- Bind to LDAP directory

Description

int ldap_bind(int link_identifier, string bind_rdn, string bind_password);

Binds to the LDAP directory with specified RDN and password. Returns true on success and false on error.

ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.

ldap_close

ldap_close -- Close link to LDAP server

Description

int ldap_close(int link_identifier);

Returns true on success, false on error.

ldap_close() closes the link to the LDAP server that's associated with the specified link identifier.

ldap_connect

ldap_connect -- Connect to an LDAP server

Description

int ldap_connect(string hostname, int port);

Returns a positive LDAP link identifier on success, or false on error.

ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is specified, then the port defaults to 389.

ldap_count_entries

ldap_count_entries -- Count the number of entries in a search

Description

int ldap_count_entries(int link_identifier, int result_identifier);

Returns number of entries in the result or false on error.

ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.

ldap_delete

ldap_delete -- Delete an entry in a directory

Description

int ldap_delete(int link_identifier, string dn);

Returns true on success and false on error.

ldap_delete() function delete a particular entry in LDAP directory specified by dn.

ldap_dn2ufn

ldap_dn2ufn -- Convert DN to User Friendly Naming format

Description

string ldap_dn2ufn(string dn);

ldap_dn2ufn() function is used to turn a DN into a more user-friendly form, stripping off type names.

ldap_explode_dn

ldap_explode_dn -- Splits DN into its component parts

Description

string ldap_explode_dn(string dn, int with_attrib);

ldap_explode_dn() function is used to split the a DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 1 and to get only values set it to 0.

ldap_first_attribute

ldap_first_attribute -- Return first attribute

Description

string ldap_first_attribute(int link_identifier, int result_entry_identifier, int ber_identifier);

Returns the first attribute in the entry on success and false on error.

Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the entry identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.

see also ldap_get_attributes()

ldap_first_entry

ldap_first_entry -- Return first result id

Description

int ldap_first_entry(int link_identifier, int result_identifier);

Returns the result entry identifier for the first entry on success and false on error.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to lap_next_entry() routine to get successive e ntries from the result.

see also ldap_get_entries().

ldap_free_entry

ldap_free_entry -- Free entry result memory

Description

int ldap_free_entry(int result_entry_identifier);

Returns true on success and false on error.

ldap_free_entry() deallocates memory used to store the entries in LDAP result. All memory allocated for entries is automatically freed when the script terminates.

ldap_free_result

ldap_free_result -- Free result memory

Description

int ldap_free_result(int result_identifier);

Returns true on success and false on error.

ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result memory will be automatically freed when the script terminates.

ldap_get_attributes

ldap_get_attributes -- Get attributes from a search result entry

Description

array ldap_get_attributes(int link_identifier, int result_entry_identifier);

Returns a comlete entry information in a multi-dimensional array on success and false on error.

ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.

    return_value["count"] = number of attributes in the entry
    return_value[0] = first attribute
    return_value[n] = nth attribute

    return_value["attribute"]["count"] = number of values for attribute
    return_value["attribute"][0] = first value of the attribute
    return_value["attribute"][i] = ith value of the attribute

see also ldap_first_attribute() and ldap_next_attribute()

ldap_get_dn

ldap_get_dn -- Get the DN of a result entry

Description

string ldap_get_dn(int link_identifier, int result_entry_identifier);

Returns the DN of the result entry and false on error.

ldap_get_dn() function is used to find out the DN of an entry in the result.

ldap_get_entries

ldap_get_entries -- Get all result entries

Description

array ldap_get_entries(int link_identifier, int result_identifier);

Returns a complete result information in a multi-dimenasional array on success and false on error.

ldap_get_entries() function is used to simplify reading multiple entries from the result and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.

The attribute index is converted to lowercase. (Attributes are case- insensitive for directory servers, but not when used as array indices)

    return_value["count"] = number of entries in the result
    return_value[0] : refers to the details of first entry

    return_value[i]["dn"] =  DN of the ith entry in the result

    return_value[i]["count"] = number of attributes in ith entry
    return_value[i][j] = jth attribute in the ith entry in the result

    return_value[i]["attribute"]["count"] = number of values for attribute in ith entry
    return_value[i]["attribute"][j] = jth value of attribute in ith entry

see also ldap_first_entry() and ldap_next_entry()

ldap_get_values

ldap_get_values -- Get all value from a result entry

Description

array ldap_get_values(int link_identifier, int result_entry_identifier, string attribute);

Returns an array of values for the attribute on success and false on error.

ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

    return_value["count"] = number of values for attribute
    return_value[0] = first value of attribute
    return_value[i] = ith value of attribute

ldap_list

ldap_list -- Single-level search

Description

int ldap_list(int link_identifier, string base_dn, string filter);

Returns a search result identifier or false on error.

ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.

ldap_modify

ldap_modify -- Modify an LDAP entry

Description

int ldap_modify(int link_identifier, string dn, array entry);

Returns true on success and false on error.

ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().

ldap_next_attribute

ldap_next_attribute -- Get the next attribute in result

Description

string ldap_next_attribute(int link_identifier, int result_entry_identifier, int ber_identifier);

Returns the next attribute in an entry on success and false on error.

ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

see also ldap_get_attributes()

ldap_next_entry

ldap_next_entry -- Get next result entry

Description

int ldap_next_entry(int link_identifier, int result_entry_identifier);

Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns false.

ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_identifier as returned from the ldap_first_entry().

see also ldap_get_entries()

ldap_read

ldap_read -- Read an entry

Description

int ldap_read(int link_identifier, string base_dn, string filter);

Returns a search result identifier or false on error.

ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.

ldap_search

ldap_search -- Search LDAP tree

Description

int ldap_search(int link_identifier, string base_dn, string filter);

Returns a search result identifier or false on error.

ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.

ldap_unbind

ldap_unbind -- Unbind from LDAP directory

Description

int ldap_unbind(int link_identifier);

Returns true on success and false on error.

ldap_unbind() function unbinds from the LDAP directory.


Mail Functions

The mail() function allows you to send mail.

mail

mail -- send mail

Description

void mail(string to, string subject, string message, string additional_headers);

Mail() automatically mails the message specified in message to the receiver specified in to. Multiple recipients can be specified by putting a space between each address in to.

Example 1. Sending mail.

mail("[email protected]", "My Subject", "Line 1\nLine 2\nLine 3");
      

If a fourth string argument is passed, this string is inserted at the end of the header.

Example 2. Sending mail with extra headers.

mail("[email protected]", "the subject", $message, "X-Mailer: PHP/" . phpversion());
      


Mathematical Functions

Abs

Abs -- absolute value

Description

mixed abs(mixed number);

Returns the absolute value of number. If the argument number is float, return type is also float, otherwise it is int.

Acos

Acos -- arc cosine

Description

float acos(float arg);

Returns the arc cosine of arg in radians.

See also asin() and atan().

Asin

Asin -- arc sine

Description

float asin(float arg);

Returns the arc sine of arg in radians.

See also acos() and atan().

Atan

Atan -- arc tangent

Description

float atan(float arg);

Returns the arc tangent of arg in radians.

See also acos() and atan().

BinDec

BinDec -- binary to decimal

Description

int bindec(string binary_string);

Returns the decimal equivalent of the binary number represented by the binary_string argument.

OctDec converts a binary number to a decimal number. The largest number that can be converted is 31 bits of 1's or 2147483647 in decimal.

See also the decbin() function.

Ceil

Ceil -- round fractions up

Description

int ceil(float number);

Returns the next highest integer value from number. Using ceil() on integers is absolutely a waste of time.

NOTE: PHP/FI 2's ceil() returned a float. Use: $new = (double)ceil($number); to get the old behaviour.

See also floor() and round().

Cos

Cos -- cosine

Description

float cos(float arg);

Returns the cosine of arg in radians.

See also sin() and tan().

DecBin

DecBin -- decimal to binary

Description

string decbin(int number);

Returns a string containing a binary representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to a string of 31 1's.

See also the bindec() function.

DecHex

DecHex -- decimal to hexadecimal

Description

string dechex(int number);

Returns a string containing a hexadecimal representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to "7fffffff".

See also the hexdec() function.

DecOct

DecOct -- decimal to octal

Description

string decoct(int number);

Returns a string containing an octal representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to "17777777777". See also octdec().

Exp

Exp -- e to the power of...

Description

float exp(float arg);

Returns e raised to the power of arg.

See also pow().

Floor

Floor -- round fractions down

Description

int floor(float number);

Returns the next lowest integer value from number. Using floor() on integers is absolutely a waste of time.

NOTE: PHP/FI 2's floor() returned a float. Use: $new = (double)floor($number); to get the old behaviour.

See also ceil() and round().

getrandmax

getrandmax -- show largest possible random value

Description

int getrandmax(void );

Returns the maximum value that can be returned by a call to rand().

See also rand() and srand().

HexDec

HexDec -- hexadecimal to decimal

Description

int hexdec(string hex_string);

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. HexDec converts a hexadecimal string to a decimal number. The largest number that can be converted is 7fffffff or 2147483647 in decimal.

See also the dechex() function.

Log

Log -- natural logarithm

Description

float log(float arg);

Returns the natural logarithm of arg.

Log10

Log10 -- base-10 logarithm

Description

float log10(float arg);

Returns the base-10 logarithm of arg.

max

max -- find highest value

Description

mixed max(mixed arg1, mixed arg2, mixed argn);

max() returns the numerically highest of the parameter values.

If the first parameter is an array, max() returns the highest value in that array. If the first parameter is an integer, string or double, you need at least two parameters and max() returns the biggest of these values. You can compare an unlimited number of values.

If one or more of the values is a double, all the values will be treated as doubles, and a double is returned. If none of the values is a double, all of them will be treated as integers, and an integer is returned.

min

min -- find lowest value

Description

mixed min(mixed arg1, mixed arg2, mixed argn);

min() returns the numerically lowest of the parameter values.

If the first parameter is an array, min() returns the lowest value in that array. If the first parameter is an integer, string or double, you need at least two parameters and min() returns the lowest of these values. You can compare an unlimited number of values.

If one or more of the values is a double, all the values will be treated as doubles, and a double is returned. If none of the values is a double, all of them will be treated as integers, and an integer is returned.

number_format

number_format -- format a number with grouped thousands

Description

string number_format(float number, int decimals, string dec_point, string thousands_sep);

number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

OctDec

OctDec -- octal to decimal

Description

int octdec(string octal_string);

Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. OctDec converts an octal string to a decimal number. The largest number that can be converted is 17777777777 or 2147483647 in decimal.

See also decoct().

pi

pi -- get value of pi

Description

double pi(void );

Returns an approximation of pi.

pow

pow -- exponential expression

Description

float pow(float base, float exp);

Returns base raised to the power of exp.

See also exp().

rand

rand -- generate a random value

Description

int rand(void );

Returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15, for example, use rand()%10 + 5.

Remember to seed the random number generator before use with srand().

See also srand() and getrandmax().

round

round -- Rounds a float.

Description

double round(double val);

Returns the rounded value of val.

$foo = round( 3.4 );   // $foo == 3.0
$foo = round( 3.5 );   // $foo == 4.0
$foo = round( 3.6 );   // $foo == 4.0
      

See also ceil() and floor().

Sin

Sin -- sine

Description

float sin(float arg);

Returns the sine of arg in radians.

See also cos() and tan().

Sqrt

Sqrt -- square root

Description

float sqrt(float arg);

Returns the square root of arg.

srand

srand -- seed the random number generator

Description

void srand(int seed);

Seeds the random number generator with seed.

// seed with microseconds since last "whole" second
srand((double)microtime()*1000000);
$randval = rand();
      

See also rand() and getrandmax().

Tan

Tan -- tangent

Description

float tan(float arg);

Returns the tangent of arg in radians.

See also sin() and cos().


Miscellaneous Functions

These functions were placed here because none of the other categories seemed to fit.

sleep

sleep -- Delay execution

Description

void sleep(int seconds);

The sleep function delays program execution for the given number of seconds.

See also usleep().

usleep

usleep -- Delay execution in microseconds

Description

void usleep(int micro_seconds);

The sleep function delays program execution for the given number of micro_seconds.

See also sleep().

uniqid

uniqid -- generate a unique id

Description

int uniqid(string prefix);

Uniqid() returns a prefixed unique identifier based on current time in microseconds. The prefix can be useful for instance if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. The prefix can be up to 114 characters long.

leak

leak -- Leak memory

Description

void leak(int bytes);

Leak() leaks the specified amount of memory.

This is useful when debugging the memory manager, which automatically cleans up "leaked" memory when each request is completed.


mSQL Functions

msql

msql -- send mSQL query

Description

int msql(string database, string query, int link_identifier);

Returns a positive mSQL result identifier to the query result, or false on error.

msql() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the mSQL server and if no such link is found it'll try to create one as if msql_connect() was called with no arguments (see msql_connect()).

msql_close

msql_close -- close mSQL connection

Description

int msql_close(int link_identifier);

Returns true on success, false on error.

msql_close() closes the link to a mSQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

msql_close() will not close persistent links generated by msql_pconnect().

See also: msql_connect() and msql_pconnect().

msql_connect

msql_connect -- open mSQL connection

Description

int msql_connect(string hostname);

Returns a positive mSQL link identifier on success, or false on error.

msql_connect() establishes a connection to a mSQL server. The hostname argument is optional, and if it's missing, localhost is assumed.

In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().

See also msql_pconnect(), msql_close().

msql_create_db

msql_create_db -- create mSQL database

Description

int msql_create_db(void);

msql_create_db() attempts to create a new database on the server associated with the specified link identifier.

See also: msql_drop_db().

msql_createdb

msql_createdb -- create mSQL database

Description

int msql_createdb(void);

Identical to msql_create_db().

msql_data_seek

msql_data_seek -- move internal row pointer

Description

int msql_data_seek(int result_identifier, int row_number);

Returns true on success, false on failure.

msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified result identifier to pointer to the specifyed row number. The next call to msql_fetch_row() would return that row.

See also: msql_fetch_row().

msql_dbname

msql_dbname -- get current mSQL database name

Description

string msql_dbname(string result, int i);

msql_dbname() returns the database name stored in position i of the result pointer returned from the msql_listdbs() function. The msql_numrows() function can be used to determine how many database names are available.

msql_drop_db

msql_drop_db -- drop (delete) mSQL database

Description

int msql_drop_db(string database_name, int link_identifier);

Returns true on success, false on failure.

msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

See also: msql_create_db().

msql_dropdb

msql_dropdb -- drop (delete) mSQL database

Description

See msql_drop_db().

msql_error

msql_error -- returns error message of last msql call

Description

string msql_error( );

Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.

msql_fetch_array

msql_fetch_array -- fetch row as array

Description

int msql_fetch_array(int result);

Returns an array that corresponds to the fetched row, or false if there are no more rows.

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

For further details, also see msql_fetch_row()

msql_fetch_field

msql_fetch_field -- get field information

Description

object msql_fetch_field(int result, int field_offset);

Returns an object containing field information

msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by msql_fetch_field() is retreived.

The properties of the object are:

See also msql_field_seek().

msql_fetch_object

msql_fetch_object -- fetch row as object

Description

int msql_fetch_object(int result);

Returns an object with properties that correspond to the fetched row, or false if there are no more rows.

msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

See also: msql_fetch_array() and msql_fetch_row().

msql_fetch_row

msql_fetch_row -- get row as enumerated array

Description

array msql_fetch_row(int result);

Returns an array that corresponds to the fetched row, or false if there are no more rows.

msql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or false if there are no more rows.

See also: msql_fetch_array(), msql_fetch_object(), msql_data_seek(), and msql_result().

msql_fieldname

msql_fieldname -- get field name

Description

string msql_fieldname(int result, int field);

msql_fieldname() returns the name of the specified field. result is the result identifier, and field is the field index. msql_fieldname($result, 2); will return the name of the second field in the result associated with the result identifier.

msql_field_seek

msql_field_seek -- set field offset

Description

int msql_field_seek(int result, int field_offset);

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

See also: msql_fetch_field().

msql_fieldtable

msql_fieldtable -- get table name for field

Description

int msql_fieldtable(int result, int field);

Returns the name of the table field was fetched from.

msql_fieldtype

msql_fieldtype -- get field type

Description

string msql_fieldtype(string result, int i);

msql_fieldtype() is similar to the msql_fieldname() function. The arguments are identical, but the field type is returned. This will be one of "int", "string" or "real".

msql_fieldflags

msql_fieldflags -- get field flags

Description

string msql_fieldflags(string result, int i);

msql_fieldflags() returns the field flags of the specified field. Currently this is either, "not null", "primary key", a combination of the two or "" (an empty string).

msql_fieldlen

msql_fieldlen -- get field length

Description

int msql_fieldlen(string result, int i);

msql_fieldlen() returns the length of the specified field.

msql_free_result

msql_free_result -- free result memory

Description

int msql_free_result(int result);

msql_free_result() frees the memory associated with result. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

msql_freeresult

msql_freeresult -- free result memory

Description

See msql_free_result()

msql_list_fields

msql_list_fields -- list result fields

Description

int msql_list_fields(string database, string tablename);

msql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with msql_fieldflags(), msql_fieldlen(), msql_fieldname(), and msql_fieldtype(). A result identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @msql_list_fields() then this error string will also be printed out.

See also msql_error().

msql_listfields

msql_listfields -- list result fields

Description

See msql_list_fields().

msql_list_dbs

msql_list_dbs -- list mSQL databases on server

Description

int msql_list_dbs(void);

msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the msql_dbname() function to traverse this result pointer.

msql_listdbs

msql_listdbs -- list mSQL databases on server

Description

See msql_list_dbs().

msql_list_tables

msql_list_tables -- list tables in an mSQL database

Description

int msql_list_tables(string database);

msql_list_tables() takes a database name and result pointer much like the msql() function. The msql_tablename() function should be used to extract the actual table names from the result pointer.

msql_listtables

msql_listtables -- list tables in an mSQL database

Description

See msql_list_tables().

msql_num_fields

msql_num_fields -- get number of fields in result

Description

int msql_num_fields(int result);

msql_num_fields() returns the number of fields in a result set.

See also: msql(), msql_query(), msql_fetch_field(), and msql_num_rows().

msql_num_rows

msql_num_rows -- get number of rows in result

Description

int msql_num_rows(string result);

msql_num_rows() returns the number of rows in a result set.

See also: msql(), msql_query(), and msql_fetch_row().

msql_numfields

msql_numfields -- get number of fields in result

Description

int msql_numfields(int result);

Identical to msql_num_fields().

msql_numrows

msql_numrows -- get number of rows in result

Description

int msql_numrows(void);

Identical to msql_num_rows().

msql_pconnect

msql_pconnect -- open persistent mSQL connection

Description

int msql_pconnect(string hostname);

Returns a positive mSQL persistent link identifier on success, or false on error.

msql_pconnect() acts very much like msql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by msql_pconnect()).

This type of links is therefore called 'persistent'.

msql_query

msql_query -- send mSQL query

Description

int msql_query(string query, int link_identifier);

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if msql_connect() was called, and use it.

Returns a positive mSQL result identifier on success, or false on error.

See also: msql(), msql_select_db(), and msql_connect().

msql_regcase

msql_regcase -- make regular expression for case insensitive match

Description

See sql_regcase().

msql_result

msql_result -- get result data

Description

int msql_result(int result, int i, mixed field);

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than msql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().

msql_select_db

msql_select_db -- select mSQL database

Description

int msql_select_db(string database_name, int link_identifier);

Returns true on success, false on error.

msql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if msql_connect() was called, and use it.

Every subsequent call to msql_query() will be made on the active database.

See also: msql_connect(), msql_pconnect(), and msql_query().

msql_selectdb

msql_selectdb -- select mSQL database

Description

See msql_select_db().

msql_tablename

msql_tablename -- get table name of field

Description

string msql_tablename(int result, int field);

msql_tablename() takes a result pointer returned by the msql_list_tables() function as well as an integer index and returns the name of a table. The msql_numrows() function may be used to determine the number of tables in the result pointer.

Example 1. msql_tablename() example

<?php 
msql_connect ("localhost");
$result = msql_list_tables("wisconsin");
$i = 0;
while ($i < msql_numrows($result)) {
    $tb_names[$i] = msql_tablename($result, $i);
    echo $tb_names[$i] . "<BR>";
    $i++; 
}
?>


MySQL Functions

mysql_affected_rows

mysql_affected_rows -- get number of affected rows in last query

Description

int mysql_affected_rows(int link_identifier );

Returns: The number of affected rows by the last query.

mysql_affected_rows() returns the number of rows affected by the last insert, update or delete query on the server associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

mysql_close

mysql_close -- close MySQL connection

Description

int mysql_close(int link_identifier );

Returns: true on success, false on error

mysql_close() closes the link to a MySQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

mysql_close() will not close persistent links generated by mysql_pconnect().

See also: mysql_connect(), and mysql_pconnect().

mysql_connect

mysql_connect -- open MySQL server connection

Description

int mysql_connect(string hostname , string username , string password );

Returns: A positive MySQL link identifier on success, or false on error.

mysql_connect() establishes a connection to a MySQL server. All of the arguments are optional, and if they're missing, defaults are assumed ('localhost', user name of the user that owns the server process, empty password). The hostname string can also include a port number. eg. "hostname:port"

In case a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().

See also mysql_pconnect(), and mysql_close().

mysql_create_db

mysql_create_db -- create MySQL database

Description

int mysql_create_db(string database name, int link_identifier );

mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.

See also: mysql_drop_db(). For downwards compatibility mysql_createdb() can also be used.

mysql_data_seek

mysql_data_seek -- move internal row pointer

Description

int mysql_data_seek(int result_identifier, int row_number);

Returns: true on success, false on failure

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to pointer to the specifyed row number. The next call to mysql_fetch_row() would return that row.

See also: mysql_data_seek().

mysql_dbname

mysql_dbname -- get current MySQL database name

Description

string mysql_dbname(string result, int i);

mysql_dbname() returns the database name stored in position i of the result pointer returned from the mysql_list_dbs() function. The mysql_num_rows() function can be used to determine how many database names are available.

mysql_db_query

mysql_db_query -- send MySQL query

Description

int mysql_db_query(string database, string query, int link_identifier);

Returns: A positive MySQL result identifier to the query result, or false on error.

mysql_db_query() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the MySQL server and if no such link is found it'll try to create one as if mysql_connect() was called with no arguments

See also mysql_connect(). For downwards compatibility mysql() can also be used.

mysql_drop_db

mysql_drop_db -- drop (delete) MySQL database

Description

int mysql_drop_db(string database_name, int link_identifier );

Returns: true on success, false on failure.

mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

See also: mysql_create_db(). For downward compatibility mysql_dropdb() can also be used.

mysql_errno

mysql_errno -- returns error number of last mysql call

Description

int mysql_errno();

Errors coming back from the mySQL database backend no longer issue warnings. Instead, use these functions to retrieve the error number.