PHP Manual

Stig Sæther Bakken
Alexander Aulbach
Egon Schmid
Jim Winstead
Lars Torben Wilson
Rasmus Lerdorf
Zeev Suraski
Andrei Zmievski

Edited by

Stig Sæther Bakken

Egon Schmid

Copyright

This manual is © Copyright 1997, 1998, 1999, 2000 by the PHP Documentation Group. The members of this group are listed on the front page of this manual.

This manual can be redistributed under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.


Table of Contents
Preface
About this Manual
I. Getting Started
1. Introduction
2. Installation
3. Configuration
4. Security
II. Language Reference
5. Basic syntax
6. Types
7. Variables
8. Constants
9. Expressions
10. Operators
11. Control Structures
12. Functions
13. Classes and Objects
14. References Explained
III. Features
15. Error Handling
16. Creating and manipulating images
17. HTTP authentication with PHP
18. Cookies
19. Handling file uploads
20. Using remote files
21. Connection handling
22. Persistent Database Connections
IV. Function Reference
I. Apache-specific Functions
II. Array Functions
III. Aspell functions
IV. BCMath Arbitrary Precision Mathematics Functions
V. Calendar functions
VI. CCVS API Functions
VII. COM support functions for Windows
VIII. Class/Object Functions
IX. ClibPDF functions
X. CURL, Client URL Library Functions
XI. Cybercash payment functions
XII. Database (dbm-style) abstraction layer functions
XIII. Date and Time functions
XIV. dBase functions
XV. DBM Functions
XVI. Directory functions
XVII. Dynamic Loading functions
XVIII. DOM XML functions
XIX. filePro functions
XX. Filesystem functions
XXI. Forms Data Format functions
XXII. FTP functions
XXIII. GNU Gettext
XXIV. HTTP functions
XXV. Hyperwave functions
XXVI. ICAP Functions
XXVII. Image functions
XXVIII. IMAP, POP3 and NNTP functions
XXIX. Informix functions
XXX. InterBase functions
XXXI. LDAP functions
XXXII. Mail functions
XXXIII. Mathematical Functions
XXXIV. MCAL functions
XXXV. Mcrypt Encryption Functions
XXXVI. Mhash Functions
XXXVII. Microsoft SQL Server functions
XXXVIII. Miscellaneous functions
XXXIX. mSQL functions
XL. MySQL functions
XLI. Network Functions
XLII. Unified ODBC functions
XLIII. Oracle functions
XLIV. Oracle 8 functions
XLV. PDF functions
XLVI. Verisign Payflow Pro functions
XLVII. PHP options & information
XLVIII. POSIX functions
XLIX. PostgreSQL functions
L. Program Execution functions
LI. Pspell Functions
LII. GNU Readline
LIII. GNU Recode functions
LIV. Regular Expression Functions (Perl-Compatible)
LV. Regular Expression Functions (POSIX Extended)
LVI. Semaphore and Shared Memory Functions
LVII. Session handling functions
LVIII. Shockwave Flash functions
LIX. SNMP functions
LX. String functions
LXI. Sybase functions
LXII. URL Functions
LXIII. Variable Functions
LXIV. Vmailmgr functions
LXV. WDDX functions
LXVI. XML parser functions
LXVII. YAZ
LXVIII. YP/NIS Functions
LXIX. Zlib Compression Functions
V. Appendixes
A. Migrating from PHP/FI 2.0 to PHP 3.0
B. PHP development
C. The PHP Debugger

Preface

PHP, which stands for "PHP: Hypertext Preprocessor", 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 XML using the DocBook XML 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. PHP's documentation framework is maintained by Stig Sæther Bakken.

Daily HTML snapshots of the manual, including translations, can be found at http://snaps.php.net/manual/.

I. Getting Started

Table of Contents
1. Introduction
2. Installation
3. Configuration
4. Security

Chapter 1. Introduction

What is PHP?

PHP (officially "PHP: Hypertext Preprocessor") is a server-side HTML-embedded scripting language.

Simple answer, but what does that mean? An example:

Example 1-1. An introductory example

<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <?php echo "Hi, I'm a PHP script!"; ?>
    </body>
</html>
     

Notice how this is different from a CGI script written in other languages like Perl or C -- instead of writing a program with lots of commands to output HTML, you write an HTML script with a some embedded code to do something (in this case, output some text). The PHP code is enclosed in special start and end tags that allow you to jump into and out of PHP mode.

What distinguishes PHP from something like client-side Javascript is that the code is executed on the server. If you were to have a script similar to the above on your server, the client would receive the results of running that script, with no way of determining what the underlying code may be. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.


What can PHP do?

At the most basic level, PHP can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies.

Perhaps the strongest and most significant feature in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

Adabas D InterBase PostgreSQL
dBase FrontBase Solid
Empress mSQL Sybase
FilePro (read-only) Direct MS-SQL Velocis
IBM DB2 MySQL Unix dbm
Informix ODBC  
Ingres Oracle (OCI7 and OCI8)  

PHP also has support for talking to other services using protocols such as IMAP, SNMP, NNTP, POP3, HTTP and countless others. You can also open raw network sockets and interact using other protocols.


A brief history of PHP

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

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

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

Also as of this writing, work is underway on the next generation of PHP, which will utilize the powerful Zend scripting engine to deliver higher performance, and will also support running under webservers other than Apache as a native server module.


Chapter 2. Installation

Downloading the latest version

The source code, and binary distributions for some platforms (including Windows), can be found at http://www.php.net/.


Installation on UNIX systems

This section will guide you through the configuration and installation of PHP. Prerequisite knowledge and software:

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

  • An ANSI C compiler

  • A web server


Quick Installation Instructions (Apache Module Version)

1.  gunzip apache_1.3.x.tar.gz
2.  tar xvf apache_1.3.x.tar
3.  gunzip php-x.x.x.tar.gz
4.  tar xvf php-x.x.x.tar
5.  cd apache_1.3.x
6.  ./configure --prefix=/www
7.  cd ../php-x.x.x
8.  ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9.  make
10. make install
11. cd ../apache_1.3.x
12. for PHP 3: ./configure --activate-module=src/modules/php3/libphp3.a
    for PHP 4: ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install

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

15. cd ../php-x.x.x
16. for PHP 3: cp php3.ini-dist /usr/local/lib/php3.ini
    for PHP 4: cp php.ini-dist /usr/local/lib/php.ini

  You can edit your .ini file to set PHP options.  If
  you prefer this file in another location, use
  --with-config-file-path=/path in step 8.

17. Edit your httpd.conf or srm.conf file and add: 
      
     For PHP 3:   AddType application/x-httpd-php3 .php3
     For PHP 4:   AddType application/x-httpd-php .php
 
  You can choose any extension you wish here.  .php is simply the one
  we suggest.

18. Use your normal procedure for starting the Apache server. (You must
    stop and restart the server, not just cause the server to reload by
    use a HUP or USR1 signal.)
      


Apache Module

PHP can be compiled in a number of different ways. Here is a quick summary:

./configure --with-apxs --with-pgsql
      

This will create a libphp4.so shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this libphp4.so library.

./configure --with-apxs --with-pgsql=shared
      

This will again create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.

./configure --with-apache=/path/to/apache_source --with-pgsql
      

This will create a libmodphp4.a library, a mod_php4.c and some accompanying files and copy this into the src/modules/php4 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php4/libphp4.a and the Apache build system will create libphp4.a and link it statically into the httpd binary. The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

./configure --with-apache=/path/to/apache_source --with-pgsql=shared
      

Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from eihter the php.ini file or directly using dl().


fhttpd Module

To build PHP 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 PHP as a CGI program. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables Apache users to run different PHP-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

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


Adabas D

      --with-adabas=DIR
     

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


IBM DB2

      --with-ibm-db2=DIR
     

Enables IBM DB2 support. The parameter to this option is the DB2 base install directory and defaults to /home/db2inst1/sqllib.

IBM DB2 home page


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 PHP supports both 1.0 and 2.0, but if you compile PHP 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 or iODBC home page


OpenLink ODBC

      --with-openlink=DIR
     

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

OpenLink Software's home page


Oracle

      --with-oracle=DIR
     

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

Oracle home page


PostgreSQL

      --with-pgsql=DIR
     

Includes PostgreSQL support. The parameter is the PostgreSQL base install directory and defaults to /usr/local/pgsql.

See also Postgres Configuration Directives in the configuration file.

PostgreSQL home page


Solid

      --with-solid=DIR
     

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

Solid home page


Sybase

      --with-sybase=DIR
     

Includes Sybase support. The parameter is the Sybase install directory and defaults to /home/sybase.

See also Sybase Configuration Directives in the configuration file.

Sybase home page


Sybase-CT

      --with-sybase-ct=DIR
     

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

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


Velocis

      --with-velocis=DIR
     

Includes Velocis support. The parameter is the Velocis install directory and defaults to /usr/local/velocis.

Velocis home page


A custom ODBC library

      --with-custom-odbc=DIR
     

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

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

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


Unified ODBC

      --disable-unified-odbc
     

Disables the Unified ODBC module, which is a common interface to all the databases with ODBC-based interfaces, such as Solid, IBM DB2 and Adabas D. It also works for normal ODBC libraries. Has been tested with iODBC, Solid, Adabas D, IBM DB2 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-ibm-db2, --with-adabas, --with-velocis, or --with-custom-odbc.

See also Unified ODBC Configuration Directives in the configuration file.


LDAP

      --with-ldap=DIR
     

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

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


Other configure options

--with-mcrypt=DIR

      --with-mcrypt
     

Include support for the mcrypt library. See the mcrypt documentation for more information. If you use the optional DIR argument, PHP will look for mcrypt.h in DIR/include.


--enable-sysvsem

      --enable-sysvsem
     

Include support for Sys V semaphores (supported by most Unix derivates). See the Semaphore and Shared Memory documentation for more information.


--enable-sysvshm

      --enable-sysvshm
     

Include support for Sys V shared memory (supported by most Unix derivates). See the Semaphore and Shared Memory documentation for more information.


--with-xml

      --with-xml
     

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


--enable-maintainer-mode

      --enable-maintainer-mode
     

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


--with-system-regex

      --with-system-regex
     

Uses the system's regular expression library rather than the bundled one. If you are building PHP as a server module, you must use the same library when building PHP 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 configuration 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.


--enable-debug

      --enable-debug
     

Enables extra debug information. This makes it possible to gather more detailed information when there are problems with PHP. (Note that this doesn't have anything to do with debugging facilities or information available to PHP scripts.)


--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 PHP 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 PHP 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 <? ?> PHP tags. You must disable the short form if you want to use PHP with XML. With short tags disabled, the only PHP 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 PHP 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 PHP 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 PHP is configured, you are ready to build the CGI executable or the PHP library. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.


Testing

If you have built PHP 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 PHP on your platform early instead of having to struggle with it later.


Benchmarking

If you have built PHP 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 configuration setting to control this time for your own scripts. make bench ignores the configuration file.


Installation on Windows 95/98/NT systems

This install guide will help you install and configure PHP on your Windows 9x/NT webservers. This guide was compiled by Bob Silva. The latest revision can be found at http://www.umesd.k12.or.us/php/win32install.html.

This guide provides installation support for:

  • Personal Web Server (Newest version recommended)

  • Internet Information Server 3 or 4

  • Apache 1.3.x

  • Omni HTTPd 2.0b1


General Installation Steps

The following steps should be performed on all installations before the server specific instructions.

  • Extract the distribution file to a directory of your choice. "C:\PHP\" is a good start.

  • Copy the file, 'php.ini-dist' to your '%WINDOWS%' directory and rename it to 'php.ini'. Your '%WINDOWS%' directory is typically:

    c:\windows for Windows 95/98
    c:\winnt or c:\winnt40 for NT servers

  • Edit your 'php.ini' file:

    • You will need to change the 'extension_dir' setting to point to your php-install-dir, or where you have placed your 'php_*.dll' files. ex: c:\php

    • If you are using Omni Httpd, do not follow the next step. Set the 'doc_root' to point to your webservers document_root. ex: c:\apache\htdocs or c:\webroot

    • Choose which modules you would like to load when PHP starts. You can uncomment the: 'extension=php_*.dll' lines to load these modules. Some modules require you to have additional libraries installed on your system for the module to work correctly. The PHP FAQ has more information on where to get supporting libraries. You can also load a module dynamically in your script using: dl("php_*.dll");

    • On PWS and IIS, you can set the browscap.ini to point to: 'c:\windows\system\inetsrv\browscap.ini' on Windows 95/98 and 'c:\winnt\system32\inetsrv\browscap.ini' on NT Server. Additional information on using the browscap functionality in PHP can be found at this mirror, select the "source" button to see it in action.

The DLLs for PHP extensions are prefixed with 'php_'. This prevents confusion between PHP extensions and their supporting libraries.


Windows 95/98/NT and PWS/IIS 3

The recommended method for configuring these servers is to use the INF file included with the distribution (php_iis_reg.inf). You may want to edit this file and make sure the extensions and PHP install directories match your configuration. Or you can follow the steps below to do it manually.

WARNING: These steps involve working directly with the windows registry. One error here can leave your system in an unstable state. We highly recommend that you back up your registry first. The PHP Development team will not be held responsible if you damage your registry.

  • Run Regedit.

  • Navigate to: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.

  • On the edit menu select: New->String Value.

  • Type in the extension you wish to use for your php scripts. ex: .php

  • Double click on the new string value and enter the path to php.exe in the value data field. ex: c:\php\php.exe %s %s. The '%s %s' is VERY important, PHP will not work properly without it.

  • Repeat these steps for each extension you wish to associate with PHP scripts.

  • Now navigate to: HKEY_CLASSES_ROOT

  • On the edit menu select: New->Key.

  • Name the key to the extension you setup in the previous section. ex: .php

  • Highlight the new key and in the right side pane, double click the "default value" and enter phpfile.

  • Repeat the last step for each extension you set up in the previous section.

  • Now create another New->Key under HKEY_CLASSES_ROOT and name it phpfile.

  • Highlight the new key phpfile and in the right side pane, double click the "default value" and enter PHP Script.

  • Right click on the phpfile key and select New->Key, name it Shell.

  • Right click on the Shell key and select New->Key, name it open.

  • Right click on the open key and select New->Key, name it command.

  • Highlight the new key command and in the right side pane, double click the "default value" and enter the path to php.exe. ex: c:\php\php.exe -q %1. (don't forget the %1).

  • Exit Regedit.

PWS and IIS 3 users now have a fully operational system. IIS 3 users can use a nifty tool from Steven Genusa to configure their script maps.


Windows NT and IIS 4

To install PHP on an NT Server running IIS 4, follow these instructions:

  • In Internet Service Manager (MMC), select the Web site or the starting point directory of an application.

  • Open the directory's property sheets (by right clicking and selecting properties), and then click the Home Directory, Virtual Directory, or Directory tab.

  • Click the Configuration button, and then click the App Mappings tab.

  • Click Add, and in the Executable box, type: c:\path-to-php-dir\php.exe %s %s. You MUST have the %s %s on the end, PHP will not function properly if you fail to do this.

  • In the Extension box, type the file name extension you want associated with PHP scripts. (You must repeat step 5 and 6 for each extension you want accociated with PHP scripts. (.php and .phtml are common.)

  • Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe.


Windows 9x/NT and Apache 1.3.x

You must edit your srm.conf or httpd.conf to configure Apache to work with the PHP CGI binary.

Although there can be a few variations of configuring PHP under Apache, this one is simple enough to be used by the newcomer. Please consult the Apache Docs for further configuration directives.

  • ScriptAlias /php/ "c:/path-to-php-dir/"

  • AddType application/x-httpd-php .php

  • AddType application/x-httpd-php .phtml

  • Action application/x-httpd-php "/php/php.exe"

To use the source code highlighting feature, simply create a PHP script file and stick this code in: <?php show_source ("original_php_script.php"); ?>. Substitute original_php_script.php with the name of the file you wish to show the source of. (this is only one way of doing it). Note: On Win-Apache all back slashes in a path statement such as: "c:\directory\file.ext", must be converted to forward slashes.


Omni HTTPd 2.0b1 for Windows

This has got to be the easiest config there is:

  • Step 1: Install Omni server

  • Step 2: Right click on the blue OmniHTTPd icon in the system tray and select Properties

  • Step 3: Click on Web Server Global Settings

  • Step 4: On the 'External' tab, enter: virtual = .php | actual = c:\path-to-php-dir\php.exe

  • Step 5: On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php

  • Step 6: Click OK

Repeat steps 2 - 6 for each extension you want to associate with PHP.


PHP Modules

Table 2-1. PHP Modules

php_calendar.dll Calendar conversion functions
php_crypt.dll Crypt functions
php_dbase.dll DBase functions
php_dbm.dll GDBM emulation via Berkely DB2 library
php_filepro.dll READ ONLY access to filepro databases
php_gd.dll GD Library functions for gif manipulation
php_hyperwave.dll HyperWave functions
php_imap4r2.dll IMAP 4 functions
php_ldap.dll LDAP functions
php_msql1.dll mSQL 1 client
php_msql2.dll mSQL 2 client
php_mssql.dll MSSQL client (requires MSSQL DB-Libraries
php3_mysql.dll (Built into PHP 4) MySQL functions
php_nsmail.dll Netscape mail functions
php_oci73.dll Oracle functions
php_snmp.dll SNMP get and walk functions (NT only!)
php_zlib.dll ZLib functions


Problems?

Read the FAQ

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


Bug reports

If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at http://www.php.net/bugs.php.


Other problems

If you are still stuck, someone on the PHP 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 archives are available from the support page on http://www.php.net/. To subscribe to the PHP mailing list, send an empty mail to php-general-subscribe@lists.php.net. The mailing list address is php-general@lists.php.net.

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


Chapter 3. Configuration

The configuration file

The configuration file (called php3.ini in PHP 3.0, and simply php.ini as of PHP 4.0) is read when PHP 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.

When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files and .htaccess files.

With PHP 3.0, there are Apache directives that correspond to each configuration setting in the php3.ini name, except the name is prefixed by "php3_".

With PHP 4.0, there are just a few Apache directives that allow you to change the PHP configuration settings.

php_value name value

This sets the value of the specified variable.

php_flag name on|off

This is used to set a Boolean configuration option.

php_admin_value name value

This sets the value of the specified variable. "Admin" configuration settings can only be set from within the main Apache configuration files, and not from .htaccess files.

php_admin_flag name on|off

This is used to set a Boolean configuration option.

You can view the settings of the configuration values in the output of phpinfo(). You can also access the values of individial configuration settings using get_cfg_var().


General Configuration Directives

asp_tags boolean

Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML.

Note: Support for ASP-style tags was added in 3.0.4.

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 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 3-1. Error Reporting Levels

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

open_basedir string

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

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

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

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

Note: Support for multiple directories was added in 3.0.7.

The default is to allow all files to be opened.

gpc_order string

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

ignore_user_abort string

On by default. If changed to Off scripts will be terminated as soon as they try to output something after a client has aborted their connection. ignore_user_abort().

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 3-1. UNIX include_path

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

Example 3-2. Windows include_path

include_path=".;c:\www\phplib"
The default value for this directive is . (only the current directory).

isapi_ext string

log_errors boolean

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

magic_quotes_gpc boolean

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

magic_quotes_runtime boolean

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

magic_quotes_sybase boolean

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

max_execution_time integer

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

memory_limit integer

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

nsapi_ext string

short_open_tag boolean

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

sql.safe_mode boolean

track_errors boolean

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

track_vars boolean

If enabled, GET, POST and cookie input can be found in the global associative arrays $HTTP_GET_VARS, $HTTP_POST_VARS and $HTTP_COOKIE_VARS, respectively.

upload_tmp_dir string

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

user_dir string

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

warn_plus_overloading boolean

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


Mail Configuration Directives

SMTP string

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

sendmail_from string

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

sendmail_path string

Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

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


Safe Mode Configuration Directives

safe_mode boolean

Whether to enable PHP's safe mode. Read the Security chapter for more more information.

safe_mode_exec_dir string

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


Debugger Configuration Directives

debugger.host string

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

debugger.port string

Port number used by the debugger.

debugger.enabled boolean

Whether the debugger is enabled.


Extension Loading Directives

enable_dl boolean

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

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

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

extension_dir string

In what directory PHP should look for dynamically loadable extensions.

extension string

Which dynamically loadable extensions to load when PHP starts up.


MySQL Configuration Directives

mysql.allow_persistent boolean

Whether to allow persistent MySQL connections.

mysql.default_host string

The default server host to use when connecting to the database server if no other host is specified.

mysql.default_user string

The default user name to use when connecting to the database server if no other name is specified.

mysql.default_password string

The default password to use when connecting to the database server if no other password is specified.

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. The default is on.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.

sybct.min_server_severity integer

Server messages with severity greater than or equal to sybct.min_server_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_server_severity(). The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Client library messages with severity greater than or equal to sybct.min_client_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_client_severity(). The default is 10 which effectively disables reporting.

sybct.login_timeout integer

The maximum time in seconds to wait for a connection attempt to succeed before returning failure. Note that if max_execution_time has been exceeded when a connection attempt times out, your script will be terminated before it can take action on failure. The default is one minute.

sybct.timeout integer

The maximum time in seconds to wait for a select_db or query operation to succeed before returning failure. Note that if max_execution_time has been exceeded when am operation times out, your script will be terminated before it can take action on failure. The default is no limit.

sybct.hostname string

The name of the host you claim to be connecting from, for display by sp_who. The default is none.


Informix Configuration Directives

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

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

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect().

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect().

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect().

ifx.blobinfile boolean

Set to true if you want to return blob columns in a file, false if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to true if you want to return TEXT columns as normal strings in select statements, false if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to true if you want to return BYTE columns as normal strings in select queries, false if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to true if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to true if you want to return NULL columns as the literal string "NULL", false if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().


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. See also get_browser().


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.


Chapter 4. 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 against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

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

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

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

  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html

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

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


Case 1: only public files served

If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to 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 in Apache by using AddHandler and Action directives (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, because of some configuration mistake, the scripts are not executed but displayed as regular 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 are accessible only 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 configuration 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 user permissions (typically those of the "nobody" user).

II. Language Reference


Chapter 5. Basic syntax

Escaping from HTML

There are four 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>

4.  <% echo ("You may optionally use ASP-style tags"); %>
    <%= $variable; # This is a shortcut for "<%echo .." %>
      

The first way is only available if short tags have been enabled. This can be done via the short_tags() function, by enabling the short_open_tag configuration setting in the PHP config file, or by compiling PHP with the --enable-short-tags option to configure.

The fourth way is only available if ASP-style tags have been enabled using the asp_tags configuration setting.

Note: Support for ASP-style tags was added in 3.0.4.

The closing tag for the block will include the immediately trailing newline if one is present.


Instruction separation

Instructions are separated the same as in C or perl - terminate each statement with a semicolon.

The closing tag (?>) also implies the end of the statement, so the following are equivalent:

<?php
    echo "This is a test";
?>

<?php echo "This is a test" ?>
      


Comments

PHP supports 'C', 'C++' and Unix shell-style comments. For example:

<?php
    echo "This is a test"; // This is a one-line c++ style comment
    /* This is a multi line comment
       yet another line of comment */
    echo "This is yet another test";
    echo "One Final Test"; # This is shell-style style comment
?>
     

The "one-line" comment styles actually only comment to the end of the line or the current block of PHP code, whichever comes first.

<h1>This is an <?# echo "simple";?> example.</h1>
<p>The header above will say 'This is an example'.

You should be careful not to nest 'C' style comments, which can happen when commenting out large blocks.

<?php
 /* 
    echo "This is a test"; /* This comment will cause a problem */
 */
?>
    


Chapter 6. Types

PHP supports the following types:

The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.

If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.

Note that a variable may behave in different manners in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling.


Integers

Integers can be specified using any of the following syntaxes:

$a = 1234; # decimal number
$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x12; # hexadecimal number (equivalent to 18 decimal)
     

The size of an integer is platform-dependent, although a maximum value of about 2 billion is the usual value (that's 32 bits signed).


Floating point numbers

Floating point numbers ("doubles") can be specified using any of the following syntaxes:

 
$a = 1.234; $a = 1.2e3;
     

The size of a floating point number is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (that's 64 bit IEEE format).

Warning

It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999....

This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . ..

So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions instead.


Strings

Strings can be specified using one of two sets of delimiters.

If the string is enclosed in double-quotes ("), variables within the string will be expanded (subject to some parsing limitations). As in C and Perl, the backslash ("\") character can be used in specifying special characters:

Table 6-1. Escaped characters

sequence meaning
\n linefeed (LF or 0x0A in ASCII)
\r carriage return (CR or 0x0D in ASCII)
\t horizontal tab (HT or 0x09 in ASCII)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

You can escape any other character, but a warning will be issued at the highest warning level.

The second way to delimit a string uses the single-quote ("'") character. When a string is enclosed in single quotes, the only escapes that will be understood are "\\" and "\'". This is for convenience, so that you can have single-quotes and backslashes in a single-quoted string. Variables will not be expanded inside a single-quoted string.

Another way to delimit strings is by using here doc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation. The closing identifier must begin in the first column of the line.

Here doc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a here doc as with strings.