2007-03-26
Copyright © 1997-2007 the PHP Documentation Group
Copyright
Copyright © 1997 - 2007 by the PHP Documentation Group. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later. A copy of the Open Publication License is distributed with this manual, the latest version is presently available at http://www.opencontent.org/openpub/.
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.
In case you are interested in redistribution or republishing of this document in whole or in part, either modified or unmodified, and you have questions, please contact the copyright holders at doc-license@lists.php.net. Note that this address is mapped to a publicly archived mailing list.
The Chapter 46 section of the documentation is based on an initial contribution by Zend Technologies.
PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.
This manual consists primarily of a function reference, but also contains a language reference, explanations of some of PHP's major features, and other supplemental information.
You can download this manual in several formats at http://www.php.net/download-docs.php. More information about how this manual is developed can be found in the 'About the manual' appendix. If you are interested in the history of PHP, visit the relevant appendix.
We highlight the currently most active people on the manual frontpage, but there are many more contributors who currently help in our work or provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with their user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful for. All the lists provided below are in alphabetical order.
The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Yasuo Ohgaki, Derick Rethans, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar and Andrei Zmievski.
The following contributors have done significant work editing the manual: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe and Egon Schmid.
The currently most active maintainers are: Mehdi Achour, Friedhelm Betz, Vincent Gevers, Aidan Lister, Nuno Lopes and Tom Sommer.
These people have also put a lot of effort into managing user notes: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, James Cox, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Andrew Lindeman, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Jani Taskinen, Yasuo Ohgaki, Philip Olson, Lars Torben Wilson, Jim Winstead, Jared Wyles and Jeroen van Wolffelaar.
PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
Simple answer, but what does that mean? An example:
Notice how this is different from a 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 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.
The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.
Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.
There are three main areas where PHP scripts are used.
Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.
Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit its own website.
PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.
So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.
With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.
One of the strongest and most significant features 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:
We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.
Adabas D InterBase PostgreSQL dBase FrontBase SQLite Empress mSQL Solid FilePro (read-only) Direct MS-SQL Sybase Hyperwave MySQL Velocis IBM DB2 ODBC Unix dbm Informix Oracle (OCI7 and OCI8) Ingres Ovrimos
PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.
PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.
At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...
As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.
Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.
PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.
In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things. Most web hosts offer PHP support, but if your host does not, consider reading the PHP Links section for resources on finding PHP enabled web hosts.
Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as Apache, and of course PHP. You will most likely want to install a database as well, such as MySQL.
You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). In case you have problems with installing PHP yourself, we would suggest you ask your questions on our installation mailing list. If you choose to go on the simpler route, then locate a pre-configured package for your operating system, which automatically installs all of these with just a few mouse clicks. It is easy to setup a web server with PHP support on any operating system, including MacOSX, Linux and Windows. On Linux, you may find rpmfind and PBone helpful for locating RPMs. You may also want to visit apt-get to find packages for Debian.
Create a file named hello.php and put it
in your web server's root directory (DOCUMENT_ROOT)
with the following content:
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many PHP support options.
The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.
A Note on Line Feeds: Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.
A Note on Text Editors: There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.
A Note on Word Processors: Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.
A Note on Windows Notepad: If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.
Let us do something more useful now. We are going to check
what sort of browser the visitor is using.
For that, we check the user agent string the browser
sends as part of the HTTP request. This information is stored in a variable. Variables always start
with a dollar-sign in PHP. The variable we are interested in right now
is $_SERVER['HTTP_USER_AGENT'].
Note: $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP 4.1.0. Before this time, we used the older
$HTTP_*_VARSarrays instead, such as$HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)
To display this variable, you can simply do:
There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.
$_SERVER is just one variable that PHP automatically
makes available to you. A list can be seen in the
Reserved Variables section
of the manual or you can get a complete list of them by looking at
the output of the phpinfo() function used in the
example in the previous section.
You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:
Example 2-4. Example using control structures and functions
A sample output of this script may be:
|
Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual. You can find a list of PHP books at http://www.php.net/books.php.
The second concept we introduced was the strpos()
function call. strpos() is a function built into
PHP which searches a string for another string. In this case we are
looking for 'MSIE' (so-called needle) inside
$_SERVER['HTTP_USER_AGENT'] (so-called haystack). If
the needle is found inside the haystack, the function returns the position
of the needle relative to the start of the haystack. Otherwise, it
returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE
and the code within its {braces} is executed. Otherwise, the code is not
run. Feel free to create similar examples,
with if,
else, and other
functions such as strtoupper() and
strlen(). Each related manual page contains examples
too. If you are unsure how to use functions, you will want to read both
the manual page on how to read a
function definition and the section about
PHP functions.
We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:
Example 2-5. Mixing both HTML and PHP modes
A sample output of this script may be:
|
Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.
One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from outside of PHP for more information and examples on using forms with PHP. Here is an example HTML form:
There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:
Apart from the htmlspecialchars() and
(int) parts, it should be obvious what this does.
htmlspecialchars() makes sure any characters that are
special in html are properly encoded so people can't inject HTML tags
or Javascript into your page. For the age field, since we know it is a
number, we can just convert
it to an integer which will automatically get rid of any
stray characters. You can also have PHP do this for you automatically by
using the filter extension.
The $_POST['name'] and $_POST['age']
variables are automatically set for you by PHP. Earlier we
used the $_SERVER superglobal; above we just
introduced the $_POST
superglobal which contains all POST data. Notice how the
method of our form is POST. If we used the
method GET then our form information would live in
the $_GET superglobal instead.
You may also use the $_REQUEST
superglobal, if you do not care about the source of your request data. It
contains the merged information of GET, POST and COOKIE data. Also see the
import_request_variables() function.
You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.
Now that PHP has grown to be a popular scripting language, there are a lot of public repositories and libraries containing code you can reuse. The PHP developers have largely tried to preserve backwards compatibility, so a script written for an older version will run (ideally) without changes in a newer version of PHP. In practice, some changes will usually be needed.
Two of the most important recent changes that affect old code are:
The deprecation of the old $HTTP_*_VARS arrays
(which need to be indicated as global when used inside a function or
method). The following
superglobal arrays
were introduced in PHP 4.1.0.
They are: $_GET, $_POST,
$_COOKIE, $_SERVER,
$_FILES, $_ENV,
$_REQUEST, and $_SESSION. The
older $HTTP_*_VARS arrays, such as
$HTTP_POST_VARS, still exist as they have since PHP 3.
As of PHP 5.0.0, the long PHP
predefined variable
arrays may be disabled with the
register_long_arrays
directive.
External variables are no longer registered in the global scope by
default. In other words, as of PHP
4.2.0 the PHP directive
register_globals is
off by default in php.ini. The preferred
method of accessing these values is via the superglobal arrays mentioned
above. Older scripts, books, and tutorials may rely on this
directive being on. If it were on, for example, one could use
$id from the URL
http://www.example.com/foo.php?id=42. Whether on
or off, $_GET['id'] is available.
With your new knowledge you should be able to understand most of the manual and also the various example scripts available in the example archives. You can also find other examples on the php.net websites in the links section: http://www.php.net/links.php.
To view various slide presentations that show more of what PHP can do, see the PHP Conference Material Sites: http://conf.php.net/ and http://talks.php.net/
Before starting the installation, first you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:
Websites and web applications (server-side scripting)
Command line scripting
Desktop (GUI) applications
For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and MacOS X; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.
In case of setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.
If you are also interested to use PHP for command line scripting (e.g. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.
With PHP you can also write desktop GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage Windows and objects within them. For more information about PHP-GTK, please visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.
From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.
PHP source code and binary distributions for Windows can be found at http://www.php.net/downloads.php. We recommend you to choose a mirror nearest to you for downloading the distributions.
This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.
As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.
There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.
Prerequisite knowledge and software for compiling:
Basic Unix skills (being able to operate "make" and a C compiler)
An ANSI C compiler
flex: Version 2.5.4
bison: Version 1.28 (preferred), 1.35, or 1.75
A web server
Any module specific components (such as gd, pdf libs, etc.)
The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.
When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.
You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.
Example 4-1. Installation Instructions (Apache Shared Module Version) for PHP
|
Alternatively, to install PHP as a static object:
Example 4-2. Installation Instructions (Static Module Installation for Apache) for PHP
|
Note: Replace php-5 by php-4 and php5 by php4 in PHP 4.
Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.
Example 4-3. Example commands for restarting Apache
|
The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.
Different examples of compiling PHP for apache are as follows:
This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.
This will 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.
This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). 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.
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 either the php.ini file or directly using dl().
When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache web page on DSO support.
Note: Apache's default httpd.conf currently ships with a section that looks like this:
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.
Note: Make sure you specify the installed version of apxs when using
--with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.
This section contains notes and hints specific to Apache 2.0 installs of PHP on Unix systems.
| Warning |
We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the related FAQ entry on using Apache2 with a threaded MPM |
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0 Server.
PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at http://www.php.net/downloads.php.
- the latest stable development version. Get the source code http://snaps.php.net/php5-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php5-win32-latest.zip.
- a prerelease version downloadable from http://qa.php.net/.
- you have always the option to obtain PHP through anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.
Download the most recent version of Apache 2.0 and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.0 and PHP. For more information read the Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'NN' here with the correct values from your files.
Example 4-4. Installation Instructions (Apache 2 Shared Module Version)
|
Following the steps above you will have a running Apache 2.0 with
support for PHP as SAPI module.
Of course there are many more configuration options available for both,
Apache and PHP. For more information use
./configure --help in the corresponding source
tree. In case you wish to build a multithreaded version of Apache 2.0
you must overwrite the standard MPM-Module prefork
either with worker or perchild.
To do so append to your configure line in step 6 above either the option
--with-mpm=worker or
--with-mpm=perchild. Take care about
the consequences and understand what you are doing. For more information
read the Apache documentation about the
MPM-Modules.
Note: If you want to use content negotiation, read the Apache MultiViews FAQ.
Note: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.
PHP 4 can be built as a Pike module for the Caudium webserver. Note that this is not supported with PHP 3. Follow the simple instructions below to install PHP 4 for Caudium.
Example 4-5. Caudium Installation Instructions
|
You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.
Note: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the
--with-mysqloption.
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.
Note: Support for fhttpd is no longer available as of PHP 4.3.0.
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.
You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: http://benoit.noss.free.fr/php/install-php4.html
To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.
Install the following packages from http://www.sunfreeware.com/ or another download site:
| autoconf-2.13 |
| automake-1.4 |
| bison-1_25-sol26-sparc-local |
| flex-2_5_4a-sol26-sparc-local |
| gcc-2_95_2-sol26-sparc-local |
| gzip-1.2.4-sol26-sparc-local |
| m4-1_4-sol26-sparc-local |
| make-3_76_1-sol26-sparc-local |
| mysql-3.23.24-beta (if you want mysql support) |
| perl-5_005_03-sol26-sparc-local |
| tar-1.13 (GNU tar) |
Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
tar xvf php-x.x.x.tar
Change to your extracted PHP directory: cd ../php-x.x.x
For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc |
Run make followed by make install.
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Configuration Instructions for Sun/iPlanet/Netscape.
Firstly you may need to add some paths to the LD_LIBRARY_PATH
environment for the server to find all the shared libs. This can best done
in the start script for your web server. The start script is often located
in: /path/to/server/https-servername/start.
You may also need to edit the configuration files that are
located in: /path/to/server/https-servername/config/.
Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php |
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"] |
Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):
<Object name="default"> . . . .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] . . </Object> |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object> |
To use PHP Authentication on a single directory, add the following:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object> |
Note: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!
Note: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Note: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
The default is to build PHP as a CGI program. This creates a command line interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. 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 users to run different PHP-enabled pages under different user-ids.
| Warning |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.
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.
If you have built PHP 3 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.
Note: make bench is only available for PHP 3.
Some server supplied
environment variables are not defined in the
current CGI/1.1 specification.
Only the following variables are defined there: AUTH_TYPE,
CONTENT_LENGTH, CONTENT_TYPE,
GATEWAY_INTERFACE, PATH_INFO,
PATH_TRANSLATED, QUERY_STRING,
REMOTE_ADDR, REMOTE_HOST,
REMOTE_IDENT, REMOTE_USER,
REQUEST_METHOD, SCRIPT_NAME,
SERVER_NAME, SERVER_PORT,
SERVER_PROTOCOL, and SERVER_SOFTWARE.
Everything else should be treated as 'vendor extensions'.
This section contains notes and hints specific to installing PHP on HP-UX systems.
There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.
Official pre-compiled packages are located here: http://software.hp.com/
Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: Building Apache and PHP on HP-UX 11.11
This section contains notes and hints specific to installing PHP on OpenBSD 3.6.
Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.
The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.
Example 4-6. OpenBSD Package Install Example
|
Read the packages(7) manual page for more information about binary packages on OpenBSD.
You can also compile up PHP from source using the ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.
The default install of Apache runs inside a chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the OpenBSD FAQ.
The OpenBSD 3.6 package for the gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.
Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).
This section contains notes and hints specific to installing PHP on Solaris systems.
Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:
gcc (recommended, other C compilers may work)
make
flex
bison
m4
autoconf
automake
perl
gzip
tar
GNU sed
You can simplify the Solaris install process by using pkgadd to install most of your needed components.
This section contains notes and hints specific to installing PHP on Debian GNU/Linux.
While you can just download the PHP source and compile it yourself, using Debian's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.
The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. The corresponding PHP packages are respectively named libapache-mod-php* and libapache2-mod-php*. The steps given below will use Apache 1.3.x. Please note that, as of this writing, there is no official Debian packages of PHP 5. Then the steps given below will install PHP 4.
PHP is available in Debian as CGI or CLI flavour too, named respectively php4-cgi and php4-cli. If you need them, you'll just have to reproduce the following steps with the good package names. Another special package you'd want to install is php4-pear. It contains a minimal PEAR installation and the pear commandline utility.
If you need more recent packages of PHP than the Debian's stable ones or if some PHP modules lacks the Debian official repository, perhaps you should take a look at http://www.apt-get.org/. One of the results found should be Dotdeb. This unofficial repository is maintained by Guillaume Plessis and contains Debian packages of the most recent versions of PHP 4 and PHP 5. To use it, just add the to following two lines to your /etc/apt/sources.lists and run apt-get update :
The last thing to consider is whether your list of packages is up to date. If you have not updated it recently, you need to run apt-get update before anything else. This way, you will be using the most recent stable version of the Apache and PHP packages.
Now that everything is in place, you can use the following example to install Apache and PHP:
APT will automatically install the PHP 4 module for Apache 1.3, and all its dependencies and then activate it. If you're not asked to restart Apache during the install process, you'll have to do it manually :
In the last section, PHP was installed with only core modules. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, cURL, GD, etc.
When you compile PHP from source yourself, you need to activate modules via the configure command. With APT, you just have to install additional packages. They're all named 'php4-*' (or 'php5-*' if you installed PHP 5 from a third party repository).
As you can see from the last output, there's a lot of PHP modules that you can install (excluding the php4-cgi, php4-cli or php4-pear special packages). Look at them closely and choose what you need. If you choose a module and you do not have the proper libraries, APT will automatically install all the dependencies for you.
If you choose to add the MySQL, cURL and GD support to PHP the command will look something like this:
APT will automatically add the appropriate lines to your different php.ini (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, etc).
You'll only have to stop/start Apache as previously to activate the modules.
If you see the PHP source instead of the result the script should produce, APT has probably not included /etc/apache/conf.d/php4 in your Apache 1.3 configuration. Please ensure that the following line is present in your /etc/apache/httpd.conf file then stop/start Apache:
If you installed an additional module and if its functions are not available in your scripts, please ensure that the appropriate line is present in your php.ini, as seen before. APT may fail during the installation of the additional module, due to a confusing debconf configuration.
This section contains notes and hints specific to installing PHP on Mac OS X. There are two slightly different versions of Mac OS X, Client and Server, our manual deals with installing PHP on both systems. Note that PHP is not available for MacOS 9 and earlier versions.
There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.
The following resources offer easy to install packages and precompiled binaries for PHP on Mac OS:
PHP has come standard with Macs since OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).
Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate MAC OS X installation documentation for further details. The following instructions are geared towards a beginner with details provided for getting a default setup to work. All users are encouraged to compile, or install a new packaged version.
The standard installation type is using mod_php, and enabling the bundled mod_php on Mac OS X for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:
Locate and open the Apache configuration file. By default, the location is as follows: /etc/httpd/httpd.conf
Using Finder or Spotlight to find this file may prove difficult as by default it's private and owned by the root user.
Note: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /etc/httpd/httpd.conf
Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.
With a text editor, uncomment the lines (by removing the #) that look similar to the following (these two lines are often not together, locate them both in the file):
# LoadModule php4_module libexec/httpd/libphp4.so # AddModule mod_php4.c |
Be sure the desired extensions will parse as PHP (examples: .php .html and .inc)
Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.
<IfModule mod_php4.c>
# If php is turned on, we respect .php and .phps files.
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
# Since most users will want index.php to work we
# also automatically enable index.php
<IfModule mod_dir.c>
DirectoryIndex index.html index.php
</IfModule>
</IfModule> |
Be sure the DirectoryIndex loads the desired default index file
This is also set in httpd.conf. Typically index.php and index.html are used. By default index.php is enabled because it's also in the PHP check shown above. Adjust accordingly.
Set the php.ini location or use the default
A typical default location on Mac OS X is /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used, PHP will use all default values. See also the related FAQ on finding php.ini.
Locate or set the DocumentRoot
This is the root directory for all the web files. Files in this directory are served from the web server so the PHP files will parse as PHP before outputting them to the browser. A typical default path is /Library/WebServer/Documents but this can be set to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is /Users/yourusername/Sites
Create a phpinfo() file
The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:
<?php phpinfo(); ?> |
Restart Apache, and load the PHP file created above
To restart, either execute sudo apachectl graceful in the shell or stop/start the "Personal Web Server" option in the OS X System Preferences. By default, loading local files in the browser will have an URL like so: http://localhost/info.php Or using the DocumentRoot in the user directory is another option and would end up looking like: http://localhost/~yourusername/info.php
The CLI (or CGI in older versions) is appropriately named php and likely exists as /usr/bin/php. Open up the terminal, read the command line section of the PHP manual, and execute php -v to check the PHP version of this PHP binary. A call to phpinfo() will also reveal this information.
Get the latest distributions of Apache and PHP.
Untar them, and run the configure program on Apache like so.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache |
If you want the compiler to do some optimization, you may also want to add this line:
setenv OPTIM=-O2 |
Next, go to the PHP 4 source directory and configure it.
./configure --prefix=/usr \
--sysconfdir=/etc \
--localstatedir=/var \
--mandir=/usr/share/man \
--with-xml \
--with-apache=/src/apache_1.3.12 |
--with-apache string, put
in the path to your apache source directory, for example
/src/apache_1.3.12.
Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.
Now, reconfigure Apache to build in PHP 4.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache \ --activate-module=src/modules/php4/libphp4.a |
Copy and rename the php.ini-dist file to your bin directory from your PHP 4 source directory: cp php.ini-dist /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-dist /usr/bin/php.ini.
The following instructions will help you install a PHP module for the Apache web server included in MacOS X. This version includes support for the MySQL and PostgreSQL databases. These instructions are graciously provided by Marc Liyanage.
| Warning |
Be careful when you do this, you could screw up your Apache web server! |
Do this to install:
Open a terminal window.
Type wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz, wait for the download to finish.
Type gunzip libphp4.so.gz.
Type sudo apxs -i -a -n php4 libphp4.so
Now type sudo open -a TextEdit /etc/httpd/httpd.conf. TextEdit will open with the web server configuration file. Locate these two lines towards the end of the file: (Use the Find command)
#AddType application/x-httpd-php .php #AddType application/x-httpd-php-source .phps |
Finally, type sudo apachectl graceful to restart the web server.
PHP should now be up and running. You can test it by dropping a file into your Sites folder which is called test.php. Into that file, write this line: <?php phpinfo() ?>.
Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with information about the PHP module.
This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32. Windows 95 is no longer supported as of PHP 4.3.0.
There are two main ways to install PHP for Windows: either manually or by using the installer.
If you have Microsoft Visual Studio, you can also build PHP from the original source code.
Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.
| Warning |
There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we believe that the manual installation is the best choice to have your system secure and optimised. |
The Windows PHP installer for later versions of PHP is built using MSI technology using the Wix Toolkit (http://wix.sourceforge.net/). It will install and configure PHP and all the built-in and PECL extensions, as well as configure many of the popular web servers such as IIS, Apache, and Xitami.
First, install your selected HTTP (web) server on your system, and make sure that it works. Then proceed with one of the following install types.
Run the MSI installer and follow the instructions provided by the installation wizard. You will be prompted to select the Web Server you wish to configure first, along with any configuration details needed.
You will then be prompted to select which features and extensions you wish to install and enable. By selecting "Will be installed on local hard drive" in the drop-down menu for each item you can trigger whether to install the feature or not. By selecting "Entire feature will be installed on local hard drive", you will be able to install all sub-features of the included feature ( for example by selecting this options for the feature "PDO" you will install all PDO Drivers ).
| Warning |
It is not recommended to install all extensions by default, since many other them require dependencies from outside PHP in order to function properly. Instead, use the Installation Repair Mode that can be triggered thru the 'Add/Remove Programs' control panel to enable or disable extensions and features after installation. |
The installer then sets up PHP to be used in Windows and the php.ini file, and configures certain web servers to use PHP. The installer will currently configure IIS (CGI mode only), Apache, Xitami, and Sambar Server; if you are using a different web server you'll need to configure it manually.
The installer also supports a silent mode, which is helpful for Systems Administrators to deploy PHP easily. To use silent mode:
msiexec.exe /i php-VERSION-win32-install.msi /q |
You can control the install directory by passing it as a parameter to the install. For example, to install to e:\php:
msiexec.exe /i php-VERSION-win32-install.msi /q INSTALLDIR=e:\php |
You can also specify what features to install. For example, to install the mysqli extension and the CGI executable:
msiexec.exe /i php-VERSION-win32-install.msi /q ADDLOCAL=cgi,ext_php_mysqli |
The current list of Features to install is as follows:
MainExecutable - php.exe executable ScriptExecutable - php-win.exe executable ext_php_* - the various extensions ( for example: ext_php_mysql for MySQL ) apache13 - Apache 1.3 module apache20 - Apache 2.0 module apache22 - Apache 2,2 module apacheCGI - Apache CGI executable iis4ISAPI - IIS ISAPI module iis4CGI - IIS CGI executable NSAPI - Sun/iPlanet/Netscape server module Xitami - Xitami CGI executable Sambar - Sambar Server ISAPI module CGI - php-cgi.exe executable PEAR - PEAR installer Manual - PHP Manual in CHM Format |
For more information on installing MSI installers from the command line, visit http://msdn.microsoft.com/library/en-us/msi/setup/command_line_options.asp
The Windows PHP installer is available from the downloads page at http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.
Note: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.
First, install your selected HTTP (web) server on your system, and make sure that it works.
Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.
The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.
Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.
| Warning |
Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better go on the manual way, and set every option carefully. This automatically working setup gives you an instantly working PHP installation, but it is not meant to be used on online servers. |
This install guide will help you manually install and configure PHP with a web server on Microsoft Windows. To get started you'll need to download the zip binary distribution from the downloads page at http://www.php.net/downloads.php.
Although there are many all-in-one installation kits, and we also distribute a PHP installer for Microsoft Windows, we recommend you take the time to setup PHP yourself as this will provide you with a better understanding of the system, and enables you to install PHP extensions easily when needed.
Upgrading from a previous PHP version: Previous editions of the manual suggest moving various ini and DLL files into your SYSTEM (i.e. C:\WINDOWS) folder and while this simplifies the installation procedure it makes upgrading difficult. We advise you remove all of these files (like php.ini and PHP related DLLs from the Windows SYSTEM folder) before moving on with a new PHP installation. Be sure to backup these files as you might break the entire system. The old php.ini might be useful in setting up the new PHP as well. And as you'll soon learn, the preferred method for installing PHP is to keep all PHP related files in one directory and have this directory available to your systems PATH.
MDAC requirements: If you use Microsoft Windows 98/NT4 download the latest version of the Microsoft Data Access Components (MDAC) for your platform. MDAC is available at http://msdn.microsoft.com/data/. This requirement exists because ODBC is built into the distributed Windows binaries.
The following steps should be completed on all installations before any server specific instructions are performed:
Extract the distribution file into a directory of your choice. If you are installing PHP 4, extract to C:\, as the zip file expands to a foldername like php-4.3.7-Win32. If you are installing PHP 5, extract to C:\php as the zip file doesn't expand as in PHP 4. You may choose a different location but do not have spaces in the path (like C:\Program Files\PHP) as some web servers will crash if you do.
The directory structure extracted from the zip is different for PHP versions 4 and 5 and look like as follows:
Example 6-1. PHP 4 package structure
|
Or:
Example 6-2. PHP 5 package structure
|
Notice the differences and similarities. Both PHP 4 and PHP 5 have a CGI executable, a CLI executable, and server modules, but they are located in different folders and/or have different names. While PHP 4 packages have the server modules in the sapi folder, PHP 5 distributions have no such directory and instead they're in the PHP folder root. The supporting DLLs for the PHP 5 extensions are also not in a seperate directory.
Note: In PHP 4, you should move all files located in the dll and sapi folders to the main folder (e.g. C:\php).
Here is a list of server modules shipped with PHP 4 and PHP 5:
sapi/php4activescript.dll (php5activescript.dll) - ActiveScript engine, allowing you to embed PHP in your Windows applications.
sapi/php4apache.dll (php5apache.dll) - Apache 1.3.x module.
sapi/php4apache2.dll (php5apache2.dll) - Apache 2.0.x module.
sapi/php5apache2_2.dll - Apache 2.2.x module.
sapi/php4isapi.dll (php5isapi.dll) - ISAPI Module for ISAPI compliant web servers like IIS 4.0/PWS 4.0 or newer.
sapi/php4nsapi.dll (php5nsapi.dll) - Sun/iPlanet/Netscape server module.
sapi/php4pi3web.dll (no equivalent in PHP 5) - Pi3Web server module.
Server modules provide significantly better performance and additional functionality compared to the CGI binary. The CLI version is designed to let you use PHP for command line scripting. More information about CLI is available in the chapter about using PHP from the command line.
| Warning |
The SAPI modules have been significantly improved as of the 4.1 release, however, in older systems you may encounter server errors or other server modules failing, such as ASP. |
The CGI and CLI binaries, and the web server modules all require the php4ts.dll (php5ts.dll) file to be available to them. You have to make sure that this file can be found by your PHP installation. The search order for this DLL is as follows:
The same directory from where php.exe is called, or in case you use a SAPI module, the web server's directory (e.g. C:\Program Files\Apache Group\Apache2\bin).
Any directory in your Windows PATH environment
variable.
To make php4ts.dll / php5ts.dll
available you have three options: copy the file to the Windows system
directory, copy the file to the web server's directory, or add your PHP
directory, C:\php to the
PATH. For better maintenance, we advise you to follow
the last option, add C:\php to the
PATH, because it will be simpler to upgrade PHP in the
future. Read more about how to add your PHP directory to
PATH in the corresponding FAQ entry (and
then don't forget to restart the computer - logoff isn't enough).
The next step is to set up a valid configuration file for PHP, php.ini. There are two ini files distributed in the zip file, php.ini-dist and php.ini-recommended. We advise you to use php.ini-recommended, because we optimized the default settings in this file for performance, and security. Read this well documented file carefully because it has changes from php.ini-dist that will drastically affect your setup. Some examples are display_errors being off and magic_quotes_gpc being off. In addition to reading these, study the ini settings and set every element manually yourself. If you would like to achieve the best security, then this is the way for you, although PHP works fine with these default ini files. Copy your chosen ini-file to a directory that PHP is able to find and rename it to php.ini. PHP searches for php.ini in the locations described in the Section called The configuration file in Chapter 9 section.
If you are running Apache 2, the simpler option is to use the PHPIniDir
directive (read the installation
on Apache 2 page), otherwise your best option is to set the
PHPRC environment variable. This process is explained
in the following FAQ entry.
Note: If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your php.ini (e.g. make it readable by Everyone).
The following steps are optional:
Edit your new php.ini file. If you plan to use OmniHTTPd, do not follow the next step. Set the doc_root to point to your web servers document_root. For example:
Choose the extensions you would like to load when PHP starts. See the section about Windows extensions, about how to set up one, and what is already built in. Note that on a new installation it is advisable to first get PHP working and tested without any extensions before enabling them in php.ini.
On PWS and IIS, you can set the browscap configuration setting to point to: c:\windows\system\inetsrv\browscap.ini on Windows 9x/Me, c:\winnt\system32\inetsrv\browscap.ini on NT/2000, and c:\windows\system32\inetsrv\browscap.ini on XP. For an up-to-date browscap.ini, read the following FAQ.
PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.
This section contains notes specific to the ActiveScript installation.
ActiveScript is a Windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.
As of PHP 5.0.1, ActiveScript has been moved to the PECL repository. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/
Note: You should read the manual installation steps first!
After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).
After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.
To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:
<job id="test">
<script language="PHPScript">
$WScript->Echo("Hello World!");
</script>
</job> |
Note: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.
Note: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.
This section contains notes and hints specific to IIS (Microsoft Internet Information Server).
| Warning |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
First, read the Manual Installation Instructions. Do not skip this step as it provides crucial information for installing PHP on Windows.
CGI users must set the cgi.force_redirect PHP directive to 0 inside php.ini. Read the faq on cgi.force_redirect for important details. Also, CGI users may want to set the cgi.redirect_status_env directive. When using directives, be sure these directives aren't commented out inside php.ini.
The PHP 4 CGI is named php.exe while in PHP 5 it's php-cgi.exe. In PHP 5, php.exe is the CLI, and not the CGI.
Modify the Windows PATH environment variable to include the PHP directory. This way the PHP DLL files and PHP executables can all remain in the PHP directory without cluttering up the Windows system directory. For more details, see the FAQ on Setting the PATH.
The IIS user (usually IUSR_MACHINENAME) needs permission to read various files and directories, such as php.ini, docroot, and the session tmp directory.
Be sure the extension_dir and doc_root PHP directives are appropriately set in php.ini. These directives depend on the system that PHP is being installed on. In PHP 4, the extension_dir is extensions while with PHP 5 it's ext. So, an example PHP 5 extensions_dir value is "c:\php\ext" and an example IIS doc_root value is "c:\Inetpub\wwwroot".
PHP extension DLL files, such as php_mysql.dll and php_curl.dll, are found in the zip package of the PHP download (not the PHP installer). In PHP 5, many extensions are part of PECL and can be downloaded in the "Collection of PECL modules" package. Files such as php_zip.dll and php_ssh2.dll. Download PHP files here.
When defining the executable, the 'check that file exists' box may also be checked. For a small performance penalty, the IIS (or PWS) will check that the script file exists and sort out authentication before firing up PHP. This means that the web server will provide sensible 404 style error messages instead of CGI errors complaining that PHP did not output any data.
PHP may be installed as a CGI binary, or with the ISAPI module. In either case, you need to start the Microsoft Management Console (may appear as 'Internet Services Manager', either in your Windows NT 4.0 Option Pack branch or the Control Panel=>Administrative Tools under Windows 2000/XP). Then right click on your Web server node (this will most probably appear as 'Default Web Server'), and select 'Properties'.
If you want to use the CGI binary, do the following:
Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
Change the Execute Permissions to 'Scripts only'
Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate CGI file. An example PHP 5 value is: C:\php\php-cgi.exe Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
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 / php-cgi.exe.
To use the ISAPI module, do the following:
If you don't want to perform HTTP Authentication using PHP, you can (and should) skip this step. Under ISAPI Filters, add a new ISAPI filter. Use PHP as the filter name, and supply a path to the php4isapi.dll / php5isapi.dll.
Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
Change the Execute Permissions to 'Scripts only'
Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate ISAPI DLL. An example PHP 5 value is: C:\php\php5isapi.dll Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
Stop IIS completely (NET STOP iisadmin)
Start IIS again (NET START w3svc)
With IIS 6 (2003 Server), open up the IIS Manager, go to Web Service Extensions, choose "Add a new Web service extension", enter in a name such as PHP, choose the Add button and for the value browse to either the ISAPI file (php4isapi.dll or php5isapi.dll) or CGI (php.exe or php-cgi.exe) then check "Set extension status to Allowed" and click OK.
In order to use index.php as a default content page, do the following: From within the Documents tab, choose Add. Type in index.php and click OK. Adjust the order by choosing Move Up or Move Down. This is similar to setting DirectoryIndex with Apache.
The steps above must be repeated for each extension that is to be associated with PHP scripts. .php is the most common although .php3 may be required for legacy applications.
If you experience 100% CPU usage after some time, turn off the IIS setting Cache ISAPI Application.
PWS 4 does not support ISAPI, only PHP CGI should be used.
Edit the enclosed pws-php4cgi.reg / pws-php5cgi.reg file (look into the SAPI folder for PHP 4, or in the main folder for PHP 5) to reflect the location of your php.exe / php-cgi.exe. Backslashes should be escaped, for example: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="C:\\php\\php.exe" (change to C:\\php\\php-cgi.exe if you are using PHP 5) Now merge this registery file into your system; you may do this by double-clicking it.
In the PWS Manager, right click on a given directory you want to add PHP support to, and select Properties. Check the 'Execute' checkbox, and confirm.
The recommended method for configuring these servers is to use the REG file included with the distribution (pws-php4cgi.reg in the SAPI folder for PHP 4, or pws-php5cgi.reg in the main folder for PHP 5). 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. For example .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 for PHP 4, or C:\php\php-cgi.exe "%s" %s for PHP 5.
Repeat these steps for each extension you wish to associate with PHP scripts.
The following steps do not affect the web server installation and only apply if you want your PHP scripts to be executed when they are run from the command line (ex. run C:\myscripts\test.php) or by double clicking on them in a directory viewer window. You may wish to skip these steps as you might prefer the PHP files to load into a text editor when you double click on them.
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.
If using PWS on Windows, reboot to reload the registry.
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.
This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.
Note: Please read the manual installation steps first!
There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.
It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.
Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.
After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.
Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext. A trailing slash may also be necessary for directories.
You should add the following lines to your Apache httpd.conf file:
Example 6-3. PHP as an Apache 1.3.x module This assumes PHP is installed to c:\php. Adjust the path if this is not the case. For PHP 4:
For PHP 5:
For both:
|
If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:
| Warning |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.
This section contains notes and hints specific to Apache 2.0.x installs of PHP on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.
Note: You should read the manual installation steps first!
Apache 2.2.x Support: Users of Apache 2.2.x may use the documentation below except the appropriate DLL file is named php5apache2_2.dll and it only exists as of PHP 5.2.0. See also http://snaps.php.net/
| Warning |
We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the related FAQ entry on using Apache2 with a threaded MPM |
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0.x Server. Also consider to read the Windows specific notes for Apache 2.0.x before reading on here.
PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at http://www.php.net/downloads.php.
- the latest stable development version. Get the source code http://snaps.php.net/php5-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php5-win32-latest.zip.
- a prerelease version downloadable from http://qa.php.net/.
- you have always the option to obtain PHP through anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.
| Warning |
Apache 2.0.x is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0.x is not expected to work on those platforms at this time. |
Download the most recent version of Apache 2.0.x and a fitting PHP version. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.
There are two ways to set up PHP to work with Apache 2.0.x on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP and then restart the server.
Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext. A trailing slash may also be necessary for directories.
You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:
| Warning |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP module for Apache 2.0:
Example 6-6. PHP and Apache 2.0 as Module
|
Note: Remember to substitute your actual path to PHP for the c:/php/ in the above examples. Take care to use either php4apache2.dll or php5apache2.dll in your LoadModule directive and not php4apache.dll or php5apache.dll as the latter ones are designed to run with Apache 1.3.x.
Note: If you want to use content negotiation, read related FAQ.
| Warning |
Don't mix up your installation with DLL files from different PHP versions. You have the only choice to use the DLL's and extensions that ship with your downloaded PHP version. |
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.
To install PHP as a CGI handler, do the following:
Copy php4ts.dll to your systemroot (the directory where you installed Windows)
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %* |
In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
Do it for each web server instance you want PHP to run
More details about setting up PHP as a CGI executable can be found here: http://benoit.noss.free.fr/php/install-php.html
To install PHP with NSAPI, do the following:
Copy php4ts.dll to your systemroot (the directory where you installed Windows)
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %* |
In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php).
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll" Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"] |
Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:
Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Restart your web service and apply changes
Do it for each web server instance you want PHP to run
Note: More details about setting up PHP as an NSAPI filter can be found here: http://benoit.noss.free.fr/php/install-php4.html
Note: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!
Note: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.
Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.
If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:
Init fn=php4_init ... server_lib="ns-httpdXX.dll" |
You can check the status by using the phpinfo() function.
Note: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
This section contains notes and hints specific to OmniHTTPd on Windows.
Note: You should read the manual installation steps first!
| Warning |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.
Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.
Install OmniHTTPd server.
Right click on the blue OmniHTTPd icon in the system tray and select Properties
Click on Web Server Global Settings
On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button.
On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.
Click OK
Repeat steps 2 - 6 for each extension you want to associate with PHP.
Note: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.
This section contains notes and hints specific to the Sambar Server for Windows.
Note: You should read the manual installation steps first!
This list describes how to set up the ISAPI module to work with the Sambar server on Windows.
Find the file called mappings.ini (in the config directory) in the Sambar install directory.
Open mappings.ini and add the following line under [ISAPI]:
Now restart the Sambar server for the changes to take effect.
Note: If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.
This section contains notes and hints specific to Xitami on Windows.
Note: You should read the manual installation steps first!
This list describes how to set up the PHP CGI binary to work with Xitami on Windows.
Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.
| Warning |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
Make sure the web server is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.
Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).
In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.
Press the 'Save' icon.
Restart the server to reflect changes.
This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Chapter 4.
To compile and build PHP you need a Microsoft Development Environment. Microsoft Visual C++ 6.0 is recommended, though Visual C++ .NET versions will also work. Since PHP 5 the free Microsoft .NET toolchain is also supported (you need to install Windows Platform SDK, Visual C++ Toolkit and .NET Framework SDK).
To extract the downloaded files you will also need a ZIP extraction utility. Windows XP and newer already include this functionality built-in.
Before you get started, you have to download:
the win32 buildtools from the PHP site at http://www.php.net/extra/win32build.zip.
the source code for the DNS name resolver used by PHP from http://www.php.net/extra/bindlib_w32.zip. This is a replacement for the resolv.lib library included in win32build.zip.
If you plan to compile PHP as a Apache module you will also need the Apache sources.
Finally, you are going to need the source to PHP itself. You can get the latest development version using anonymous CVS, a snapshot or the most recent released source tarball.
After downloading the required packages you have to extract them in a proper place:
Create a working directory where all files end up after extracting, e.g: C:\work.
Create the directory win32build under your working directory (C:\work) and unzip win32build.zip into it.
Create the directory bindlib_w32 under your working directory (C:\work) and unzip bindlib_w32.zip into it.
Extract the downloaded PHP source code into your working directory (C:\work).
Build the libraries you are going to need (or download the binaries if available) and place the headers and libs in the C:\work\win32build\include and C:\work\win32build\lib directories, respectively.
If you don't have cygwin installed with bison and flex, you also need to make the C:\work\win32build\bin directory available in the PATH, so that thoses tools can be found by the configure script.
+--C:\work | | | +--bindlib_w32 | | | | | +--arpa | | | | | +--conf | | | | | +--... | | | +--php-5.x.x | | | | | +--build | | | | | +--... | | | | | +--win32 | | | | | +--... | | | +--win32build | | | | | +--bin | | | | | +--include | | | | | +--lib |
If you aren't using Cygwin, you must also create the directories C:\usr\local\lib and then copy bison.simple from C:\work\win32build\bin to C:\usr\local\lib.
Note: If you want to use PEAR and the comfortable command line installer, the CLI-SAPI is mandatory. For more information about PEAR and the installer read the documentation at the PEAR website.
You must build the resolv.lib library. Decide whether you want to have debug symbols available (bindlib - Win32 Debug) or not (bindlib - Win32 Release), but please remember the choice you made, because the debug build will only link with PHP when it is also built in debug mode. Build the appropriate configuration:
For GUI users, launch VC++, by double-clicking in C:\work\bindlib_w32\bindlib.dsw. Then select Build=>Rebuild All.
For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands:
msdev bindlib.dsp /MAKE "bindlib - Win32 Debug"
msdev bindlib.dsp /MAKE "bindlib - Win32 Release"
This chapter explains how to compile PHP >=5 using the new build system, which is CLI-based and very similar with the main PHP's Unix build system.
Note: This build system isn't available in PHP 4. Please refer to the Section called Building PHP using DSW files [PHP 4] instead.
Before starting, be sure you have read the Section called Putting it all together and you have built all needed libraries, like Libxml or ICU (needed for PHP >= 6).
First you should open a Visual Studio Command Prompt, which should be available under the Start menu. A regular Command Prompt window shouldn't work, as probably it doesn't have the necessary environment variables set. Then type something like cd C:\work\php-5.x.x to enter in the PHP source dir. Now you are ready to start configuring PHP.
The second step is running the buildconf batch file to make the configure script, by scanning the folder for config.w32 files. By default this command will also search in the following directories: pecl; ..\pecl; pecl\rpc; ..\pecl\rpc. Since PHP 5.1.0, you can change this behaviour by using the --add-modules-dir argument (e.g. cscript /nologo win32/build/buildconf.js --add-modules-dir=../php-gtk2 --add-modules-dir=../pecl).
The third step is configuring. To view the list of the available configuration options type cscript /nologo configure.js --help. After choosing the options that you will enable/disable, type something like: cscript /nologo configure.js --disable-foo --enable-fun-ext. Using --enable-foo=shared will attempt to build the 'foo' extension as a shared, dynamically loadable module.
The last step is compiling. To achieve this just issue the command nmake. The generated files (e.g. .exe and .dll) will be placed in either Release_TS or Debug_TS directories (if built with Thread safety), or in the Release or Debug directories otherwise.
Optionally you may also run PHP's test suite, by typing nmake test. If you want to run just a specific test, you may use the 'TESTS' variable (e.g. nmake /D TESTS=ext/sqlite/tests test - will only run sqlite's tests). To delete the files that were created during the compilation, you can use the nmake clean command.
A very useful configure option to build snapshots is --enable-snapshot-build, which add a new compiling mode (nmake build-snap). This tries to build every extension available (as shared, by default), but it will ignore build errors in individual extensions or SAPI.
Compiling PHP using the DSW files isn't supported as of PHP 5, as a much more flexible system was made available. Anyway, you can still use them, but keep in mind that they are not maintained very often, so you can have compiling problems. To compile PHP 4 for windows, this is the only available way though.
The first step is to configure MVC++ to prepare for compiling. Launch Microsoft Visual C++, and from the menu select Tools => Options. In the dialog, select the directories tab. Sequentially change the dropdown to Executables, Includes, and Library files. Your entries should look like this:
Executable files: C:\work\win32build\bin, Cygwin users: C:\cygwin\bin
Include files: C:\work\win32build\include
Library files: C:\work\win32build\lib
The best way to get started is to build the CGI version:
For GUI users, launch VC++, and then select File => Open Workspace and select C:\work\php-4.x.x\win32\php4ts.dsw. Then select Build=>Set Active Configuration and select the desired configuration, either php4ts - Win32 Debug_TS or php4ts - Win32 Release_TS. Finally select Build=>Rebuild All.
For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands from the C:\work\php-4.x.x\win32 directory:
msdev php4ts.dsp /MAKE "php4ts - Win32 Debug_TS"
msdev php4ts.dsp /MAKE "php4ts - Win32 Release_TS"
At this point, you should have a usable php.exe in either your C:\work\php-4.x.x\Debug_TS or Release_TS subdirectories.
It is possible to do minor customization to the build process by editing the main/config.win32.h file. For example you can change the default location of php.ini, the built-in extensions, and the default location for your extensions.
Next you may want to build the CLI version which is designed to use PHP from the command line. The steps are the same as for building the CGI version, except you have to select the php4ts_cli - Win32 Debug_TS or php4ts_cli - Win32 Release_TS project file. After a successful compiling run you will find the php.exe in either the directory Release_TS\cli\ or Debug_TS\cli\.
In order to build the SAPI module (php4isapi.dll) for integrating PHP with Microsoft IIS, set your active configuration to php4isapi-whatever-config and build the desired dll.
After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().
The DLLs for PHP extensions are prefixed with php_.
Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:
In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML and Zlib
In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL and SQLite. And the following are no longer built in: MySQL and Overload.
The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:
You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:
Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.
Example 6-8. Enable Bzip2 extension for PHP-Windows
|
Some of the extensions need extra DLLs to work. Couple of them can be
found in the distribution package, in the
C:\php\dlls\ folder in PHP 4 or
in the main folder in PHP 5, but some, for example Oracle
(php_oci8.dll) require DLLs which are not bundled
with the distribution package. If you are installing PHP 4, copy the
bundled DLLs from C:\php\dlls
folder to the main C:\php
folder. Don't forget to include C:\php in the system
PATH (this process is explained in a separate FAQ entry).
Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.
Note: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.
The following table describes some of the extensions available and required additional dlls.
Table 6-1. PHP Extensions
| Extension | Description | Notes |
|---|---|---|
| php_bz2.dll | bzip2 compression functions | None |
| php_calendar.dll | Calendar conversion functions | Built in since PHP 4.0.3 |
| php_cpdf.dll | ClibPDF functions | None |
| php_crack.dll | Crack functions | None |
| php_ctype.dll | ctype family functions | Built in since PHP 4.3.0 |
| php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled) |
| php_cybercash.dll | Cybercash payment functions | PHP <= 4.2.0 |
| php_db.dll | DBM functions | Deprecated. Use DBA instead (php_dba.dll) |
| php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None |
| php_dbase.dll | dBase functions | None |
| php_dbx.dll | dbx functions | |
| php_domxml.dll | DOM XML functions | PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled) |
| php_dotnet.dll | .NET functions | PHP <= 4.1.1 |
| php_exif.dll | EXIF functions | php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini. |
| php_fbsql.dll | FrontBase functions | PHP <= 4.2.0 |
| php_fdf.dll | FDF: Forms Data Format functions. | Requires: fdftk.dll (bundled) |
| php_filepro.dll | filePro functions | Read-only access |
| php_ftp.dll | FTP functions | Built-in since PHP 4.0.3 |
| php_gd.dll | GD library image functions | Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll. |
| php_gd2.dll | GD library image functions | GD2 |
| php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled). |
| php_hyperwave.dll | HyperWave functions | None |
| php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll |
| php_ifx.dll | Informix functions | Requires: Informix libraries |
| php_iisfunc.dll | IIS management functions | None |
| php_imap.dll | IMAP POP3 and NNTP functions | None |
| php_ingres.dll | Ingres II functions | Requires: Ingres II libraries |
| php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled) |
| php_java.dll | Java functions | PHP <= 4.0.6 requires: jvm.dll (bundled) |
| php_ldap.dll | LDAP functions | PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled) |
| php_mbstring.dll | Multi-Byte String functions | None |
| php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll |
| php_mhash.dll | Mhash functions | PHP >= 4.3.0 requires: libmhash.dll (bundled) |
| php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled) |
| php_ming.dll | Ming functions for Flash | None |
| php_msql.dll | mSQL functions | Requires: msql.dll (bundled) |
| php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled) |
| php_mysql.dll | MySQL functions | PHP >= 5.0.0, requires libmysql.dll (bundled) |
| php_mysqli.dll | MySQLi functions | PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled) |
| php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries |
| php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled) |
| php_oracle.dll | Oracle functions | Requires: Oracle 7 client libraries |
| php_overload.dll | Object overloading functions | Built in since PHP 4.3.0 |
| php_pdf.dll | PDF functions | None |
| php_pgsql.dll | PostgreSQL functions | None |
| php_printer.dll | Printer functions | None |
| php_shmop.dll | Shared Memory functions | None |
| php_snmp.dll | SNMP get and walk functions | NT only! |
| php_soap.dll | SOAP functions | PHP >= 5.0.0 |
| php_sockets.dll | Socket functions | None |
| php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries |
| php_tidy.dll | Tidy functions | PHP >= 5.0.0 |
| php_tokenizer.dll | Tokenizer functions | Built in since PHP 4.3.0 |
| php_w32api.dll | W32api functions | None |
| php_xmlrpc.dll | XML-RPC functions | PHP >= 4.2.1 requires: iconv.dll (bundled) |
| php_xslt.dll | XSLT functions | PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled). |
| php_yaz.dll | YAZ functions | Requires: yaz.dll (bundled) |
| php_zip.dll | Zip File functions | Read only access |
| php_zlib.dll | ZLib compression functions | Built in since PHP 4.3.0 |
PECL is a repository of PHP extensions that are made available to you via the PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.
These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the pear command. The information in the PEAR manual for the pear command also applies to the pecl command.
To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive. To this php.ini file, or through the use of the dl() function.
When building PHP modules, it's important to have known-good versions of the required tools (autoconf, automake, libtool, etc.) See the Anonymous CVS Instructions for details on the required tools, and required versions.
There are several options for downloading PECL extensions, such as:
The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
pecl download extname
PECL extensions that have releases listed on the PECL web site are available for download and installation using the pecl command. Specific revisions may also be specified.
CVS
Most PECL extensions also reside in CVS. A web-based view may be seen at http://cvs.php.net/pecl/. To download straight from CVS, the following sequence of commands may be used. Note that phpfi is the password for user cvsread:
$ cvs -d:pserver:cvsread@cvs.php.net:/repository login $ cvs -d:pserver:cvsread@cvs.php.net:/repository co pecl/extname |
Windows downloads
Windows users may find compiled PECL binaries by downloading the Collection of PECL modules from the PHP Downloads page, or by retrieving a PECL Snapshot or an extension DLL on PECL4WIN. To compile PHP under Windows, read the appropriate chapter.
As with any other PHP extension DLL, installation is as simple as copying the PECL extension DLLs into the extension_dir folder and loading them from php.ini. For example, add the following line to your php.ini:
extension=php_extname.dll |
After doing this, restart the web server.
PECL makes it easy to create shared PHP extensions. Using the pecl command, do the following:
$ pecl install extname |
This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini
By default, the pecl command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:
$ pecl install extname-beta |
You may also install a specific version using this variant:
$ pecl install extname-0.1 |
Sometimes, using the pecl installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PECL compatible package, such as unreleased extensions from CVS. If you need to build such an extension, you can use the lower-level build tools to perform the build manually.
The phpize command is used to prepare the build environment for a PHP extension. In the following sample, the sources for an extension are in a directory named extname:
$ cd extname $ phpize $ ./configure $ make # make install |
A successful install will have created extname.so and put it into the PHP extensions directory. You'll need to and adjust php.ini and add an extension=extname.so line before you can use the extension.
If the system is missing the phpize command, and precompiled packages (like RPM's) are used, be sure to also install the appropriate devel version of the PHP package as they often include the phpize command along with the appropriate header files to build PHP and its extensions.
Execute phpize --help to display additional usage information.
You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the php-src/ext/ directory and tell the PHP build system to regenerate its configure script.
$ cd /your/phpsrcdir/ext $ pecl download extname $ gzip -d < extname.tgz | tar -xvf - $ mv extname-x.x.x extname |
This will result in the following directory:
/your/phpsrcdir/ext/extname |
From here, force PHP to rebuild the configure script, and then build PHP as normal:
$ cd /your/phpsrcdir $ rm configure $ ./buildconf --force $ ./configure --help $ ./configure --with-extname --enable-someotherext --with-foobar $ make $ make install |
Note: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).
Whether --enable-extname or --with-extname is used depends on the extension. Typically an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:
$ ./configure --help | grep extname |
Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.
If you are still stuck, someone on the PHP installation 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/support.php. To subscribe to the PHP installation mailing list, send an empty mail to php-install-subscribe@lists.php.net. The mailing list address is php-install@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, safe mode, etc...), and preferably enough code to make others able to reproduce and test your problem.
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://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.
Read the How to report a bug document before submitting any bug reports!
The configuration file (called php3.ini in PHP 3, and simply php.ini as of PHP 4) 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 and CLI version, it happens on every invocation.
php.ini is searched in these locations (in order):
SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
The PHPRC environment variable. Before PHP 5.2.0
this was checked after the registry key mentioned below.
As of PHP 5.2.0, the following registry locations are searched in order: HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z\IniFilePath, HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y\IniFilePath and HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x\IniFilePath, where x, y and z mean the PHP major, minor and release versions.
HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
Current working directory (except CLI)
The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)
Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option
If php-SAPI.ini exists (where SAPI is used SAPI, so the filename is e.g. php-cli.ini or php-apache.ini), it's used instead of php.ini. SAPI name can be determined by php_sapi_name().
Note: The Apache web server changes the directory to root at startup causing PHP to attempt to read php.ini from the root filesystem if it exists.
The php.ini directives handled by extensions are documented respectively on the pages of the extensions themselves. The list of the core directives is available in the appendix. Probably not all PHP directives are documented in the manual though. For a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find the the latest php.ini from CVS helpful too.
Example 9-1. php.ini example
|
Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".
When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need "AllowOverride Options" or "AllowOverride All" privileges to do so.
With PHP 4 and PHP 5, there are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are PHP_INI_ALL, PHP_INI_PERDIR, or PHP_INI_SYSTEM, have a look at the List of php.ini directives appendix.
Note: With PHP 3, there are Apache directives that correspond to each configuration setting in the php3.ini name, except the name is prefixed by "php3_".
name
valueSets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.
Note: Don't use php_value to set boolean values. php_flag (see below) should be used instead.
name
on|offUsed to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.
name
valueSets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or virtualhost directives. To clear a previously set value use none as the value.
name
on|offUsed to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or virtualhost directives.
Example 9-2. Apache configuration example
|
| Caution |
PHP constants do not exist outside of PHP. For example, in httpd.conf you can not use PHP constants such as E_ALL or E_NOTICE to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini |
When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\SOFTWARE\PHP\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\inetpub\wwwroot would be stored in the key HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in PHP_INI_USER can be set this way, PHP_INI_PERDIR values can not.
Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.
If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().
When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows php to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see php embedded in HTML documents, as in this example.
<p>This is going to be ignored.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored.</p> |
You can also use more advanced structures:
There are four different pairs of opening and closing tags which can be used in php. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.
Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.
Example 10-2. PHP Opening and Closing Tags
|
While the tags seen in examples one and two are both always available, example one is the most commonly used, and recommended, of the two.
Short tags (example three) are only available when they are
enabled via the short_open_tag
php.ini configuration file directive, or if php was configured
with the --enable-short-tags option.
Note: If you are using PHP 3 you may also enable short tags via the short_tags() function. This is only available in PHP 3!
ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive.
Note: Support for ASP tags was added in 3.0.4.
Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.
<?php
echo 'This is a test';
?>
<?php echo 'This is a test' ?>
<?php echo 'We omitted the last closing tag'; |
Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include() or require(), so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
PHP supports 'C', 'C++' and Unix shell-style (Perl 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 a one-line shell-style comment
?> |
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.
<h1>This is an <?php # echo 'simple';?> example.</h1> <p>The header above will say 'This is an example'.</p> |
'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.
PHP supports eight primitive types.
Four scalar types:
Two compound types: And finally two special types: This manual also introduces some pseudo-types for readability reasons: You may also find some references to the type "double". Consider double the same as float, the two names exist only for historic reasons.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.
Note: If you want to check out the type and value of a certain expression, use var_dump().
Note: If you simply want a human-readable representation of the type for debugging, use gettype(). To check for a certain type, do not use gettype(), but use the is_type functions. Some examples:
<?php $a_bool = TRUE; // a boolean $a_str = "foo"; // a string $a_str2 = 'foo'; // a string $an_int = 12; // an integer echo gettype($a_bool); // prints out: boolean echo gettype($a_str); // prints out: string // If this is an integer, increment it by four if (is_int($an_int)) { $an_int += 4; } // If $bool is a string, print it out // (does not print out anything) if (is_string($a_bool)) { echo "String: $a_bool"; } ?>
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 be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. Also, you may be interested in viewing the type comparison tables, as they show examples of various type related comparisons.
This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Note: The boolean type was introduced in PHP 4.
To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.
Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.
To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
| Warning |
-1 is considered TRUE, like any other non-zero (whether negative or positive) number! |
<?php var_dump((bool) ""); // bool(false) var_dump((bool) 1); // bool(true) var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) ?> |
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
See also: Arbitrary length integer / GMP, Floating point numbers, and Arbitrary precision / BCMath
Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded by a sign (- or +).
If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.
If you specify a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, if you perform an operation that results in a number beyond the bounds of the integer type, a float will be returned instead.
<?php $large_number = 2147483647; var_dump($large_number); // output: int(2147483647) $large_number = 2147483648; var_dump($large_number); // output: float(2147483648) // it's true also for hexadecimal specified integers between 2^31 and 2^32-1: var_dump( 0xffffffff ); // output: float(4294967295) // this doesn't go for hexadecimal specified integers above 2^32-1: var_dump( 0x100000000 ); // output: int(2147483647) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // output: float(50000000000) ?> |
| Warning |
Unfortunately, there was a bug in PHP so that this does not always work correctly when there are negative numbers involved. For example: when you do -50000 * $million, the result will be -429496728. However, when both operands are positive there is no problem. This is solved in PHP 4.1.0. |
There is no integer division operator in PHP. 1/2 yields the float 0.5. You can cast the value to an integer to always round it downwards, or you can use the round() function.
To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires an integer argument. You can also convert a value to integer with the function intval().
See also type-juggling.
When converting from float to integer, the number will be rounded towards zero.
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!
| Warning |
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results. See for more information the warning about float-precision. |
| Caution |
Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean. However, do not rely on this behaviour, as it can change without notice. |
Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:
Formally:LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM}) |
| Floating point precision |
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 or gmp functions instead. |
For information on when and how strings are converted to floats, see the section titled String conversion to numbers. For values of other types, the conversion is the same as if the value would have been converted to integer and then to float. See the Converting to integer section for more information. As of PHP 5, notice is thrown if you try to convert object to float.
A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.
Note: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.
A string literal can be specified in three different ways.
The easiest way to specify a simple string is to enclose it in single quotes (the character ').
To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.
Note: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.
Note: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
<?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?> |
If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:
Table 11-1. Escaped characters
| sequence | meaning |
|---|---|
| \n | linefeed (LF or 0x0A (10) in ASCII) |
| \r | carriage return (CR or 0x0D (13) in ASCII) |
| \t | horizontal tab (HT or 0x09 (9) 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 |
Again, if you try to escape any other character, the backslash will be printed too! Before PHP 5.1.1, backslash in \{$var} hasn't been printed.
But the most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier (followed by new line) 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. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
| Warning | |
It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system. This is \r on Macintosh for example. Closing delimiter (possibly followed by a semicolon) must be followed by a newline too. If this rule is broken and the closing identifier is not "clean" then it's not considered to be a closing identifier and PHP will continue looking for one. If in this case a proper closing identifier is not found then a parse error will result with the line number being at the end of the script. It is not allowed to use heredoc syntax in initializing class members. Use other string syntaxes instead. |
Heredoc 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 heredoc as with strings.
Example 11-4. Heredoc string quoting example
|
Note: Heredoc support was added in PHP 4.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to parse a variable, an array value, or an object property.
The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name.
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drank some $beers"; // won't work, 's' is a valid character for varnames
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?> |
Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.
<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote your array string keys
// and do not use {braces} when outside of strings either.
// Let's show all errors
error_reporting(E_ALL);
$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
// Works but note that this works differently outside string-quotes
echo "A banana is $fruits[banana].";
// Works
echo "A banana is {$fruits['banana']}.";
// Works but PHP looks for a constant named banana first
// as described below.
echo "A banana is {$fruits[banana]}.";
// Won't work, use braces. This results in a parse error.
echo "A banana is $fruits['banana'].";
// Works
echo "A banana is " . $fruits['banana'] . ".";
// Works
echo "This square is $square->width meters broad.";
// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?> |
For anything more complex, you should use the complex syntax.
This isn't called complex because the syntax is complex, but because you can include complex expressions this way.
In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" to get a literal "{$"). Some examples to make it clear:
<?php
// Let's show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong
// outside a string. In other words, it will still work but
// because PHP first looks for a constant named foo, it will
// throw an error of level E_NOTICE (undefined constant).
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use
// braces around arrays when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "You can even write {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
?> |
Note: Functions and method calls works since PHP 5.
Characters within strings may be accessed and modified by specifying the
zero-based offset of the desired character after the string
using square array-brackets like $str[42] so think of
a string as an array of characters.
Note: They may also be accessed using braces like
$str{42}for the same purpose. However, using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6.
Example 11-5. Some string examples
|
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.
There are a lot of useful functions for string modification.
See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).
There are also functions for URL-strings, and functions to encrypt/decrypt strings (mcrypt and mhash).
Finally, if you still didn't find what you're looking for, see also the character type functions.
You can convert a value to a string using the (string) cast, or the strval() function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the echo() or print() functions, or when you compare a variable value to a string. Reading the manual sections on Types and Type Juggling will make the following clearer. See also settype().
A boolean TRUE value is converted to the string "1", the FALSE value is represented as "" (empty string). This way you can convert back and forth between boolean and string values.
An integer or a floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers).
Note: The decimal point character is defined in the script's locale (category LC_NUMERIC). See setlocale().
Arrays are always converted to the string "Array", so you cannot dump out the contents of an array with echo() or print() to see what is inside them. To view one element, you'd do something like echo $arr['foo']. See below for tips on dumping/viewing the entire contents.
Objects are always converted to the string "Object". If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use get_class(). As of PHP 5, __toString() method is used if applicable.
Resources are always converted to strings with the structure "Resource id #1" where 1 is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use get_resource_type().
NULL is always converted to an empty string.
As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselves. Look at the functions print_r() and var_dump() for better ways to print out values for debugging.
You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function serialize(). You can also serialize PHP values to XML structures, if you have WDDX support in your PHP setup.
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a float 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.
<?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ?> |
For more information on this conversion, see the Unix manual page for strtod(3).
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.
An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.
Explanation of those data structures is beyond the scope of this manual, but you'll find at least one example for each of them. For more information we refer you to external literature about this broad topic.
An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.
array( [key =>] value
, ...
)
// key may be an integer or string
// value may be any value |
A key may be either an
integer or a string. If a key is
the standard representation of an integer, it will
be interpreted as such (i.e. "8" will be
interpreted as 8, while
"08" will be interpreted as
"08").
Floats in key are truncated to integer.
There are no different indexed and
associative array types in PHP; there is only one array type,
which can both contain integer and string indices.
A value can be of any PHP type.
<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
?> |
If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> |
| Warning |
As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are. |
Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.
You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.
You can also modify an existing array by explicitly setting values in it.
This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case.
$arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value |
$arr doesn't exist yet, it will be created.
So this is also an alternative way to specify an array.
To change a certain value, just assign a new value
to an element specified with its key. If you want to
remove a key/value pair, you need to unset() it.
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?> |
Note: As mentioned above, if you provide the brackets with no key specified, then the maximum of the existing integer indices is taken, and the new key will be that maximum value + 1 . If no integer indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.
Warning As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.
Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:
<?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array itself intact: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0 as you // might expect). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?>The above example will output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
There are quite a few useful functions for working with arrays. See the array functions section.
Note: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achieve the reindex effect by using array_values().
The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.
You should always use quotes around a string literal array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts:
This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.Note: This does not mean to always quote the key. You do not want to quote keys which are constants or variables, as this will prevent PHP from interpreting them.
<?php error_reporting(E_ALL); ini_set('display_errors', true); ini_set('html_errors', false); // Simple array: $array = array(1, 2); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "\nChecking $i: \n"; echo "Bad: " . $array['$i'] . "\n"; echo "Good: " . $array[$i] . "\n"; echo "Bad: {$array['$i']}\n"; echo "Good: {$array[$i]}\n"; } ?>Note: The above example will output:
Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2
More examples to demonstrate this fact:
<?php
// Let's show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of
// level E_NOTICE because of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// Let's define a constant to demonstrate what's going on. We
// will assign value 'veggie' to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay as it's inside a string. Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]"; // Hello apple
// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// This will not work, results in a parse error such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?> |
When you turn error_reporting() up to show E_NOTICE level errors (such as setting it to E_ALL) then you will see these errors. By default, error_reporting is turned down to not show them.
As stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this:
This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before.<?php $error_descriptions[E_ERROR] = "A fatal error has occured"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE] = "This is just an informal notice"; ?> |
<?php $error_descriptions[1] = "A fatal error has occured"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; ?> |
As we already explained in the above examples, $foo[bar] still works but is wrong. It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.
At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special reserved keywords.
Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.
For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with.
If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names with a few notable exceptions: private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour.
<?php
class A {
private $A; // This will become '\0A\0A'
}
class B extends A {
private $A; // This will become '\0B\0A'
public $AA; // This will become 'AA'
}
var_dump((array) new B());
?> |
If you convert a NULL value to an array, you get an empty array.
The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.
<?php
// this
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?> |
Example 11-6. Using array()
|
Changing values of the array directly is possible since PHP 5 by passing them as reference. Prior versions need workaround:
Example 11-8. Collection
The above example will output:
|
This example creates a one-based array.
Arrays are ordered. You can also change the order using various sorting functions. See the array functions section for more information. You can count the number of items in an array using the count() function.
Because the value of an array can be anything, it can also be another array. This way you can make recursive and multi-dimensional arrays.
Example 11-12. Recursive and multi-dimensional arrays
|
You should be aware that array assignment always involves value copying. It also means that the internal array pointer used by current() and similar functions is reset. You need to use the reference operator to copy an array by reference.
To initialize an object, you use the new statement to instantiate the object to a variable.
For a full discussion, please read the section Classes and Objects.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built in class is created. If the value was NULL, the new instance will be empty. Array converts to an object with properties named by array keys and with corresponding values. For any other value, a member variable named scalar will contain the value.
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.
Note: The resource type was introduced in PHP 4
See also get_resource_type().
As resource types hold special handlers to opened files, database connections, image canvas areas and the like, you cannot convert any value to a resource.
Due to the reference-counting system introduced with PHP 4's Zend Engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function.
Note: Persistent database links are special, they are not destroyed by the garbage collector. See also the section about persistent connections.
The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL.
Note: The null type was introduced in PHP 4.
A variable is considered to be NULL if
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
Some functions like call_user_func() or usort() accept user defined callback functions as a parameter. Callback functions can not only be simple functions but also object methods including static class methods.
A PHP function is simply passed by its name as a string. You can pass any built-in or user defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print() and unset().
A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.
Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.
Apart from common user-defined function, create_function() can be used to create an anonymous callback function.
Example 11-13. Callback function examples
|
Note: In PHP4, you will have to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.
void in return type means that the return value is useless. void in parameters list means that the function doesn't accept any parameters.
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 float, then all operands are evaluated as floats, and the result will be a float. 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.
<?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?> |
If the last two examples above seem odd, see String conversion to numbers.
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().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Note: The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:
See the section titled String access by character for more information.
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.
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
Note: Instead of casting a variable to string, you can also enclose the variable in double quotes.
It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).
Tip: You may also want to take a look at the Appendix S.
For information on variable related functions, see the Variable Functions Reference.
<?php $var = 'Bob'; $Var = 'Joe'; echo "$var, $Var"; // outputs "Bob, Joe" $4site = 'not yet'; // invalid; starts with a number $_4site = 'not yet'; // valid; starts with an underscore $täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228. ?> |
In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.
As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:
<?php $foo = 'Bob'; // Assign the value 'Bob' to $foo $bar = &$foo; // Reference $foo via $bar. $bar = "My name is $bar"; // Alter $bar... echo $bar; echo $foo; // $foo is altered too. ?> |
One important thing to note is that only named variables may be assigned by reference.
<?php
$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.
function test()
{
return 25;
}
$bar = &test(); // Invalid.
?> |
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type - FALSE, zero, empty string or an empty array.
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.
PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.
| Warning |
In PHP 4.2.0 and later, the default value for the PHP directive register_globals is
off. This is a major change in PHP. Having
register_globals off affects the set of predefined
variables available in the global scope. For example, to get
For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP 4.1.0 and 4.2.0 Release Announcements. Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred. |
From version 4.1.0 onward, PHP provides an additional set of predefined arrays
containing variables from the web server (if applicable), the
environment, and user input. These new arrays are rather special
in that they are automatically global--i.e., automatically
available in every scope. For this reason, they are often known as
"superglobals". (There is no mechanism in PHP for
user-defined superglobals.) The superglobals are listed below;
however, for a listing of their contents and further discussion on
PHP predefined variables and their natures, please see the section
Reserved Predefined Variables.
Also, you'll notice how the older predefined variables
($HTTP_*_VARS) still exist.
As of PHP 5.0.0, the long PHP
predefined variable
arrays may be disabled with the
register_long_arrays
directive.
Variable variables: Superglobals cannot be used as variable variables inside functions or class methods.
Note: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.
If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.
PHP Superglobals
Contains a reference to every variable which is currently
available within the global scope of the script. The keys of
this array are the names of the global variables.
$GLOBALS has existed since PHP 3.
Variables set by the web server or otherwise directly related
to the execution environment of the current script. Analogous
to the old $HTTP_SERVER_VARS array (which is
still available, but deprecated).
Variables provided to the script via URL query string. Analogous to the
old $HTTP_GET_VARS array (which is still
available, but deprecated).
Variables provided to the script via HTTP POST. Analogous to the
old $HTTP_POST_VARS array (which is still
available, but deprecated).
Variables provided to the script via HTTP cookies. Analogous to
the old $HTTP_COOKIE_VARS array (which is
still available, but deprecated).
Variables provided to the script via HTTP post file
uploads. Analogous to the old
$HTTP_POST_FILES array (which is still
available, but deprecated). See POST method
uploads for more information.
Variables provided to the script via the environment. Analogous
to the old $HTTP_ENV_VARS array (which is
still available, but deprecated).
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the PHP variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().
| Caution |
Since PHP 4.3.0, FILE information from |
Note: When running on the command line , this will not include the
argvandargcentries; these are present in the$_SERVERarray.
Variables which are currently registered to a script's
session. Analogous to the old
$HTTP_SESSION_VARS array (which is still
available, but deprecated). See the Session handling functions section
for more information.
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. This single scope spans included and required files as well. For example:
Here the $a variable will be available within
the included b.inc script. 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:
<?php
$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.
First, an example use of global:
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:
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.
Notice how $GLOBALS exists in any scope, this
is because $GLOBALS is a superglobal.
Here's an example demonstrating the power of superglobals:
Example 12-4. Example demonstrating superglobals and scope
|
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:
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:
Now, every time the Test() function is called it will print the
value of $a and increment it.
Static variables also provide one way to deal with recursive
functions. 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, using the static
variable $count to know when to stop:
Note: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.
The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?php
function test_global_ref() {
global $obj;
$obj = &new stdclass;
}
function test_global_noref() {
global $obj;
$obj = new stdclass;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?> |
Executing this example will result in the following output:
NULL
object(stdClass)(0) {
} |
A similar behaviour applies to the static statement. References are not stored statically:
<?php
function &get_instance_ref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign a reference to the static variable
$obj = &new stdclass;
}
$obj->property++;
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign the object to the static variable
$obj = new stdclass;
}
$obj->property++;
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?> |
Executing this example will result in the following output:
Static object: NULL
Static object: NULL
Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
} |
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.
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 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. i.e.
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:
produces the exact same output as:
i.e. 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.
| Warning |
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. |
When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:
Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:
Example 12-10. Accessing data from a simple POST HTML form
|
Using a GET form is similar except you'll use the appropriate
GET predefined variable instead. GET also applies to the
QUERY_STRING (the information after the '?' in a URL). So,
for example, http://www.example.com/test.php?id=3
contains GET data which is accessible with $_GET['id'].
See also $_REQUEST and
import_request_variables().
Note: Superglobal arrays, like
$_POSTand$_GET, became available in PHP 4.1.0
As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was always on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.
Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.
PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:
Example 12-11. More complex form variables
|
In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such restriction applies.
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.
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. Cookie data
is then available in the appropriate cookie data arrays, such
as $_COOKIE, $HTTP_COOKIE_VARS
as well as in $_REQUEST. See the
setcookie() manual page for more details and
examples.
If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:
<?php
setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?> |
That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.
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 12-12. A setcookie() example
|
Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:
<?php $varname.ext; /* invalid variable name */ ?> |
$varname, followed by the string concatenation
operator, followed by the barestring (i.e. unquoted string which
doesn't match any known key or reserved words) 'ext'. Obviously,
this doesn't have the intended result.
For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
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, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Tip: You may also want to take a look at the Appendix S.
Example 13-1. Valid and invalid constant names
|
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).
Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.
You can define a constant by using the define()-function. Once a constant is defined, it can never be changed or undefined.
Only scalar data (boolean, integer, float and string) can be contained in constants. Do not define resource constants.
You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all defined constants.
Note: Constants and (global) variables are in a different namespace. This implies that for example TRUE and
$TRUEare generally different.
If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). If you simply want to check if a constant is set, use the defined() function.
These are the differences between constants and variables:
Constants do not have a dollar sign ($) before them;
Constants may only be defined using the define() function, not by simple assignment;
Constants may be defined and accessed anywhere without regard to variable scoping rules;
Constants may not be redefined or undefined once they have been set; and
Constants may only evaluate to scalar values.
See also Class Constants.
PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.
There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:
Table 13-1. A few "magical" PHP constants
| Name | Description |
|---|---|
| __LINE__ | The current line number of the file. |
| __FILE__ | The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances. |
| __FUNCTION__ | The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. |
| __CLASS__ | The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. |
| __METHOD__ | The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive). |
See also get_class(), get_object_vars(), file_exists() and function_exists().
Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions 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:
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 four scalar value types: integer values, floating point values (float), string values and boolean 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.
PHP takes expressions much further, in the same way many other languages do. PHP 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 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 enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, 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 identical. 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 FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). 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, 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.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:
If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in general a bit better:
<?php
function double($i)
{
return $i*2;
}
$b = $a = 5; /* assign the value five into the variable $a and $b */
$c = $a++; /* post-increment, assign original value of $a
(5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of
$b (6) to $d and $e */
/* at this point, both $d and $e are equal to 6 */
$f = double($d++); /* assign twice the value of $d before
the increment, 2*6 = 12 to $f */
$g = double(++$e); /* assign twice the value of $e after
the increment, 2*7 = 14 to $g */
$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. */
?> |
Some expressions can be considered as statements. 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. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.
PHP 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 indicate any valid PHP expression.
An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value (so that the construction itself becomes an expression). So you can think of functions or constructions that return a value (like print) as operators and those that return nothing (like echo) as any other thing.
There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports, and a list follows below in the section Operator Precedence.
The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. If operator precedence is equal, left to right associativity is used.
The following table lists the precedence of operators with the highest-precedence operators listed at the top of the table. Operators on the same line have equal precedence, in which case their associativity decides which order to evaluate them in.
Table 15-1. Operator Precedence
| Associativity | Operators | Additional Information |
|---|---|---|
| non-associative | new | new |
| left | [ | array() |
| non-associative | ++ -- | increment/decrement |
| non-associative | ~ - (int) (float) (string) (array) (object) @ | types |
| non-associative | instanceof | types |
| right | ! | logical |
| left | * / % | arithmetic |
| left | + - . | arithmetic and string |
| left | << >> | bitwise |
| non-associative | < <= > >= | comparison |
| non-associative | == != === !== | comparison |
| left | & | bitwise and references |
| left | ^ | bitwise |
| left | | | bitwise |
| left | && | logical |
| left | || | logical |
| left | ? : | ternary |
| right | = += -= *= /= .= %= &= |= ^= <<= >>= | assignment |
| left | and | logical |
| left | xor | logical |
| left | or | logical |
| left | , | many uses |
Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.
Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into
$a.
Remember basic arithmetic from school? These work just like those.
Table 15-2. Arithmetic Operators
| Example | Name | Result |
|---|---|---|
| -$a | Negation | Opposite of $a. |
| $a + $b | Addition | Sum of $a and $b. |
| $a - $b | Subtraction | Difference of $a and $b. |
| $a * $b | Multiplication | Product of $a and $b. |
| $a / $b | Division | Quotient of $a and $b. |
| $a % $b | Modulus | Remainder of $a divided by $b. |
The division operator ("/") returns a float value anytime, even if the two operands are integers (or strings that get converted to integers).
Note: Remainder $a % $b is negative for negative $a.
See also the manual page on Math functions.
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:
In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:
<?php $a = 3; $a += 5; // sets $a to 8, as if we had said: $a = $a + 5; $b = "Hello "; $b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!"; ?> |
Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. Since PHP 4, assignment by reference has been supported, using the $var = &$othervar; syntax, but this is not possible in PHP 3. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise with the new clone keyword.
Bitwise operators allow you to turn specific bits within an integer on or off. If both the left- and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.
<?php
echo 12 ^ 9; // Outputs '5'
echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8
echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4
?> |
Table 15-3. Bitwise Operators
| Example | Name | Result |
|---|---|---|
| $a & $b | And | Bits that are set in both $a and $b are set. |
| $a | $b | Or | Bits that are set in either $a or $b are set. |
| $a ^ $b | Xor | Bits that are set in $a or $b but not both are set. |
| ~ $a | Not | Bits that are set in $a are not set, and vice versa. |
| $a << $b | Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two") |
| $a >> $b | Shift right | Shift the bits of $a $b steps to the right (each step means "divide by two") |
| Warning |
Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. |
Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.
Table 15-4. Comparison Operators
| Example | Name | Result |
|---|---|---|
| $a == $b | Equal | TRUE if $a is equal to $b. |
| $a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4) |
| $a != $b | Not equal | TRUE if $a is not equal to $b. |
| $a <> $b | Not equal | TRUE if $a is not equal to $b. |
| $a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4) |
| $a < $b | Less than | TRUE if $a is strictly less than $b. |
| $a > $b | Greater than | TRUE if $a is strictly greater than $b. |
| $a <= $b | Less than or equal to | TRUE if $a is less than or equal to $b. |
| $a >= $b | Greater than or equal to | TRUE if $a is greater than or equal to $b. |
If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?> |
For various types, comparison is done according to the following table (in order).
Table 15-5. Comparison with Various Types
| Type of Operand 1 | Type of Operand 2 | Result |
|---|---|---|
| null or string | string | Convert NULL to "", numerical or lexical comparison |
| bool or null | anything | Convert to bool, FALSE < TRUE |
| object | object | Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation |
| string, resource or number | string, resource or number | Translate strings and resources to numbers, usual math |
| array | array | Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example) |
| array | anything | array is always greater |
| object | anything | object is always greater |
Example 15-2. Transcription of standard array comparison
|
See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.
Another conditional operator is the "?:" (or ternary) operator.
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
Note: Is is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:
Example 15-4. Non-obvious Ternary Behaviour
<?php // on first glance, the following appears to output 'true' echo (true?'true':false?'t':'f'); // however, the actual output of the above is 't' // this is because ternary expressions are evaluated from left to right // the following is a more obvious version of the same code as above echo ((true ? 'true' : 'false') ? 't' : 'f'); // here, you can see that the first expression is evaluated to 'true', which // in turn evaluates to (bool)true, thus returning the true branch of the // second ternary expression. ?>
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
If the track_errors
feature is enabled, any error message generated by the expression
will be saved in the variable
$php_errormsg.
This variable will be overwritten on each error, so check early if you
want to use it.
<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
?> |
Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.
See also error_reporting() and the manual section for Error Handling and Logging functions.
| Warning |
Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why. |
PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().
Note: The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.
See also the manual section on Program Execution functions, popen() proc_open(), and Using PHP from the commandline.
PHP supports C-style pre- and post-increment and decrement operators.
Note: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.
Table 15-6. Increment/decrement Operators
| Example | Name | Effect |
|---|---|---|
| ++$a | Pre-increment | Increments $a by one, then returns $a. |
| $a++ | Post-increment | Returns $a, then increments $a by one. |
| --$a | Pre-decrement | Decrements $a by one, then returns $a. |
| $a-- | Post-decrement | Returns $a, then decrements $a by one. |
Here's a simple example script:
<?php echo "<h3>Postincrement</h3>"; $a = 5; echo "Should be 5: " . $a++ . "<br />\n"; echo "Should be 6: " . $a . "<br />\n"; echo "<h3>Preincrement</h3>"; $a = 5; echo "Should be 6: " . ++$a . "<br />\n"; echo "Should be 6: " . $a . "<br />\n"; echo "<h3>Postdecrement</h3>"; $a = 5; echo "Should be 5: " . $a-- . "<br />\n"; echo "Should be 4: " . $a . "<br />\n"; echo "<h3>Predecrement</h3>"; $a = 5; echo "Should be 4: " . --$a . "<br />\n"; echo "Should be 4: " . $a . "<br />\n"; ?> |
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Incrementing or decrementing booleans has no effect.
Table 15-7. Logical Operators
| Example | Name | Result |
|---|---|---|
| $a and $b | And | TRUE if both $a and $b are TRUE. |
| $a or $b | Or | TRUE if either $a or $b is TRUE. |
| $a xor $b | Xor | TRUE if either $a or $b is TRUE, but not both. |
| ! $a | Not | TRUE if $a is not TRUE. |
| $a && $b | And | TRUE if both $a and $b are TRUE. |
| $a || $b | Or | TRUE if either $a or $b is TRUE. |
The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.
<?php $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; // now $a contains "Hello World!" ?> |
See also the manual sections on the String type and String functions.
Table 15-8. Array Operators
| Example | Name | Result |
|---|---|---|
| $a + $b | Union | Union of $a and $b. |
| $a == $b | Equality | TRUE if $a and $b have the same key/value pairs. |
| $a === $b | Identity | TRUE if $a and $b have the same key/value pairs in the same order and of the same types. |
| $a != $b | Inequality | TRUE if $a is not equal to $b. |
| $a <> $b | Inequality | TRUE if $a is not equal to $b. |
| $a !== $b | Non-identity | TRUE if $a is not identical to $b. |
The + operator appends the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?> |
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
} |
Elements of arrays are equal for the comparison if they have the same key and value.
See also the manual sections on the Array type and Array functions.
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:
Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:
Example 15-10. Using instanceof with other variables
The above example will output:
|
There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:
The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof.
See also get_class() and is_a().
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or 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.
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 structure that is similar to that of C:
As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.
The following example would display a is bigger
than b if $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 statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.
Often you'd want to execute a statement if a certain condition is
met, and a different statement if the condition is not met. This
is what else is for. else
extends an if statement to execute a statement
in case the expression in the if statement
evaluates to FALSE. For example, the following
code would display a is bigger than
b if $a is bigger than
$b, and a is NOT bigger
than b otherwise:
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 conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "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, 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 preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
In the above example, the HTML block "A is equal to 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 as well. The following is an if structure with elseif and else in the alternative format:
while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:
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:
The following examples are identical, and both print numbers from 1 to 10:
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 guaranteed 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:
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:
<?php
do {
if ($i < 5) {
echo "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "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 loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
The first expression (expr1) is
evaluated (executed) once 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 or contain multiple
expressions separated by commas. Comma separated expressions in expr2
are treated similarly to being separated by the || operator but has a
lower precedence than ||.
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:
<?php
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?> |
Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.
PHP also supports the alternate "colon syntax" for for loops.
PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement |
The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).
The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
As of PHP 5, it is possible to iterate objects too.
Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. Therefore, the array pointer is not modified as with the each() construct, and changes to the array element returned are not reflected in the original array. However, the internal pointer of the original array is advanced with the processing of the array. Assuming the foreach loop runs to completion, the array's internal pointer will be at the end of the array.
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
This is possible only if iterated array can be referenced (i.e. is variable).
Note: foreach does not support the ability to suppress error messages using '@'.
You may have noticed that the following are functionally identical:
<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
echo "Value: $value<br />\n";
}
foreach ($arr as $value) {
echo "Value: $value<br />\n";
}
?> |
<?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
?> |
Some more examples to demonstrate usages:
<?php
/* foreach example 1: value only */
$a = array(1, 2, 3, 17);
foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}
/* foreach example 2: value (with key printed for illustration) */
$a = array(1, 2, 3, 17);
$i = 0; /* for illustrative purposes only */
foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
$i++;
}
/* foreach example 3: key and value */
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
/* foreach example 5: dynamic arrays */
foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?> |
break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
/* Using the optional argument. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?> |
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
<?php
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip odd members
continue;
}
do_something_odd($value);
}
$i = 0;
while ($i++ < 5) {
echo "Outer<br />\n";
while (1) {
echo " Middle<br />\n";
while (1) {
echo " Inner<br />\n";
continue 3;
}
echo "This never gets output.<br />\n";
}
echo "Neither does this.<br />\n";
}
?> |
Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?> |
One can expect the result to be :
0 1 3 4 |
but this script will output :
2 |
because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.
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.
Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.
The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:
It is important to understand how the switch statement is executed in order to avoid mistakes. 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 does PHP begin 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:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?> |
Here, if $i is equal to 0, PHP would execute all of the echo
statements! If $i is equal to 1, PHP would execute the last two
echo statements. You would get the expected behavior ('i equals 2'
would be displayed) only if $i is equal to 2. Thus,
it is important not to forget break statements
(even though you may want to avoid supplying them on purpose under
certain circumstances).
In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.
The statement list for a case can also be empty, which simply passes control into the statement list for the next case.
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?> |
A special case is the default case. This case matches anything that wasn't matched by the other cases, and should be the last case statement. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?> |
The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.
The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures .
The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:
The directive section allows the behavior of the declare block to be set. Currently only one directive is recognized: the ticks directive. (See below for more information on the ticks directive)
The statement part of the declare block will be executed -- how it is executed and what side effects occur during execution may depend on the directive set in the directive block.
The declare construct can also be used in the global scope, affecting all code following it.
<?php
// these are the same:
// you can use this:
declare(ticks=1) {
// entire script here
}
// or you can use this:
declare(ticks=1);
// entire script here
?> |
A tick is an event that occurs for every
N low-level statements executed
by the parser within the declare block.
The value for N is specified
using ticks=N
within the declare blocks's
directive section.
The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.
Example 16-3. Profile a section of PHP code
|
Ticks are well suited for debugging, implementing simple multitasking, background I/O and many other tasks.
See also register_tick_function() and unregister_tick_function().
If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.
If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.
For more information, see Returning values.
Note: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.
Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of
$a).
The require() statement includes and evaluates the specific file.
require() includes and evaluates a specific file. Detailed information on how this inclusion works is described in the documentation for include().
require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.
Example 16-4. Basic require() examples
|
See the include() documentation for more examples.
Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.
Note: Because this is a language construct and not a function, it cannot be called using variable functions
| Warning |
Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled. |
See also include(), require_once(), include_once(), get_included_files(), eval(), file(), readfile(), virtual() and include_path.
The include() statement includes and evaluates the specified file.
The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in included file doesn't cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.
Files for including are first looked in include_path relative to the current working directory and then in include_path relative to the directory of current script. E.g. if your include_path is ., current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in include_path relative to the current working directory.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
Example 16-5. Basic include() example
|
If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.
Example 16-6. Including within functions
|
When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.
If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Appendix N for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.
| Warning |
Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled. |
Example 16-7. include() through HTTP
|
| Security warning |
Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code. |
See also Remote files, fopen() and file() for related information.
Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.
Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.
Note: In PHP 3, the return may not appear inside a block unless it's a function block, in which case the return() applies to that function and not the whole file.
$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.
If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.
Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:
Example 16-10. Using output buffering to include a PHP file into a string
|
In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.
Note: Because this is a language construct and not a function, it cannot be called using variable functions
See also require(), require_once(), include_once(), get_included_files(), readfile(), virtual(), and include_path.
The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again. See the documentation for require() for more information on how this statement works.
require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
For examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.
Return values are the same as with include(). If the file was already included, this function returns TRUE
Note: require_once() was added in PHP 4.0.1
Note: Be aware, that the behaviour of require_once() and include_once() may not be what you expect on a non case sensitive operating system (such as Windows).
This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is required just once.
Example 16-11. require_once() is case insensitive on Windows
<?php require_once("a.php"); // this will include a.php require_once("A.php"); // this will include a.php again on Windows! (PHP 4 only) ?>
| Warning |
Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled. |
See also require(), include(), include_once(), get_required_files(), get_included_files(), readfile(), and virtual().
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
For more examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.
Return values are the same as with include(). If the file was already included, this function returns TRUE
Note: include_once() was added in PHP 4.0.1
Note: Be aware, that the behaviour of include_once() and require_once() may not be what you expect on a non case sensitive operating system (such as Windows).
This behaviour changed in PHP 5 - the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.
Example 16-12. include_once() is case insensitive on Windows
<?php include_once("a.php"); // this will include a.php include_once("A.php"); // this will include a.php again on Windows! (PHP 4 only) ?>
| Warning |
Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled. |
See also include(), require(), require_once(), get_required_files(), get_included_files(), readfile(), and virtual().
A function may be defined using syntax such as the following:
Any valid PHP code may appear inside a function, even other functions and class definitions.
Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
Tip: You may also want to take a look at the Appendix S.
In PHP 3, functions must be defined before they are referenced. No such requirement exists since PHP 4. Except when a function is conditionally defined such as shown in the two examples below.
When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.
Example 17-2. Conditional functions
|
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
Note: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.
PHP 3 does not support variable numbers of arguments to functions, although default arguments are supported (see Default argument values for more information). Both are supported, as of PHP 4: see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.
It is possible to call recursive functions in PHP. However avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.
PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are supported only in PHP 4 and later; see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. A similar effect can be achieved in PHP 3 by passing an array of arguments to a function:
By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference.
If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition:
A function may define C++-style default values for scalar arguments as follows:
The output from the above snippet is:
Making a cup of cappuccino. Making a cup of . Making a cup of espresso. |
Also PHP allows you to use arrays and special type NULL as default values, for example:
Example 17-8. Using non-scalar types as default values
|
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
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:
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:
The output of this example is:
Making a bowl of acidophilus raspberry. |
Note: As of PHP 5, default values may be passed by reference.
PHP 4 and above has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.
No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.
Values are returned by using the optional return statement. Any type may be returned, including lists and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return() for more information.
Example 17-11. Use of return()
|
You can't return multiple values from a function, but similar results can be obtained by returning a list.
To return a reference from a function, you have to use the reference operator & in both the function declaration and when assigning the returned value to a variable:
For more information on references, please check out References Explained.
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. You need to use your own wrapper function to utilize any of these constructs as variable functions.
Example 17-14. Variable function example
|
You can also call an object's method by using the variable functions feature.
See also call_user_func(), variable variables and function_exists().
PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in otherwise you'll get fatal "undefined function" errors. For example, to use image functions such as imagecreatetruecolor(), you'll need your PHP compiled with GD support. Or, to use mysql_connect() you'll need your PHP compiled in with MySQL support. There are many core functions that are included in every version of PHP like the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show you which extensions are loaded into your PHP. Also note that many extensions are enabled by default and that the PHP manual is split up by extension. See the configuration, installation, and individual extension chapters, for information on how to setup your PHP.
Reading and understanding a function's prototype is explained within the manual section titled how to read a function definition. It's important to realize what a function returns or if a function works directly on a passed in value. For example, str_replace() will return the modified string while usort() works on the actual passed in variable itself. Each manual page also has specific information for each function like information on function parameters, behavior changes, return values for both success and failure, and availability information. Knowing these important (yet often subtle) differences is crucial for writing correct PHP code.
Note: If the parameters given to a function are not what it expects, such as passing an array where a string is expected, the return value of the function is undefined. In this case it will likely return NULL but this is just a convention, and cannot be relied upon.
See also function_exists(), the function reference, get_extension_funcs(), and dl().
A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:
<?php
class Cart {
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
function remove_item($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true;
} else {
return false;
}
}
}
?> |
This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.
| Warning |
You can NOT break up a class definition into multiple files. You also can NOT break a class definition into multiple PHP blocks, unless the break is within a method declaration. The following will not work:
However, the following is allowed:
|
The following cautionary notes are valid for PHP 4.
| Caution |
The name stdClass is used internally by Zend and is reserved. You cannot have a class named stdClass in PHP. |
| Caution |
The function names __sleep and __wakeup are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them. See below for more information. |
| Caution |
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality. |
In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor (see below).
<?php
class Cart {
/* None of these will work in PHP 4. */
var $todays_date = date("Y-m-d");
var $name = $firstname;
var $owner = 'Fred ' . 'Jones';
/* Arrays containing constant values will, though. */
var $items = array("VCR", "TV");
}
/* This is how it should be done. */
class Cart {
var $todays_date;
var $name;
var $owner;
var $items = array("VCR", "TV");
function Cart() {
$this->todays_date = date("Y-m-d");
$this->name = $GLOBALS['firstname'];
/* etc. . . */
}
}
?> |
Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.
<?php
$cart = new Cart;
$cart->add_item("10", 1);
$another_cart = new Cart;
$another_cart->add_item("0815", 3);
?> |
This creates the objects $cart and
$another_cart, both of the class Cart. The function
add_item() of the $cart object is being called to add 1
item of article number 10 to the $cart. 3 items of
article number 0815 are being added to $another_cart.
Both, $cart and $another_cart, have
functions add_item(), remove_item() and a variable items. These are
distinct functions and variables. You can think of the objects as
something similar to directories in a filesystem. In a filesystem you can
have two different files README.TXT, as long as they
are in different directories. Just like with directories where you'll have
to type the full pathname in order to reach each file from the toplevel
directory, you have to specify the complete name of the function you want to
call: in PHP terms, the toplevel directory would be the global namespace,
and the pathname separator would be ->. Thus, the
names $cart->items and
$another_cart->items name two different variables.
Note that the variable is named $cart->items, not
$cart->$items, that is, a variable name in PHP has
only a single dollar sign.
<?php
// correct, single $
$cart->items = array("10" => 1);
// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);
// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1);
?> |
Within a class definition, you do not know under which name the object
will be accessible in your program: at the time the Cart class was
written, it was unknown whether the object would be named
$cart, $another_cart, or something
else later. Thus,
you cannot write $cart->items within the Cart class
itself. Instead, in order to be able to access its own functions and
variables from within a class, one can use the pseudo-variable
$this which can be read as 'my own' or 'current
object'. Thus, '$this->items[$artnr] +=
$num' can be read as 'add $num to
the $artnr counter of my own items array' or 'add
$num to the $artnr counter of the
items array within the current object'.
Note: The
$thispseudo-variable is not usually defined if the method in which it is hosted is called statically. This is not, however, a strict rule:$thisis defined if a method is called statically from within another object. In this case, the value of$thisis that of the calling object. This is illustrated in the following example:
<?php class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")\n"; } else { echo "\$this is not defined.\n"; } } } class B { function bar() { A::foo(); } } $a = new A(); $a->foo(); A::foo(); $b = new B(); $b->bar(); B::bar(); ?>The above example will output:
$this is defined (a) $this is not defined. $this is defined (b) $this is not defined.
Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.
Often you need classes with similar variables and functions to another existing class. In fact, it is good practice to define a generic class which can be used in all your projects and adapt this class for the needs of each of your specific projects. To facilitate this, classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class (this is called 'inheritance' despite the fact that nobody died) and what you add in the extended definition. It is not possible to subtract from a class, that is, to undefine any existing functions or variables. An extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.
<?php
class Named_Cart extends Cart {
var $owner;
function set_owner ($name) {
$this->owner = $name;
}
}
?> |
This defines a class Named_Cart that has all variables and functions of
Cart plus an additional variable $owner and an
additional function set_owner(). You create a named cart the usual way and
can now set and get the carts owner. You can still use normal cart
functions on named carts:
<?php
$ncart = new Named_Cart; // Create a named cart
$ncart->set_owner("kris"); // Name that cart
print $ncart->owner; // print the cart owners name
$ncart->add_item("10", 1); // (inherited functionality from cart)
?> |
This is also called a "parent-child" relationship. You create a class, parent, and use extends to create a new class based on the parent class: the child class. You can even use this new child class and create another class based on this child class.
Note: Classes must be defined before they are used! If you want the class Named_Cart to extend the class Cart, you will have to define the class Cart first. If you want to create another class called Yellow_named_cart based on the class Named_Cart you have to define Named_Cart first. To make it short: the order in which the classes are defined is important.
Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base class will be called, if it exists.
This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can take arguments and these arguments can be optional, which makes them much more useful. To be able to still use the class without parameters, all parameters to constructors should be made optional by providing default values.
<?php
class Constructor_Cart extends Cart {
function Constructor_Cart($item = "10", $num = 1) {
$this->add_item ($item, $num);
}
}
// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;
// Shop for real...
$different_cart = new Constructor_Cart("20", 17);
?> |
You also can use the @ operator to mute errors occurring in the constructor, e.g. @new.
<?php
class A
{
function A()
{
echo "I am the constructor of A.<br />\n";
}
function B()
{
echo "I am a regular function named B in class A.<br />\n";
echo "I am not a constructor in A.<br />\n";
}
}
class B extends A
{
}
// This will call B() as a constructor
$b = new B;
?> |
The function B() in class A will suddenly become a constructor in class B, although it was never intended to be. PHP 4 does not care if the function is being defined in class B, or if it has been inherited.
| Caution |
PHP 4 doesn't call constructors of the base class automatically from a constructor of a derived class. It is your responsibility to propagate the call to constructors upstream where appropriate. |
Destructors are functions that are called automatically when an object is destroyed, either with unset() or by simply going out of scope. There are no destructors in PHP. You may use register_shutdown_function() instead to simulate most effects of destructors.
| Caution |
The following is valid for PHP 4 and later only. |
Sometimes it is useful to refer to functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this.
<?php
class A {
function example() {
echo "I am the original function A::example().<br />\n";
}
}
class B extends A {
function example() {
echo "I am the redefined function B::example().<br />\n";
A::example();
}
}
// there is no object of class A.
// this will print
// I am the original function A::example().<br />
A::example();
// create an object of class B.
$b = new B;
// this will print
// I am the redefined function B::example().<br />
// I am the original function A::example().<br />
$b->example();
?> |
The above example calls the function example() in class A, but there is no object of class A, so that we cannot write $a->example() or similar. Instead we call example() as a 'class function', that is, as a function of the class itself, not any object of that class.
There are class functions, but there are no class variables.
In fact, there is no object at all at the time of the call.
Thus, a class function may not use any object variables (but
it can use local and global variables), and it may not use
$this at all.
In the above example, class B redefines the function example(). The original definition in class A is shadowed and no longer available, unless you are referring specifically to the implementation of example() in class A using the ::-operator. Write A::example() to do this (in fact, you should be writing parent::example(), as shown in the next section).
In this context, there is a current object and it may have object
variables. Thus, when used from WITHIN an object function, you may use
$this and object variables.
You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialisation of code in your base class.
Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. By doing this, you avoid using the name of your base class in more than one place. Should your inheritance tree change during implementation, the change is easily made by simply changing the extends declaration of your class.
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?> |
Note: In PHP 3, objects will lose their class association throughout the process of serialization and unserialization. The resulting variable is of type object, but has no class and no methods, thus it is pretty useless (it has become just like an array with a funny syntax).
| Caution |
The following information is valid for PHP >= 4 only. |
serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The functions in an object will not be saved, only the name of the class.
In order to be able to unserialize() an object, the
class of that object needs to be defined. That is, if you have an object
$a of class A on page1.php and serialize this, you'll
get a string that refers to class A and contains all values of variabled
contained in $a. If you want to be able to unserialize
this on page2.php, recreating $a of class A, the
definition of class A must be present in page2.php. This can be done for
example by storing the class definition of class A in an include file and
including this file in both page1.php and page2.php.
<?php
// classa.inc:
class A {
var $one = 1;
function show_one() {
echo $this->one;
}
}
// page1.php:
include("classa.inc");
$a = new A;
$s = serialize($a);
// store $s somewhere where page2.php can find it.
$fp = fopen("store", "w");
fwrite($fp, $s);
fclose($fp);
// page2.php:
// this is needed for the unserialize to work properly.
include("classa.inc");
$s = implode("", @file("store"));
$a = unserialize($s);
// now use the function show_one() of the $a object.
$a->show_one();
?> |
If you are using sessions and use session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This basically means that these objects can show up on any of your pages once they become part of your session.
It is strongly recommended that you include the class definitions of all such registered objects on all of your pages, even if you do not actually use these classes on all of your pages. If you don't and an object is being unserialized without its class definition being present, it will lose its class association and become an object of class stdClass without any functions available at all, that is, it will become quite useless.
So if in the example above $a became part of a session
by running session_register("a"), you should include the
file classa.inc on all of your pages, not only page1.php
and page2.php.
serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not be saved completely.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that object may have.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Creating references within the constructor can lead to confusing results. This tutorial-like section helps you to avoid problems.
<?php
class Foo {
function Foo($name) {
// create a reference inside the global array $globalref
global $globalref;
$globalref[] = &$this;
// set name to passed value
$this->setName($name);
// and put it out
$this->echoName();
}
function echoName() {
echo "<br />", $this->name;
}
function setName($name) {
$this->name = $name;
}
}
?> |
Let us check out if there is a difference between
$bar1 which has been created using
the copy = operator and
$bar2 which has been created using
the reference =& operator...
<?php
$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();
/* output:
set in constructor
set in constructor
set in constructor */
$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();
/* output:
set in constructor
set in constructor
set in constructor */
?> |
Apparently there is no difference, but in fact there is a
very significant one: $bar1 and
$globalref[0] are _NOT_ referenced, they
are NOT the same variable. This is because "new" does not
return a reference by default, instead it returns a copy.
Note: There is no performance loss (since PHP 4 and up use reference counting) returning copies instead of references. On the contrary it is most often better to simply work with copies instead of references, because creating references takes some time where creating copies virtually takes no time (unless none of them is a large array or object and one of them gets changed and the other(s) one(s) subsequently, then it would be wise to use references to change them all concurrently).
<?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');
// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();
/* output:
set from outside
set in constructor */
// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');
// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();
/* output:
set from outside
set from outside */
?> |
Another final example, try to understand it.
<?php
class A {
function A($i) {
$this->value = $i;
// try to figure out why we do not need a reference here
$this->b = new B($this);
}
function createRef() {
$this->c = new B($this);
}
function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->value;
}
}
class B {
function B(&$a) {
$this->a = &$a;
}
function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->a->value;
}
}
// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new A(10);
$a->createRef();
$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();
$a->value = 11;
$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();
?> |
The above example will output:
class A: 10 class B: 10 class B: 10 class A: 11 class B: 11 class B: 11 |
In PHP 4, objects are compared in a very simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. Similar rules are applied when comparing two objects using the identity operator (===).
If we were to execute the code in the example below:
Example 18-1. Example of object comparison in PHP 4
The above example will output:
|
Even in the cases where we have object composition, the same comparison rules apply. In the example below we create a container class that stores an associative array of Flag objects.
Example 18-2. Compound object comparisons in PHP 4
The above example will output:
|
In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features.
Tip: You may also want to take a look at the Appendix S.
Every class definition begins with the keyword class, followed by a class
name, which can be any name that isn't a reserved
word in PHP. Followed by a pair of curly braces,
which contains the definition of the classes members and methods. A
pseudo-variable, $this is available when a method is
called from within an object context. $this is a
reference to the calling object (usually the object to which the method
belongs, but can be another object, if the method is called
statically from the context
of a secondary object). This is illustrated in the following examples:
Example 19-1.
The above example will output:
|
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
Example 19-3. Class members' default value
|
Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.
To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.
Example 19-5. Object Assignment
The above example will output:
|
A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.
The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them within the same name defined in the parent class. It is possible to access the overridden methods or members by referencing them with parent::
Example 19-6. Simple Class Inherintance
The above example will output:
|
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Note: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
Example 19-8. using new unified constructors
|
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed.
Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.
Note: Destructor is called during the script shutdown so headers are always already sent.
Note: Attempting to throw an exception from a destructor causes a fatal error.
The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.
Class members must be defined with public, private, or protected.
Example 19-10. Member declaration
|
Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.
Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.
Example 19-11. Method Declaration
|
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.
When referencing these items from outside the class definition, use the name of the class.
Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!
Two special keywords self and parent
are used to access members or methods from inside the class definition.
When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.
Example 19-14. Calling a parent's method
|
Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
The static declaration must be after the visibility declaration. For compatibility with PHP 4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public.
Because static methods are callable without an instance of
the object created, the pseudo variable $this is
not available inside the method declared as static.
In fact static method calls are resolved at compile time. When using an explicit class name the method is already identified completely and no inheritance rules apply. If the call is done by self then self is translated to the current class, that is the class the code belongs to. Here also no inheritance rules apply.
Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Example 19-15. Static member example
|
It is possible to define constant values on a per-class basis remaining the
same and unchangeable. Constants differ from normal variables in that you
don't use the $ symbol to declare or use them. Like
static members, constant values
cannot be accessed from an instance of the object (using
$object::constant).
The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or weaker) visibillity. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public.
Example 19-18. Abstract class example
The above example will output:
|
Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface.
To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.
Example 19-19. Interface example
|
See also the instanceof operator.
Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static. All overloading methods must be defined as public.
Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively. Method __isset is called also with empty().
Class members can be overloaded to run custom code defined in your class
by defining these specially named methods. The $name
parameter used is the name of the variable that should be set or retrieved.
The __set() method's $value parameter specifies the
value that the object should set the $name.
Example 19-20. overloading with __get, __set, __isset and __unset example
The above example will output:
|
The magic method __call() allows to capture invocation of non existing
methods. That way __call() can be used to implement user defined method
handling that depends on the name of the actual method being called. This
is for instance useful for proxy implementations. The arguments that were
passed in the function will be defined as an array in the
$arguments parameter. The value returned from the
__call() method will be returned to the caller of the method.
Example 19-21. overloading with __call example
The above example will output:
|
PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.
Example 19-22. Simple Object Iteration
The above example will output:
|
As the output shows, the foreach iterated through all
visible variables that can be
accessed. To take it a step further you can implement one
of PHP 5's internal interface named
Iterator. This allows the object to decide what and how
the object will be iterated.
Example 19-23. Object Iteration implementing Iterator
The above example will output:
|
You can also define your class so that it doesn't have to define
all the Iterator functions by simply implementing
the PHP 5 IteratorAggregate interface.
Example 19-24. Object Iteration implementing IteratorAggregate
The above example will output:
|
Note: For more examples of iterators, see the SPL Extension.
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.
The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.
Example 19-25. Parameterized Factory Method
Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:
|
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
Example 19-26. Singleton Function
This allows a single instance of the Example class to be retrieved.
|
The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __set_state, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.
| Caution |
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality. |
serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
The __sleep method should return the value to serialize (usually $this), otherwise NULL is serialized.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Example 19-27. Sleep and wakeup
|
The __toString method allows a class to decide how it will react when it is converted to a string.
It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print().
This static method is called for classes exported by var_export() since PHP 5.1.0.
The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Example 19-29. Final methods example
|
Example 19-30. Final class example
|
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.
An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
Example 19-31. Cloning an object
The above example will output:
|
In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
An example will clarify these rules.
Example 19-32. Example of object comparison in PHP 5
The above example will output:
|
PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.
The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:
<?php
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
?> |
Note: For details on these classes, have a look at the next chapters.
If we were to execute the code in the example below:
Example 19-33. Basic usage of the reflection API
The above example will output:
|
ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.
The ReflectionFunction class lets you reverse-engineer functions.
<?php
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector
{
final private __clone()
public object __construct(string name)
public string __toString()
public static string export(string name, bool return)
public string getName()
public bool isInternal()
public bool isUserDefined()
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public array getStaticVariables()
public mixed invoke(mixed args)
public mixed invokeArgs(array args)
public bool returnsReference()
public ReflectionParameter[] getParameters()
public int getNumberOfParameters()
public int getNumberOfRequiredParameters()
}
?> |
Note: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.
To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.
Example 19-34. Using the ReflectionFunction class
|
Note: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().
The ReflectionParameter class retrieves information about a function's or method's parameters.
<?php
class ReflectionParameter implements Reflector
{
final private __clone()
public object __construct(string name)
public string __toString()
public static string export(mixed function, mixed parameter, bool return)
public string getName()
public bool isPassedByReference()
public ReflectionFunction getDeclaringFunction()
public ReflectionClass getDeclaringClass()
public ReflectionClass getClass()
public bool isArray()
public bool allowsNull()
public bool isPassedByReference()
public bool getPosition()
public bool isOptional()
public bool isDefaultValueAvailable()
public mixed getDefaultValue()
}
?> |
Note: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0. getDeclaringFunction() and getPosition() were added in PHP 5.1.3.
To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.
Example 19-35. Using the ReflectionParameter class
|
The ReflectionClass class lets you reverse-engineer classes.
<?php
class ReflectionClass implements Reflector
{
final private __clone()
public object __construct(string name)
public string __toString()
public static string export(mixed class, bool return)
public string getName()
public bool isInternal()
public bool isUserDefined()
public bool isInstantiable()
public bool hasConstant(string name)
public bool hasMethod(string name)
public bool hasProperty(string name)
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public ReflectionMethod getConstructor()
public ReflectionMethod getMethod(string name)
public ReflectionMethod[] getMethods()
public ReflectionProperty getProperty(string name)
public ReflectionProperty[] getProperties()
public array getConstants()
public mixed getConstant(string name)
public ReflectionClass[] getInterfaces()
public bool isInterface()
public bool isAbstract()
public bool isFinal()
public int getModifiers()
public bool isInstance(stdclass object)
public stdclass newInstance(mixed args)
public stdclass newInstanceArgs(array args)
public ReflectionClass getParentClass()
public bool isSubclassOf(ReflectionClass class)
public array getStaticProperties()
public mixed getStaticPropertyValue(string name [, mixed default])
public void setStaticPropertyValue(string name, mixed value)
public array getDefaultProperties()
public bool isIterateable()
public bool implementsInterface(string name)
public ReflectionExtension getExtension()
public string getExtensionName()
}
?> |
Note: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0, while newInstanceArgs() was added in PHP 5.1.3.
To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.
Example 19-36. Using the ReflectionClass class
|
Note: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().
Note: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').
The ReflectionMethod class lets you reverse-engineer class methods.
<?php
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector
{
public __construct(mixed class, string name)
public string __toString()
public static string export(mixed class, string name, bool return)
public mixed invoke(stdclass object, mixed args)
public mixed invokeArgs(stdclass object, array args)
public bool isFinal()
public bool isAbstract()
public bool isPublic()
public bool isPrivate()
public bool isProtected()
public bool isStatic()
public bool isConstructor()
public bool isDestructor()
public int getModifiers()
public ReflectionClass getDeclaringClass()
// Inherited from ReflectionFunction
final private __clone()
public string getName()
public bool isInternal()
public bool isUserDefined()
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public array getStaticVariables()
public bool returnsReference()
public ReflectionParameter[] getParameters()
public int getNumberOfParameters()
public int getNumberOfRequiredParameters()
}
?> |
To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance.
Example 19-37. Using the ReflectionMethod class
|
Note: Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke() method.
Note: For static methods as seen above, you should pass NULL as the first argument to invoke(). For non-static methods, pass an instance of the class.
The ReflectionProperty class lets you reverse-engineer class properties.
<?php
class ReflectionProperty implements Reflector
{
final private __clone()
public __construct(mixed class, string name)
public string __toString()
public static string export(mixed class, string name, bool return)
public string getName()
public bool isPublic()
public bool isPrivate()
public bool isProtected()
public bool isStatic()
public bool isDefault()
public int getModifiers()
public mixed getValue(stdclass object)
public void setValue(stdclass object, mixed value)
public ReflectionClass getDeclaringClass()
public string getDocComment()
}
?> |
Note: getDocComment() was added in PHP 5.1.0.
To introspect a property, you will first have to create an instance of the ReflectionProperty class. You can then call any of the above methods on this instance.
Example 19-38. Using the ReflectionProperty class
|
Note: Trying to get or set private or protected class property's values will result in an exception being thrown.
The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().
<?php
class ReflectionExtension implements Reflector {
final private __clone()
public __construct(string name)
public string __toString()
public static string export(string name, bool return)
public string getName()
public string getVersion()
public ReflectionFunction[] getFunctions()
public array getConstants()
public array getINIEntries()
public ReflectionClass[] getClasses()
public array getClassNames()
}
?> |
To introspect an extension, you will first have to create an instance of the ReflectionExtension class. You can then call any of the above methods on this instance.
Example 19-39. Using the ReflectionExtension class
|
In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.
Example 19-40. Extending the built-in classes
|
Note: Caution: If you're overwriting the constructor, remember to call the parent's constructor _before_ any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object
PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1).
Example 19-41. Type Hinting examples
Failing to satisfy the type hint results in a fatal error.
Type hinting also works with functions:
|
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().
Example 20-1. Throwing an Exception
|
A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class.
Example 20-2. The Built in Exception class
|
If a class extends the built-in Exception class and re-defines the constructor, it is highly recomended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overriden to provide a custom output when the object is presented as a string.
Example 20-3. Extending the Exception class
|
References in PHP are a means to access the same variable content by different names. They are not like C pointers; instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The most close analogy is with Unix filenames and files - variable names are directory entries, while variable contents is the file itself. References can be thought of as hardlinking in Unix filesystem.
PHP references allow you to make two variables to refer to the same content. Meaning, when you do:
it means that$a and $b
point to the same content.
Note:
$aand$bare completely equal here, that's not$ais pointing to$bor vice versa, that's$aand$bpointing to the same place.
Note: If array with references is copied, its values are not dereferenced. This is valid also for arrays passed by value to functions.
Note: If you assign, pass or return an undefined variable by reference, it will get created.
The same syntax can be used with functions, that return references, and with new operator (in PHP 4.0.4 and later):
Since PHP 5, new return reference automatically so using =& in this context is deprecated and produces E_STRICT level message.Note: Not using the & operator causes a copy of the object to be made. If you use $this in the class it will operate on the current instance of the class. The assignment without & will copy the instance (i.e. the object) and $this will operate on the copy, which is not always what is desired. Usually you want to have a single instance to work with, due to performance and memory consumption issues.
While you can use the @ operator to mute any errors in the constructor when using it as @new, this does not work when using the &new statement. This is a limitation of the Zend Engine and will therefore result in a parser error.
| Warning | ||
If you assign a reference to a variable declared global
inside a function, the reference will be visible only inside the function.
You can avoid this by using the
|
Note: If you assign a value to a variable with references in a foreach statement, the references are modified too.
The second thing references do is to pass variables by-reference. This is done by making a local variable in a function and a variable in the calling scope reference to the same content. Example:
will make$a to be 6. This happens because in
the function foo the variable
$var refers to the same content as
$a. See also more detailed explanations about passing by reference.
The third thing reference can do is return by reference.
As said before, references aren't pointers. That means, the following construct won't do what you expect:
What happens is that $var in
foo will be bound with
$bar in caller, but then it will be
re-bound with $GLOBALS["baz"]. There's no way
to bind $bar in the calling scope to something else
using the reference mechanism, since $bar is not
available in the function foo (it is represented by
$var, but $var has only
variable contents and not name-to-value binding in the calling
symbol table).
You can use returning
references to reference variables selected by the function.
You can pass variable to function by reference, so that function could modify its arguments. The syntax is as follows:
Note that there's no reference sign on function call - only on function definition. Function definition alone is enough to correctly pass the argument by reference. In recent versions of PHP you will get a warning saying that "Call-time pass-by-reference" is deprecated when you use a & in foo(&$a);.The following things can be passed by reference:
Variable, i.e. foo($a)
New statement, i.e. foo(new foobar())
Reference, returned from a function, i.e.:
See also explanations about returning by reference.Any other expression should not be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:
These requirements are for PHP 4.0.4 and later.Returning by-reference is useful when you want to use a function to find which variable a reference should be bound to. Do not use return-by-reference to increase performance, the engine is smart enough to optimize this on its own. Only return references when you have a valid technical reason to do it! To return references, use this syntax:
<?php
function &find_var($param)
{
/* ...code... */
return $found_var;
}
$foo =& find_var($bar);
$foo->x = 2;
?> |
find_var function would be set, not the
copy, as it would be without using reference syntax.
Note: Unlike parameter passing, here you have to use & in both places - to indicate that you return by-reference, not a copy as usual, and to indicate that reference binding, rather than usual assignment, should be done for
$foo.
Note: If you try to return a reference from a function with the syntax: return ($found_var); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. E_NOTICE error is issued since PHP 4.4.0 and PHP 5.1.0 if the code tries to return a dynamic expression or a result of the new operator.
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:
won't unset$b, just $a.
Again, it might be useful to think about this as analogous to Unix unlink call.
Many syntax constructs in PHP are implemented via referencing mechanisms, so everything told above about reference binding also apply to these constructs. Some constructs, like passing and returning by-reference, are mentioned above. Other constructs that use references are:
When you declare variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:
That means, for example, that unsetting $var
won't unset global variable.
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, and proper coding practices, it can give 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.
The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.
This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.
A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.
The best security is often unobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.
A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.
When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.
The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.
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.php 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.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, 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.
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 --enable-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.php nor by redirection http://my.host/dir/script.php.
Redirection can be configured in Apache by using AddHandler and Action directives (see below).
This compile-time option prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. 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 php-script /cgi-bin/php AddHandler php-script .php |
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.
To include active content, like scripts and executables, in the web server document directories is sometimes considered 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 a URL like http://my.host/~user/doc.php does not
result in opening a file under users home directory, but a file
called ~user/doc.php 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.php will open a file called doc.php 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.php.
user_dir expansion happens regardless of
the doc_root setting, so you can control
the document root and user directory access
separately.
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:
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.
When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.
Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.
A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilities in some other way.
Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.
There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.
PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.
Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.
Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.
Example 26-2. ... A filesystem attack
|
Only allow limited permissions to the PHP web user binary.
Check all variables which are submitted.
Example 26-3. More secure file name checking
|
Example 26-4. More secure file name checking
|
Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.
Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.
As you can surmise, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.
Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.
The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.
Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.
You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.
You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.
You may want to establish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.
SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.
Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.
The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.
In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may also be taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().
Example 27-1. Using hashed password field
|
Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.
Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.
Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.
$offset
is encoded into the URL. The script expects that the incoming
$offset is a decimal number. However, what if someone tries to
break in by appending a urlencode()'d form of the
following to the URL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
-- |
Note: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.
A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.
$query, the query beast awakened.
SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.
$uid to
change the admin's password, or simply sets $pwd to
"hehehe', admin='yes', trusted=100 " (with a trailing
space) to gain more privileges. Then, the query will be twisted:
<?php // $uid == ' or uid like'%admin%'; -- $query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --"; // $pwd == "hehehe', admin='yes', trusted=100 " $query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE ...;"; ?> |
A frightening example how operating system level commands can be accessed on some database hosts.
$prod, then the $query will be:
<?php
$query = "SELECT * FROM products
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);
?> |
Note: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.
You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.
These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.
Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.
If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().
Example 27-6. A more secure way to compose a query for paging
|
Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_escape_string(), sql_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable.
Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.
You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.
Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.
With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.
A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:
The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occurred in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:
Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.
For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.
A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.
A filesystem or general PHP error can indicate what permissions the web server has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.
There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.
One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.
Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.
When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:
Example 29-1. Example misuse with register_globals = on
|
When register_globals = on, our logic above may be compromised. When
off, $authorized can't be set via request so it'll
be fine, although it really is generally a good programming practice to
initialize variables first. For example, in our example above we might
have first done $authorized = false. Doing this
first means our above code would work with register_globals on or off as
users by default would be unauthorized.
Another example is that of sessions.
When register_globals = on, we could also use
$username in our example below but again you must
realize that $username could also come from other
means, such as GET (through the URL).
Example 29-2. Example use of sessions with register_globals on or off
|
It's even possible to take preventative measures to warn when forging is
being attempted. If you know ahead of time exactly where a variable
should be coming from, you can check to see if the submitted data is
coming from an inappropriate kind of submission. While it doesn't
guarantee that data has not been forged, it does require an attacker to
guess the right kind of forging. If you don't care where the request
data comes from, you can use $_REQUEST as it contains
a mix of GET, POST and COOKIE data. See also the manual section on
using variables from outside
of PHP.
Example 29-3. Detecting simple variable poisoning
|
Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.
For information about emulating register_globals being On or Off, see this FAQ.
Superglobals: availability note: Since PHP 4.1.0, superglobal arrays such as
$_GET,$_POST, and$_SERVER, etc. have been available. For more information, read the manual section on superglobals
The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.
Example 30-1. Dangerous Variable Usage
|
You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:
Will this script only affect the intended files?
Can unusual or undesirable data be acted upon?
Can this script be used in unintended ways?
Can this be used in conjunction with other scripts in a negative manner?
Will any transactions be adequately logged?
By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.
You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.
There are three magic quote directives:
Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP.
See also get_magic_quotes_gpc().
If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP.
See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped.
See also ini_get() for retrieving its value.
Useful for beginners
Magic quotes are implemented in PHP to help code written by beginners from being dangerous. Although SQL Injection is still possible with magic quotes on, the risk is reduced.
Convenience
For inserting data into a database, magic quotes essentially runs addslashes() on all Get, Post, and Cookie data, and does so automagically.
Portability
Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
Performance
Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient.
Although php.ini-dist enables these directives by default, php.ini-recommended disables it. This recommendation is mainly due to performance reasons.
Inconvenience
Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().
The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.
Example 31-1. Disabling magic quotes server side An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.
If access to the server configuration is unavailable, use of .htaccess is also an option. For example:
|
In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.
Example 31-2. Disabling magic quotes at runtime
|
In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.
A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php = off in your php.ini file, you reduce the amount of information available to them.
Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:
PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance security and repair any flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.
Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.
The HTTP Authentication hooks in PHP are only available when it is
running as an Apache module and is hence not available in the CGI version.
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
predefined variables
PHP_AUTH_USER, PHP_AUTH_PW,
and AUTH_TYPE set to the user name, password and
authentication type respectively. These predefined variables are found
in the $_SERVER and
$HTTP_SERVER_VARS arrays. Both "Basic" and "Digest"
(since PHP 5.1.0) authentication methods are supported. See the
header() function for more information.
PHP Version Note: Superglobals, such as $_SERVER, became available in PHP 4.1.0.
$HTTP_SERVER_VARShas been available since PHP 3.
An example script fragment which would force client authentication on a page is as follows:
Example 34-1. Basic HTTP Authentication example
|
Example 34-2. Digest HTTP Authentication example This example shows you how to implement a simple Digest HTTP authentication script. For more information read the RFC 2617.
|
Compatibility Note: Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above.
Instead of simply printing out PHP_AUTH_USER
and PHP_AUTH_PW, as done in the above example,
you may 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.
As of PHP 4.3.0, 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 and safe mode is enabled. Regardless,
REMOTE_USER can be used
to identify the externally-authenticated user. So, you can use
$_SERVER['REMOTE_USER'].
Configuration Note: PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.
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.
Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.
Example 34-3. HTTP Authentication example forcing a new name/password
|
This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.
Also note that until PHP 4.3.3, HTTP Authentication did not work using Microsoft's IIS server with the CGI version of PHP due to a limitation of IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.
Another limitation is if you're using the IIS module (ISAPI) and PHP 4, you may not use the PHP_AUTH_* variables but instead, the variable HTTP_AUTHORIZATION is available. For example, consider the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
IIS Note:: For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).
Note: If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.
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() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.
Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name.
Depending on register_globals,
regular PHP variables can be created from cookies. However it's not
recommended to rely on them as this feature is often turned off for the
sake of security.
$HTTP_COOKIE_VARS is also set in earlier versions of PHP
when the track_vars configuration
variable is set. (This setting is always on since PHP 4.0.3.)
For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function.
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.
XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.
The first key difference in XForms is how the form is sent to the client. XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.
Example 37-1. A simple XForms search form
|
The above form displays a text input box (named q),
and a submit button. When the submit button is clicked, the form will be
sent to the page referred to by action.
Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.
If you're choosing to work with XForms then you probably want that data as
XML, in that case, look in $HTTP_RAW_POST_DATA where
you'll find the XML document generated by the browser which you can pass
into your favorite XSLT engine or document parser.
If you're not interested in formatting and just want your data to be loaded
into the traditional $_POST variable, you can instruct
the client browser to send it as application/x-www-form-urlencoded
by changing the method attribute to
urlencoded-post.
Example 37-2. Using an XForm to populate
|
Note: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.
This feature lets people upload both text and binary files. With PHP's authentication and file manipulation 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.
PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch).
Related Configurations Note: See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini
PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.
Example 38-1. File Upload Form A file upload screen can be built by creating a special form which looks something like this:
The __URL__ in the above example should be replaced, and point to a PHP file. The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. Fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. The PHP settings for maximum-size, however, cannot be fooled. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too big and the transfer failed. |
Note: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
The global $_FILES
exists as of PHP 4.1.0 (Use $HTTP_POST_FILES
instead if using an earlier version).
These arrays will contain all the uploaded file information.
The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.
$_FILES['userfile']['name']The original name of the file on the client machine.
$_FILES['userfile']['type']The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size']The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name']The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error']The error code associated with this file upload. This element was added in PHP 4.2.0
Files will, by default be stored in the server's default temporary
directory, unless another location has been given with the upload_tmp_dir directive in
php.ini. The server's default directory can
be changed by setting the environment variable
TMPDIR in the environment in which PHP runs.
Setting it using putenv() from within a PHP
script will not work. This environment variable can also be used
to make sure that other operations are working on uploaded files,
as well.
Example 38-2. Validating file uploads See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.
|
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
$_FILES['userfile']['size'] variable
to throw away any files that are either too small or too big. You
could use the
$_FILES['userfile']['type'] variable
to throw away any files that didn't match a certain type criteria, but
use this only as first of a series of checks, because this value
is completely under the control of the client and not checked on the PHP
side.
As of PHP 4.2.0, you could use $_FILES['userfile']['error']
and plan your logic according to the error codes.
Whatever the logic, you should either delete the file from the
temporary directory or move it elsewhere.
If no file is selected for upload in your form, PHP will return
$_FILES['userfile']['size'] as 0, and
$_FILES['userfile']['tmp_name'] as none.
The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.
Example 38-3. Uploading array of files PHP supports HTML array feature even with files.
|
Since PHP 4.2.0, PHP returns an appropriate error code along with the
file array. The error code can be found in the
error segment of the file array that is created
during the file upload by PHP. In other words, the error might be
found in $_FILES['userfile']['error'].
Value: 0; There is no error, the file uploaded with success.
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
Value: 3; The uploaded file was only partially uploaded.
Value: 4; No file was uploaded.
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0.
Note: These became PHP constants in PHP 4.3.0.
The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize ini-setting. The default is 2 Megabytes.
If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough.
If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough.
Note: max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running.
| Warning |
max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded. |
If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough.
Not validating which file you operate on may mean that users can access sensitive information in other directories.
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.
Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly.
A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]).
Multiple files can be uploaded using different name for input.
It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:
Note: Support for multiple file uploads was added in PHP 3.0.10.
When the above form is submitted, the arrays
$_FILES['userfile'],
$_FILES['userfile']['name'], and
$_FILES['userfile']['size'] will be
initialized (as well as in $HTTP_POST_FILES for PHP versions prior
to 4.1.0).
When
register_globals is on, globals for uploaded
files are also initialized. Each of these will be a numerically
indexed array of the appropriate values for the submitted files.
For instance, assume that the filenames
/home/test/review.html and
/home/test/xwp.out are submitted. In this
case, $_FILES['userfile']['name'][0]
would contain the value review.html, and
$_FILES['userfile']['name'][1] would
contain the value xwp.out. Similarly,
$_FILES['userfile']['size'][0] would
contain review.html's file size, and so forth.
$_FILES['userfile']['name'][0],
$_FILES['userfile']['tmp_name'][0],
$_FILES['userfile']['size'][0], and
$_FILES['userfile']['type'][0] are
also set.
PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:
This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <Virtualhost> block. A line like this would do the trick:
This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have.
With PHP 4 and following you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy.
Example 38-5. Saving HTTP PUT files with PHP 4
|
Note: All documentation below applies to PHP 3 only.
The only
trick here is that when PHP sees a PUT-method request it stores
the uploaded file in a temporary file just like those handled by
the POST-method.
When the request ends, this temporary file is deleted. So, your
PUT handling PHP script has to copy that file somewhere. The
filename of this temporary file is in the $PHP_PUT_FILENAME
variable, and you can see the suggested destination filename in
the $REQUEST_URI (may vary on non-Apache web servers). This
destination filename is the one that the remote client specified.
You do not have to listen to this client. You could, for example,
copy all uploaded files to a special uploads directory.
As long as allow_url_fopen is enabled in
php.ini, you can use HTTP and FTP
URLs with most of the functions
that take a filename as a parameter. In addition, URLs can be
used with the include(),
include_once(), require() and
require_once() statements.
See Appendix N for more information about the protocols
supported by PHP.
Note: In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option
--enable-url-fopen-wrapper.
Note: The Windows versions of PHP earlier than PHP 4.3 did not support remote file accessing for the following functions: include(), include_once(), require(), require_once(), and the imagecreatefromXXX functions in the Reference LXIV, Image Functions extension.
For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.
Example 39-1. Getting the title of a remote page
|
You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.
To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)
Note: The following applies to 3.0.7 and later.
Internally in PHP a connection status is maintained. There are 3 possible states:
0 - NORMAL
1 - ABORTED
2 - TIMEOUT
When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.
You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding "php_value ignore_user_abort" Apache .conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.
Your script can also be terminated by the built-in script timer.
The default timeout is 30 seconds. It can be changed using
the max_execution_time php.ini directive or the corresponding
php_value max_execution_time Apache .conf directive as well as with
the set_time_limit() function. When the timer
expires the script will be aborted and as with the above client
disconnect case, if a shutdown function has been registered it will
be called. Within this shutdown function you can check to see if
a timeout caused the shutdown function to be called by calling the
connection_status() function. This function will
return 2 if a timeout caused the shutdown function to be called.
One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.
Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.
Why?
This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.
The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.
The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.
The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before. Note that SAPI support is not available in PHP 3.
If persistent connections don't have any added functionality, what are they good for?
The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.
Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.
| Warning |
There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is that when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere). |
An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!
See also fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), ora_plogon(), pfsockopen(), pg_pconnect(), and sybase_pconnect().
The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now.
| Warning |
Safe Mode was removed in PHP 6.0.0. |
Table 42-1. Security and Safe Mode Configuration Directives
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| safe_mode | "0" | PHP_INI_SYSTEM | |
| safe_mode_gid | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0. |
| safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Available since PHP 4.1.0. |
| safe_mode_exec_dir | "" | PHP_INI_SYSTEM | |
| safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | |
| safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | |
| open_basedir | NULL | PHP_INI_SYSTEM | |
| disable_functions | "" | php.ini only | Available since PHP 4.0.1. |
| disable_classes | "" | php.ini only | Available since PHP 4.3.2. |
Here's a short explanation of the configuration directives.
safe_mode
booleanWhether to enable PHP's safe mode.
safe_mode_gid
booleanBy default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.
safe_mode_include_dir
stringUID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).
As of PHP 4.2.0, this directive can take a colon (semi-colon on Windows) separated path in a fashion similar to the include_path directive, rather than just a single directory.
The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "safe_mode_include_dir = /dir/incl/"
If the value of this directive is empty, no files with different UID/GID can be included in PHP 4.2.3 and as of PHP 4.3.3. In earlier versions, all files could be included.
safe_mode_exec_dir
stringIf PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.
safe_mode_allowed_env_vars
stringSetting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).
Note: If this directive is empty, PHP will let the user modify ANY environment variable!
safe_mode_protected_env_vars
stringThis directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.
open_basedir
stringLimit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.
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 working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().
In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".
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.
The restriction specified with open_basedir is actually a prefix, not a directory name. This means that "open_basedir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "open_basedir = /dir/incl/"
Note: Support for multiple directories was added in 3.0.7.
The default is to allow all files to be opened.
disable_functions
stringThis directive allows you to disable certain functions for security reasons. It takes on a comma-delimited list of function names. disable_functions is not affected by Safe Mode.
This directive must be set in php.ini For example, you cannot set this in httpd.conf.
disable_classes
stringThis directive allows you to disable certain classes for security reasons. It takes on a comma-delimited list of class names. disable_classes is not affected by Safe Mode.
This directive must be set in php.ini For example, you cannot set this in httpd.conf.
Availability note: This directive became available in PHP 4.3.2
See also: register_globals, display_errors, and log_errors.
When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:
-rw-rw-r-- 1 rasmus rasmus 33 Jul 1 19:20 script.php -rw-r--r-- 1 root root 1116 May 26 18:01 /etc/passwd |
<?php
readfile('/etc/passwd');
?> |
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2 |
However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.
If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory. For example (Apache httpd.conf example):
<Directory /docroot> php_admin_value open_basedir /docroot </Directory> |
Warning: open_basedir restriction in effect. File is in wrong directory in /docroot/script.php on line 2 |
You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:
disable_functions readfile,system |
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2 |
| Warning |
These PHP restrictions are not valid in executed binaries, of course. |
This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.
Table 42-2. Safe mode limited functions
| Function | Limitations |
|---|---|
| dbmopen() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| dbase_open() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| filepro() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| filepro_rowcount() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| filepro_retrieve() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| ifx_* | sql_safe_mode restrictions, (!= safe mode) |
| ingres_* | sql_safe_mode restrictions, (!= safe mode) |
| mysql_* | sql_safe_mode restrictions, (!= safe mode) |
| pg_lo_import() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| posix_mkfifo() | Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| putenv() | Obeys the safe_mode_protected_env_vars and safe_mode_allowed_env_vars ini-directives. See also the documentation on putenv() |
| move_uploaded_file() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| chdir() | Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| dl() | This function is disabled in safe mode. |
| backtick operator | This function is disabled in safe mode. |
| shell_exec() (functional equivalent of backticks) | This function is disabled in safe mode. |
| exec() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| system() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| passthru() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| popen() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| fopen() | Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| mkdir() | Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| rmdir() | Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| rename() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| unlink() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| copy() | Checks whether the files or directories you are
about to operate on have the same UID (owner) as the script that is being
executed. Checks whether the directory in which
you are about to operate has the same UID (owner) as the script that is being
executed. (on
source and
target) |
| chgrp() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| chown() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. |
| chmod() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits |
| touch() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. |
| symlink() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only the target is checked) |
| link() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only the target is checked) |
| apache_request_headers() | In safe mode, headers beginning with 'authorization' (case-insensitive) will not be returned. |
| header() | In safe mode, the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication). |
| PHP_AUTH variables |
In safe mode, the variables PHP_AUTH_USER,
PHP_AUTH_PW, and AUTH_TYPE
are not available in $_SERVER. Regardless, you
can still use REMOTE_USER for the USER.
(note: only affected since PHP 4.3.0)
|
| highlight_file(), show_source() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1) |
| parse_ini_file() | Checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. Checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1) |
| set_time_limit() | Has no effect when PHP is running in safe mode. |
| max_execution_time | Has no effect when PHP is running in safe mode. |
| mail() | In safe mode, the fifth parameter is disabled. (note: only affected since PHP 4.2.3) |
| Any function that uses php4/main/fopen_wrappers.c | ?? |
As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It's worth mentioning that CLI and CGI are different SAPI's although they do share many of the same behaviors.
The CLI SAPI was released for the first time with
PHP 4.2.0, but was still experimental and had
to be explicitly enabled with --enable-cli when running
./configure. Since PHP 4.3.0 the
CLI SAPI is no longer experimental and the option
--enable-cli is on by default. You may use
--disable-cli to disable it.
As of PHP 4.3.0, the name, location and existence of the CLI/CGI binaries
will differ depending on how PHP is installed on your system. By default
when executing make, both the CGI and CLI are built and
placed as sapi/cgi/php and sapi/cli/php
respectively, in your PHP source directory. You will note that both are
named php. What happens during make install depends on
your configure line. If a module SAPI is chosen during configure, such as apxs, or the
--disable-cgi option is used, the CLI is copied to
{PREFIX}/bin/php during make install
otherwise the CGI is placed there. So, for example, if --with--apxs
is in your configure line then the CLI is copied to
{PREFIX}/bin/php during make
install. If you want to override the installation of the CGI
binary, use make install-cli after make
install. Alternatively you can specify
--disable-cgi in your configure line.
Note: Because both
--enable-cliand--enable-cgiare enabled by default, simply having--enable-cliin your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.
The Windows packages between PHP 4.2.0 and PHP 4.2.3 distributed the CLI as php-cli.exe, living in the same folder as the CGI php.exe. Starting with PHP 4.3.0 the Windows package distributes the CLI as php.exe in a separate folder named cli, so cli/php.exe . Starting with PHP 5, the CLI is distributed in the main folder, named php.exe. The CGI version is distributed as php-cgi.exe.
As of PHP 5, a new php-win.exe file is distributed.
This is equal to the CLI version, except that php-win doesn't output
anything and thus provides no console (no "dos box" appears on the screen).
This behavior is similar to php-gtk. You should configure with
--enable-cli-win32.
What SAPI do I have?: From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.
Note: A Unix manual page was added in PHP 4.3.2. You may view this by typing man php in your shell environment.
Remarkable differences of the CLI SAPI compared to other SAPIs:
Unlike the CGI SAPI, no headers are written to the output.
Though the CGI SAPI provides a way to suppress HTTP headers, there's no equivalent switch to enable them in the CLI SAPI.
CLI is started up in quiet mode by default, though the -q
and --no-header switches are kept for compatibility so
that you can use older CGI scripts.
It does not change the working directory to that of the script.
(-C and --no-chdir switches kept for
compatibility)
Plain text error messages (no HTML formatting).
There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:
Table 43-1. Overridden php.ini directives
| Directive | CLI SAPI default value | Comment |
|---|---|---|
| html_errors | FALSE | It can be quite hard to read the error message in your shell when it's cluttered with all those meaningless HTML tags, therefore this directive defaults to FALSE. |
| implicit_flush | TRUE | It is desired that any output coming from print(), echo() and friends is immediately written to the output and not cached in any buffer. You still can use output buffering if you want to defer or manipulate standard output. |
| max_execution_time | 0 (unlimited) | Due to endless possibilities of using PHP in shell environments, the maximum execution time has been set to unlimited. Whereas applications written for the web are often executed very quickly, shell application tend to have a much longer execution time. |
| register_argc_argv | TRUE |
Because this setting is TRUE you will always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments) in the CLI SAPI.
As of PHP 4.3.0, the PHP variables |
Note: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv).
To ease working in the shell environment, the following constants are defined:
Table 43-2. CLI specific Constants
| Constant | Description | ||
|---|---|---|---|
| STDIN |
An already opened stream to stdin. This saves
opening it with
| ||
| STDOUT |
An already opened stream to stdout. This saves
opening it with
| ||
| STDERR |
An already opened stream to stderr. This saves
opening it with
|
Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:
php -r 'fwrite(STDERR, "stderr\n");' |
The CLI SAPI does not change the current directory to the directory of the executed script!
Example showing the difference to the CGI SAPI:
<?php // Our simple test application named test.php echo getcwd(), "\n"; ?> |
When using the CGI version, the output is:
$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directory |
This clearly shows that PHP changes its current directory to the one of the executed script.
Using the CLI SAPI yields:
$ pwd /tmp $ php -f another_directory/test.php /tmp |
This allows greater flexibility when writing shell tools in PHP.
Note: The CGI SAPI supports this CLI SAPI behaviour by means of the
-Cswitch when run from the command line.
The list of command line options provided by the PHP
binary can be queried anytime by running PHP with the
-h switch:
Usage: php [options] [-f] <file> [--] [args...]
php [options] -r <code> [--] [args...]
php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
php [options] -- [args...]
php [options] -a
-a Run as interactive shell
-c <path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse and execute <file>.
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r <code> Run PHP <code> without using script tags <?..?>
-B <begin_code> Run PHP <begin_code> before processing input lines
-R <code> Run PHP <code> for every input line
-F <file> Parse and execute <file> for every input line
-E <end_code> Run PHP <end_code> after processing all input lines
-H Hide any passed arguments from external tools.
-s Display colour syntax highlighted source.
-v Version number
-w Display source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.
args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin
--rf <name> Show information about function <name>.
--rc <name> Show information about class <name>.
--re <name> Show information about extension <name>.
--ri <name> Show configuration for extension <name>. |
The CLI SAPI has three different ways of getting the PHP code you want to execute:
Telling PHP to execute a certain file.
Both ways (whether using the -f switch or not) execute
the file my_script.php. You can choose any file to
execute - your PHP scripts do not have to end with the
.php extension but can have any name or extension
you wish.
Pass the PHP code to execute directly on the command line.
Special care has to be taken in regards of shell variable substitution and quoting usage.
Note: Read the example carefully, there are no beginning or ending tags! The
-rswitch simply does not need them. Using them will lead to a parser error.
Provide the PHP code to execute via standard input (stdin).
This gives the powerful ability to dynamically create PHP code and feed it to the binary, as shown in this (fictional) example:
Like every shell application, the PHP binary
accepts a number of arguments but your PHP script can
also receive arguments. The number of arguments which can be passed to your script
is not limited by PHP (the shell has a certain size limit
in the number of characters which can be passed; usually you won't hit this
limit). The arguments passed to your script are available in the global
array $argv. The zero index always contains the script
name (which is - in case the PHP code
is coming from either standard input or from the command line switch
-r). The second registered global variable is
$argc which contains the number of elements in the
$argv array (not the
number of arguments passed to the script).
As long as the arguments you want to pass to your script do not start with the - character, there's nothing special to watch out for. Passing an argument to your script which starts with a - will cause trouble because PHP itself thinks it has to handle it. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every argument following it is passed untouched to your script.
# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]
# This will pass the '-h' argument to your script and prevent PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
} |
However, there's another way of using PHP for shell scripting. You can write a script where the first line starts with #!/usr/bin/php. Following this you can place normal PHP code included within the PHP starting and end tags. Once you have set the execution attributes of the file appropriately (e.g. chmod +x test) your script can be executed like a normal shell or perl script:
Example 43-1. Execute PHP script as shell script
Assuming this file is named test in the current directory, we can now do the following:
|
As you see, in this case no care needs to be taken when passing parameters which start with - to your script.
Long options are available since PHP 4.3.3.
Table 43-3. Command line options
| Option | Long Option | Description | |||
|---|---|---|---|---|---|
| -a | --interactive |
Runs PHP interactively. If you compile PHP with the Readline extension (which is not available on Windows), you'll have a nice shell, including a completion feature (e.g. you can start typing a variable name, hit the TAB key and PHP completes its name) and a typing history that can be accessed using the arrow keys. The history is saved in the ~/.php_history file.
| |||
| -c | --php-ini |
This option can either specify a directory where to look for php.ini or specify a custom INI file (which does not need to be named php.ini), e.g.: If you don't specify this option, file is searched in default locations. | |||
| -n | --no-php-ini |
Ignore php.ini at all. This switch is available since PHP 4.3.0. | |||
| -d | --define |
This option allows you to set a custom value for any of the configuration directives allowed in php.ini. The syntax is:
Examples (lines are wrapped for layout reasons):
| |||
| -e | --profile-info |
Activate the extended information mode, to be used by a debugger/profiler. | |||
| -f | --file |
Parses and executed the given filename to the | |||
| -h and -? | --help and --usage | With this option, you can get information about the actual list of command line options and some one line descriptions about what they do. | |||
| -i | --info | This command line option calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore quite huge. | |||
| -l | --syntax-check |
This option provides a convenient way to only perform a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to 255.
This option won't find fatal errors (like undefined functions). Use
| |||
| -m | --modules | ||||
| -r | --run |
This option allows execution of PHP right from within the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parser error if present.
| |||
| -B | --process-begin |
PHP code to execute before processing stdin. Added in PHP 5. | |||
| -R | --process-code |
PHP code to execute for every input line. Added in PHP 5.
There are two special variables available in this mode:
| |||
| -F | --process-file |
PHP file to execute for every input line. Added in PHP 5. | |||
| -E | --process-end |
PHP code to execute after processing the input. Added in PHP 5. | |||
| -s | --syntax-highlight and --syntax-highlight |
Display colour syntax highlighted source. This option uses the internal mechanism to parse the file and produces a HTML highlighted version of it and writes it to standard output. Note that all it does it to generate a block of <code> [...] </code> HTML tags, no HTML headers.
| |||
| -v | --version | ||||
| -w | --strip |
Display source with stripped comments and whitespace.
| |||
| -z | --zend-extension |
Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually specified /etc/ld.so.conf on Linux systems). Passing a filename with an absolute path information will not use the systems library search path. A relative filename with a directory information will tell PHP only to try to load the extension relative to the current directory. | |||
| --rf | --rfunction |
Shows information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2.
| |||
| --rc | --rclass |
Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2. | |||
| --re | --rextension |
Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2. | |||
| -ri | --rextinfo |
Shows the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. |
The PHP executable can be used to run PHP scripts absolutely independent from the web server. If you are on a Unix system, you should add a special first line to your PHP script, and make it executable, so the system will know, what program should run the script. On a Windows platform you can associate php.exe with the double click option of the .php files, or you can make a batch file to run the script through PHP. The first line added to the script to work on Unix won't hurt on Windows, so you can write cross platform programs this way. A simple example of writing a command line PHP program can be found below.
Example 43-4. Script intended to be run from command line (script.php)
|
In the script above, we used the special first line to indicate
that this file should be run by PHP. We work with a CLI version
here, so there will be no HTTP header printouts. There are two
variables you can use while writing command line applications with
PHP: $argc and $argv. The
first is the number of arguments plus one (the name of the script
running). The second is an array containing the arguments, starting
with the script name as number zero ($argv[0]).
In the program above we checked if there are less or more than one
arguments. Also if the argument was --help,
-help, -h or -?,
we printed out the help message, printing the script name dynamically.
If we received some other argument we echoed that out.
If you would like to run the above script on Unix, you need to make it executable, and simply call it as script.php echothis or script.php -h. On Windows, you can make a batch file for this task:
Assuming you named the above program script.php, and you have your CLI php.exe in C:\php\php.exe this batch file will run it for you with your added options: script.bat echothis or script.bat -h.
See also the Readline extension documentation for more functions you can use to enhance your command line applications in PHP.
See also Appendix J.
| Warning |
This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
These functions are only available when running PHP as an Apache module.
Note: As of PHP 4.3.2,
PATH_TRANSLATEDis no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as theSCRIPT_FILENAMEserver variable when it's not populated by Apache. This change was made to comply with the CGI specification thatPATH_TRANSLATEDshould only exist ifPATH_INFOis defined.Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define
PATH_INFO.
The behaviour of the Apache PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by php_flag settings in the server configuration file or local .htaccess files.
Table 1. Apache configuration options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| engine | "1" | PHP_INI_ALL | Available since PHP 4.0.5. |
| child_terminate | "0" | PHP_INI_ALL | Available since PHP 4.0.5. |
| last_modified | "0" | PHP_INI_ALL | Available since PHP 4.0.5. |
| xbithack | "0" | PHP_INI_ALL | Available since PHP 4.0.5. |
Here's a short explanation of the configuration directives.
engine
booleanTurns PHP parsing on or off. 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.
child_terminate
booleanSpecify whether PHP scripts may request child process termination on end of request, see also apache_child_terminate().
last_modified
booleanSend PHP scripts modification date as Last-Modified: header for this request.
xbithack
booleanParse files with executable bit set as PHP regardless of their file ending.
apache_child_terminate() will register the Apache process executing the current PHP request for termination once execution of PHP code it is completed. It may be used to terminate a process after a script with high memory consumption has been run as memory will usually only be freed internally but not given back to the operating system.
Returns TRUE if PHP is running as an Apache 1 module, the Apache version is non-multithreaded, and the child_terminate PHP directive is enabled (disabled by default). If these conditions are not met, FALSE is returned and an error of level E_WARNING is generated.
Get an Apache environment variable as specified by
variable.
This function requires Apache 2 otherwise it's undefined.
variableThe Apache environment variable
walk_to_topWhether to get the top-level variable available to all Apache layers.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
apache_lookup_uri -- Perform a partial request for the specified URI and return all info about itThis performs a partial request for a URI. It goes just far enough to obtain all the important information about the given resource.
This function is only supported when PHP is installed as an Apache module.
An object of related URI information. The properties of this object are:
| status |
| the_request |
| status_line |
| method |
| content_type |
| handler |
| uri |
| filename |
| path_info |
| args |
| boundary |
| no_cache |
| no_local_copy |
| allowed |
| send_bodyct |
| bytes_sent |
| byterange |
| clength |
| unparsed_uri |
| mtime |
| request_time |
Example 1. apache_lookup_uri() example
The above example will output something similar to:
|
apache_note() is an Apache-specific function which gets and sets values in a request's notes table.
If called with one argument, it returns the current value of note note_name. If called with two arguments, it sets the value of note note_name to note_value and returns the previous value of note note_name. If the note cannot be retrieved, FALSE is returned.
Fetches all HTTP requests from the current request.
This function is only supported when PHP is installed as an Apache module.
An associative array of all the HTTP headers in the current request, or FALSE on failure.
Example 1. apache_request_headers() example
The above example will output something similar to:
|
Note: Prior to PHP 4.3.0, apache_request_headers() was called getallheaders(). After PHP 4.3.0, getallheaders() is an alias for apache_request_headers().
Note: You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.
Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.
apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.
This function requires Apache 1.
Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.
apache_setenv() sets the value of the Apache
environment variable specified by
variable.
Note: When setting an Apache environment variable, the corresponding $_SERVER variable is not changed.
variableThe environment variable that's being set.
value
The new variable value.
walk_to_topWhether to set the top-level variable available to all Apache layers.
Note: apache_setenv() can be paired up with apache_getenv() across separate pages or for setting variables to pass to Server Side Includes (.shtml) that have been included in PHP scripts.
ascii2ebcdic() is an Apache-specific function which
is available only on EBCDIC based operating systems (OS/390, BS2000).
It translates the ASCII encoded string ascii_str
to its equivalent EBCDIC representation (binary safe), and returns
the result.
ebcdic2ascii() is an Apache-specific function which
is available only on EBCDIC based operating systems (OS/390, BS2000).
It translates the EBCDIC encoded string ebcdic_str
to its equivalent ASCII representation (binary safe), and returns
the result.
Fetches all HTTP requests from the current request.
This function is an alias for apache_request_headers(). Please read the apache_request_headers() documentation for more information on how this function works.
This function is only supported when PHP is installed as an Apache module.
An associative array of all the HTTP headers in the current request, or FALSE on failure.
| Version | Description |
|---|---|
| 4.3.0 | Became an alias for apache_request_headers(). Essentially, it was renamed. This is because this function only works with Apache. |
Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.
virtual() is an Apache-specific function which is similar 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.
To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.
This function is only supported when PHP is installed as an Apache module.
| Warning |
The query string can be passed to the included file but
|
Note: Environment variables set in the requested file are not visible to the calling script.
Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. It was conceived of to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.
This PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/apc.
The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/
Note: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks TMP, TEMP, USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.
Note: For more in-depth, highly technical implementation details, see the developer-supplied TECHNOTES file .
The behaviour of these functions is affected by settings in php.ini.
Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.
There are two main decisions you have to make. First, how much shared memory do you want to set aside for APC, and second, whether you want APC to check if a file has been modified on every request. The two ini directives involved here are apc.shm_size and apc.stat. Read the sections on these two directives carefully below.
Once you have a running server, you should copy the apc.php script that comes with the extension to somewhere in your docroot and load it up in your browser. It provides you with a detailed look at what is happening in your cache. If you have GD enabled in PHP, it will even have pretty graphs. First thing to check is of course that it is actually caching files. Assuming it is working you should then pay close attention to the Cache full count number on the left. That tells you the number of times the cache has filled up and has had to forcefully clean up any entries not accessed within the last apc.ttl seconds. You should configure your cache to minimize this number. If you are constantly filling your cache, the resulting cache churn is going to hurt performance. You should either set more memory aside for APC, or use apc.filters to cache fewer scripts.
Table 1. APC configuration options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in APC <= 3.0.12p2 |
| apc.shm_segments | "1" | PHP_INI_SYSTEM | |
| apc.shm_size | "30" | PHP_INI_SYSTEM | |
| apc.optimization | "0" | PHP_INI_ALL | |
| apc.num_files_hint | "1000" | PHP_INI_SYSTEM | |
| apc.ttl | "0" | PHP_INI_SYSTEM | |
| apc.gc_ttl | "3600" | PHP_INI_SYSTEM | |
| apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12p2 |
| apc.filters | NULL | PHP_INI_SYSTEM | |
| apc.mmap_file_mask | NULL | PHP_INI_SYSTEM | |
| apc.slam_defense | "0" | PHP_INI_SYSTEM | |
| apc.file_update_protection | "2" | PHP_INI_SYSTEM | |
| apc.enable_cli | "0" | PHP_INI_SYSTEM | > APC 3.0.6 |
| apc.max_file_size | "1M" | PHP_INI_SYSTEM | > APC 3.0.6 |
| apc.stat | "1" | PHP_INI_SYSTEM | > APC 3.0.9 |
Here's a short explanation of the configuration directives.
apc.enabled
booleanapc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).
apc.shm_segments
integerThe number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but you have already set apc.shm_size as high as your system allows, you can try raising this value.
apc.shm_size
integerThe size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.
apc.optimization
integerThe optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.
apc.num_files_hint
integerA "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if you're not sure; this setting is mainly useful for sites that have many thousands of source files.
apc.ttl
integerThe number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.
apc.gc_ttl
integerThe number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.
apc.cache_by_default
booleanOn by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.
apc.filters
stringA comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.
apc.mmap_file_mask
stringIf compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.
apc.slam_defense
integerOn very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.
apc.file_update_protection
integerWhen you modify a file on a live web server you really should do so in an atomic manner. That is, write to a temporary file and rename (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If you are certain you always atomically update your files by using something like rsync which does this correctly, you can turn this protection off by setting it to 0. If you have a system that is flooded with io causing some update procedure to take longer than 2 seconds, you may want to increase this a bit.
apc.enable_cli
integerMostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Normally you wouldn't want to create, populate and tear down the APC cache on every CLI request, but for various test scenarios it is handy to be able to enable APC for the CLI version of APC easily.
apc.max_file_size
integerPrevent files larger than this value from getting cached. Defaults to 1M.
apc.stat
integerBe careful if you change this setting. The default is for this to be On which means that APC will stat (check) the script on each request to see if it has been modified. If it has been modified it will recompile and cache the new version. If you turn this setting off, it will not check. That means that in order to have changes become active you need to restart your web server. On a production server where you rarely change the code, turning stats off can produce a significant performance boost.
For included/required files this option applies as well, but note that if you are using relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.
(no version information, might be only in CVS)
apc_add -- Cache a variable in the data store (only if it's not stored)Note: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).
key
Store the variable using this name. keys are
cache-unique, so attempting to use apc_add() to
store data with a key that already exists will not overwrite the
existing data, and will instead return FALSE. (This is the only
difference between apc_add() and
apc_store().)
varThe variable to store
ttl
Time To Live; store var in the cache for
ttl seconds. After the
ttl has passed, the stored variable will be
expunged from the cache (on the next request). If no ttl
is supplied (or if the ttl is
0), the value will persist until it is removed from
the cache manually, or otherwise fails to exist in the cache (clear,
restart, etc.).
Array of cached data (and meta-data), or FALSE on failure
Note: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.
cache_type
If cache_type is "user",
information about the user cache will be returned; otherwise,
information about the system cache (cached files) will be returned.
limited
If limited is TRUE, the
return value will exclude the individual list of cache entries. This
is usefull when trying to optimize calls for statistics gathering.
Example 1. A apc_cache_info() example
The above example will output something similar to:
|
cache_type
If cache_type is "user", the
user cache will be cleared; otherwise, the system cache (cached files)
will be cleared.
define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.
For a better-performing solution, try the hidef extension from PECL.
Note: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the
constantsparameter, effectively clearing the stored value(s).
key
The key serves as the name of the constant set
being stored. This key is used to retrieve the
stored constants in apc_load_constants().
constantsAn associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.
case_sensitiveThe default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
keyThe name of the constant set (that was stored with apc_define_constants()) to be retrieved.
case_sensitiveThe default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
Note: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).
key
Store the variable using this name. keys are
cache-unique, so storing a second value with the same
key will overwrite the original value.
varThe variable to store
ttl
Time To Live; store var in the cache for
ttl seconds. After the
ttl has passed, the stored variable will be
expunged from the cache (on the next request). If no ttl
is supplied (or if the ttl is
0), the value will persist until it is removed from
the cache manually, or otherwise fails to exist in the cache (clear,
restart, etc.).
APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.
| Caution |
APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer). |
APD is currently available as a PECL extension from http://pecl.php.net/package/apd. Make sure you have installed the CGI version of PHP and it is available in your current path along with the phpize script.
Run the following command to download, build, and install the latest stable version of APD:
pear install apd |
This automatically installs the APD Zend module into your PHP extensions directory. It is not mandatory to keep it there; you can store the module in any directory PHP can read as long as you set the zend_extension parameter accordingly.
Windows users can download the extension dll php_apd.dll from http://snaps.php.net/win32/PECL_STABLE/.
In your INI file, add the following lines:
zend_extension = /absolute/path/to/apd.so apd.dumpdir = /absolute/path/to/trace/directory apd.statement_tracing = 0 |
Depending on your PHP build, the zend_extension directive can be one of the following:
zend_extension (non ZTS, non debug build) zend_extension_ts ( ZTS, non debug build) zend_extension_debug (non ZTS, debug build) zend_extension_debug_ts ( ZTS, debug build) |
To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.
The behaviour of these functions is affected by settings in php.ini.
Table 1. APD Configuration Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apd.dumpdir | NULL | PHP_INI_ALL | |
| apd.statement_tracing | "0" | PHP_INI_ALL |
Here's a short explanation of the configuration directives.
apd.dumpdir
stringSets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.
You can specify a different directory as an argument to apd_set_pprof_trace().
apd.statement_tracing
booleanSpecfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Table 2. APD constants
| Constant | Value | Description |
|---|---|---|
| FUNCTION_TRACE (integer) | 1 | |
| ARGS_TRACE (integer) | 2 | |
| ASSIGNMENT_TRACE (integer) | 4 | |
| STATEMENT_TRACE (integer) | 8 | |
| MEMORY_TRACE (integer) | 16 | |
| TIMING_TRACE (integer) | 32 | |
| SUMMARY_TRACE (integer) | 64 | |
| ERROR_TRACE (integer) | 128 | |
| PROF_TRACE (integer) | 256 | |
| APD_VERSION (string) | example: 1.0.2-dev |
As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:
apd_set_pprof_trace(); |
You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.
Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.
Tip: If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php
To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:
bash-2.05b$ pprofp -R /tmp/pprof.22141.0 Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace |
The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.
To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to apd@mail.communityconnect.com. Any help is very welcome.
This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
Example 1. Typical session using tcplisten
|
(no version information, might be only in CVS)
apd_callstack -- Returns the current call stack as an arrayBehaves like perl's Carp::cluck. Throw a warning and a callstack.
Usually sent via the socket to restart the interpreter.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
(no version information, might be only in CVS)
apd_croak -- Throw an error, a callstack and then exitBehaves like perl's Carp::croak. Throw an error, a callstack and then exit.
(no version information, might be only in CVS)
apd_dump_function_table -- Outputs the current function table(no version information, might be only in CVS)
apd_dump_persistent_resources -- Return all persistent resources as an arrayReturn all persistent resources as an array.
(no version information, might be only in CVS)
apd_dump_regular_resources -- Return all current regular resources as an arrayReturn all current regular resources as an array.
Usually sent via the socket to request information about the running script.
(no version information, might be only in CVS)
apd_get_active_symbols -- Get an array of the current variables names in the local scopeReturns the names of all the variables defined in the active scope, (not their values).
Starts debugging to pprof_{process_id} in the dump directory.
dump_directoryThe directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.
Starts debugging to apd_dump_{process_id} in the dump directory.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
dump_directoryThe directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.
(no version information, might be only in CVS)
apd_set_session -- Changes or sets the current debugging levelThis can be used to increase or decrease debugging in a different area of your application.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
(no version information, might be only in CVS)
apd_set_socket_session_trace -- Starts the remote session debugging
Connects to the specified tcp_server (eg. tcplisten)
and sends debugging data to the socket.
tcp_serverIP or Unix Domain socket (like a file) of the TCP server.
socket_typeCan be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.
portYou can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
Overrides built-in functions by replacing them in the symbol table.
function_nameThe function to override.
function_argsThe function arguments, as a coma separated string.
Usually you will want to pass this parameter, as well as the
function_code parameter, as a single quote
delimited string. The reason for using single quoted strings, is to
protect the variable names from parsing, otherwise, if you use double
quotes there will be a need to escape the variable names, e.g.
\$your_var.
function_codeThe new code for the function.
Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.
These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.
Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays.
Please see the Arrays section of the manual for a detailed explanation of how arrays are implemented and used in PHP. See also Array operators for other ways how to manipulate the arrays.
The constants below are always available as part of the PHP core.
CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case().
CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case.
Sorting order flags:
SORT_ASC is used with array_multisort() to sort in ascending order.
SORT_DESC is used with array_multisort() to sort in descending order.
Sorting type flags: used by various sort functions
SORT_REGULAR is used to compare items normally.
SORT_NUMERIC is used to compare items numerically.
SORT_STRING is used to compare items as strings.
SORT_LOCALE_STRING is used to compare items as strings, based on the current locale. Added in PHP 4.4.0 and 5.0.2.
(PHP 4 >= 4.2.0, PHP 5)
array_change_key_case -- Returns an array with all string keys lowercased or uppercased
array_change_key_case() changes the
keys in the input array to
be all lowercase or uppercase. The change depends
on the last optional case
parameter. You can pass two constants there,
CASE_UPPER and
CASE_LOWER. The default is
CASE_LOWER. The function will leave
number indices as is.
If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices.
array_chunk() splits the array into
several arrays with size values
in them. You may also have an array with less values
at the end. You get the arrays as members of a
multidimensional array indexed with numbers starting
from zero.
By setting the optional preserve_keys
parameter to TRUE, you can force PHP to preserve the original
keys from the input array. If you specify FALSE new number
indices will be used in each resulting array with
indices starting from zero. The default is FALSE.
Example 1. array_chunk() example
The above example will output:
|
Returns an array by using the values from the
keys array as keys and the values from the
values array as the corresponding values.
Returns FALSE if the number of elements for each array isn't equal or if the arrays are empty.
See also array_merge(), array_walk(), and array_values().
array_count_values() returns an array using
the values of the input array as keys and
their frequency in input as values.
See also count(), array_unique(), array_values(), and count_chars().
(PHP 4 >= 4.3.0, PHP 5)
array_diff_assoc -- Computes the difference of arrays with additional index check
array_diff_assoc() returns an array
containing all the values from array1
that are not present in any of the other arguments.
Note that the keys are used in the comparison unlike
array_diff().
Example 1. array_diff_assoc() example
The above example will output:
|
In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.
Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same.
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);.
See also array_diff(), array_intersect(), and array_intersect_assoc().
array_diff_key() returns an array
containing all the values of array1
that have keys that are not present in any of the other arguments.
Note that the associativity is preserved. This function is like
array_diff() except the comparison is done on the
keys instead of the values.
Example 1. array_diff_key() example
The above example will output:
|
The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc(), array_intersect_key() and array_intersect_ukey().
(PHP 5)
array_diff_uassoc -- Computes the difference of arrays with additional index check which is performed by a user supplied callback function
array_diff_uassoc() returns an array
containing all the values from array1
that are not present in any of the other arguments.
Note that the keys are used in the comparison unlike
array_diff().
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff_assoc() where an internal function for comparing the indices is used.
Example 1. array_diff_uassoc() example
The above example will output:
|
In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.
The equality of 2 indices is checked by the user supplied callback function.
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.
See also array_diff(), array_diff_assoc(), array_udiff(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5 >= 5.1.0RC1)
array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparison
array_diff_ukey() returns an array
containing all the values of array1
that have keys that are not present in any of the other arguments.
Note that the associativity is preserved. This function is like
array_diff() except the comparison is done on the
keys instead of the values.
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
Example 1. array_diff_ukey() example
The above example will output:
|
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc(), array_intersect_key() and array_intersect_ukey().
array_diff() returns an array
containing all the values of array1
that are not present in any of the other arguments.
Note that keys are preserved.
Example 1. array_diff() example
Multiple occurrences in $array1 are all treated the same way. This will output :
|
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.
| Warning |
This was broken in PHP 4.0.4! |
See also array_diff_assoc(), array_intersect(), and array_intersect_assoc().
(no version information, might be only in CVS)
array_fill_keys -- Fill an array with values, specifying keys
array_fill_keys() fills an array with the
value of the value parameter, using the
values of the keys array as keys.
See also array_fill() and array_combine().
array_fill() fills an array with
num entries of the value of the
value parameter, keys starting at the
start_index parameter. Note that
num must be a number greater than zero, or PHP will throw
a warning.
See also str_repeat() and range().
array_filter() iterates over each value in
the input array passing them to the
callback function. If the
callback function returns true, the current
value from input is returned into the
result array. Array keys are preserved.
Example 1. array_filter() example
The above example will output:
|
Users may not change the array itself from the callback function. e.g. Add/delete an element, unset the array that array_filter() is applied to. If the array is changed, the behavior of this function is undefined.
If the callback function is not supplied,
array_filter() will remove all the entries of
input that are equal to FALSE. See converting to boolean
for more information.
See also array_map(), array_reduce(), and array_walk().
array_flip() returns an array in flip
order, i.e. keys from trans become values and values
from trans become keys.
Note that the values of trans need to be valid
keys, i.e. they need to be either integer or
string. A warning will be emitted if a value has the wrong
type, and the key/value pair in question will not be
flipped.
If a value has several occurrences, the latest key will be used as its values, and all others will be lost.
array_flip() returns FALSE if it fails.
See also array_values(), array_keys(), and array_reverse().
(PHP 4 >= 4.3.0, PHP 5)
array_intersect_assoc -- Computes the intersection of arrays with additional index check
array_intersect_assoc() returns an array
containing all the values of array1
that are present in all the arguments. Note that the keys are used in
the comparison unlike in array_intersect().
Example 1. array_intersect_assoc() example
The above example will output:
|
In our example you see that only the pair "a" =>
"green" is present in both arrays and thus is returned.
The value "red" is not returned because in
$array1 its key is 0 while
the key of "red" in $array2 is
1.
The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.
See also array_intersect(), array_uintersect_assoc(), array_intersect_uassoc(), array_uintersect_uassoc(), array_diff() and array_diff_assoc().
(PHP 5 >= 5.1.0RC1)
array_intersect_key -- Computes the intersection of arrays using keys for comparison
array_intersect_key() returns an array
containing all the values of array1
which have matching keys that are present in all the arguments.
Example 1. array_intersect_key() example
The above example will output:
|
In our example you see that only the keys 'blue'
and 'green' are present in both arrays and thus
returned. Also notice that the values for the keys
'blue' and 'green' differ between
the two arrays. A match still occurs because only the keys are checked.
The values returned are those of array1.
The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc() and array_intersect_ukey().
(PHP 5)
array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback function
array_intersect_uassoc() returns an array
containing all the values of array1
that are present in all the arguments. Note that the keys are used in
the comparison unlike in array_intersect().
The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Example 1. array_intersect_uassoc() example
The above example will output:
|
See also array_intersect(), array_intersect_assoc(), array_uintersect_assoc(), array_uintersect_uassoc(), array_intersect_key() and array_intersect_ukey().
(PHP 5 >= 5.1.0RC1)
array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparison
array_intersect_ukey() returns an array
containing all the values of array1
which have matching keys that are present in all the arguments.
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
Example 1. array_intersect_ukey() example
The above example will output:
|
In our example you see that only the keys 'blue'
and 'green' are present in both arrays and thus
returned. Also notice that the values for the keys
'blue' and 'green' differ between
the two arrays. A match still occurs because only the keys are checked.
The values returned are those of array1.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc() and array_intersect_key().
array_intersect() returns an array
containing all the values of array1
that are present in all the arguments.
Note that keys are preserved.
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
See also array_intersect_assoc(), array_diff(), and array_diff_assoc().
array_key_exists() returns TRUE if the
given key is set in the array.
key can be any value possible
for an array index. array_key_exists() also works
on objects.
Note: The name of this function is key_exists() in PHP 4.0.6.
Example 2. array_key_exists() vs isset() isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.
|
See also isset(), array_keys(), and in_array().
array_keys() returns the keys, numeric and
string, from the input array.
If the optional search_value is specified,
then only the keys for that value are returned. Otherwise, all
the keys from the input are returned.
As of PHP 5, you can use strict parameter for
comparison including type (===).
Example 1. array_keys() example
The above example will output:
|
See also array_values() and array_key_exists().
array_map() returns an array containing all
the elements of arr1 after applying the
callback function to each one.
The number of parameters that the callback
function accepts
should match the number of arrays
passed to the array_map()
Example 2. array_map() - using more arrays
The above example will output:
|
Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, the shortest one will be extended with empty elements.
An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function
Example 3. Creating an array of arrays
The above example will output:
|
See also array_filter(), array_reduce(), array_walk(), create_function(), and information about the callback type.
array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.
Example 1. array_merge_recursive() example
The above example will output:
|
See also array_merge().
array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.
Example 1. array_merge() example
The above example will output:
|
Example 2. Simple array_merge() example
Don't forget that numeric keys will be renumbered!
If you want to completely preserve the arrays and just want to append them to each other, use the + operator:
The numeric key will be preserved and thus the association remains.
|
| Warning | |
The behavior of array_merge() was modified in PHP 5. Unlike PHP 4, array_merge() now only accepts parameters of type array. However, you can use typecasting to merge other types. See the example below for details.
|
See also array_merge_recursive(), array_combine() and array operators.
Returns TRUE on success or FALSE on failure.
array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.
Associative (string) keys will be maintained, but numeric keys will be re-indexed.
The input arrays are treated as columns of a table to be sorted by rows - this resembles the functionality of SQL ORDER BY clause. The first array is the primary one to sort by. The rows (values) in that array that compare the same are sorted by the next input array, and so on.
The argument structure of this function is a bit unusual, but flexible. The first argument has to be an array. Subsequently, each argument can be either an array or a sorting flag from the following lists.
Sorting order flags:
SORT_ASC - Sort in ascending order
SORT_DESC - Sort in descending order
Sorting type flags:
SORT_REGULAR - Compare items normally
SORT_NUMERIC - Compare items numerically
SORT_STRING - Compare items as strings
No two sorting flags of the same type can be specified after each array. The sorting flags specified after an array argument apply only to that array - they are reset to default SORT_ASC and SORT_REGULAR before each new array argument.
Example 1. Sorting multiple arrays
In this example, after sorting, the first array will contain "10", "a", 100, 100. The second array will contain 1, 1, "2", 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.
|
Example 2. Sorting multi-dimensional array
In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).
|
Example 3. Sorting database results
For this example, each element in the Example data:
The data as an array, called
In this example, we will order by We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.
The dataset is now sorted, and will look like this:
|
Example 4. Case insensitive sorting Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter. To perform a case insensitive search, force the sorting order to be determined by a lowercase copy of the original array.
The above example will output:
|
array_pad() returns a copy of the
input padded to size specified by
pad_size with value
pad_value. If
pad_size is positive then the array is
padded on the right, if it's negative then on the left. If the
absolute value of pad_size is less than or
equal to the length of the input then no
padding takes place.
It is possible to add most 1048576 elements at a time.
See also array_fill() and range().
array_pop() pops and returns the last value of
the array, shortening the
array by one element.
If array is empty (or is not an array),
NULL will be returned.
See also array_push(), array_shift(), and array_unshift().
array_product() returns the product of values in an array as an integer or float.
array_push() treats
array as a stack, and pushes the passed
variables onto the end of array. The
length of array increases by the number of
variables pushed. Has the same effect as:
<?php $array[] = $var; ?> |
var.
Returns the new number of elements in the array.
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.
See also array_pop(), array_shift(), and array_unshift().
array_rand() is rather useful when you want to
pick one or more random entries out of an array. It takes an
input array and an optional argument
num_req which specifies how many entries you
want to pick - if not specified, it defaults to 1.
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.
See also shuffle().
(PHP 4 >= 4.0.5, PHP 5)
array_reduce -- Iteratively reduce the array to a single value using a callback function
array_reduce() applies iteratively the
function function to the elements of the
array input, so as to reduce the array to
a single value. If the optional initial is
available, it will be used at the beginning of the process, or as
a final result in case the array is empty.
If the array is empty and initial is not passed,
array_reduce() returns NULL.
This will result in $b containing
15, $c containing
1200 (= 10*1*2*3*4*5), and
$d containing 1.
See also array_filter(), array_map(), array_unique(), and array_count_values().
array_reverse() takes input
array and returns a new array with the
order of the elements reversed, preserving the keys if
preserve_keys is TRUE.
Example 1. array_reverse() example
This makes both
|
Note: The second parameter was added in PHP 4.0.3.
See also array_flip().
(PHP 4 >= 4.0.5, PHP 5)
array_search -- Searches the array for a given value and returns the corresponding key if successful
Searches haystack for
needle and returns the key if it is found in
the array, FALSE otherwise.
Note: If
needleis a string, the comparison is done in a case-sensitive manner.
Note: Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.
If the optional third parameter strict is set to
TRUE then the array_search()
will also check the types of the needle
in the haystack.
If needle is found in
haystack more than once, the first matching key
is returned. To return the keys for all matching values, use
array_keys() with the optional
search_value parameter instead.
| Warning |
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. |
See also array_keys(), array_values(), array_key_exists(), and in_array().
array_shift() shifts the first value of the
array off and returns it, shortening the
array by one element and moving everything
down. All numerical array keys will be modified to start counting from zero
while literal keys won't be touched. If array is empty
(or is not an array), NULL will be returned.
See also array_unshift(), array_push(), and array_pop().
array_slice() returns the sequence of elements
from the array array as specified by the
offset and length
parameters.
If offset is non-negative, the sequence will
start at that offset in the array. If
offset is negative, the sequence will
start that far from the end of the array.
If length is given and is positive, then
the sequence will have that many elements in it. If
length is given and is negative then the
sequence will stop that many elements from the end of the
array. If it is omitted, then the sequence will have everything
from offset up until the end of the
array.
Note that array_slice() will reset numeric array
keys by default. Since PHP 5.0.2, you can change this behaviour by
setting preserve_keys to TRUE.
Example 1. array_slice() examples
The above example will output:
|
See also array_splice() and unset().
array_splice() removes the elements designated
by offset and
length from the
input array, and replaces them with the
elements of the replacement array, if
supplied. It returns an array containing the extracted elements.
Note that numeric keys in input are not preserved.
If offset is positive then the start of
removed portion is at that offset from the beginning of the
input array. If
offset is negative then it starts that far
from the end of the input array.
If length is omitted, removes everything
from offset to the end of the array. If
length is specified and is positive, then
that many elements will be removed. If
length is specified and is negative then
the end of the removed portion will be that many elements from
the end of the array. Tip: to remove everything from
offset to the end of the array when
replacement is also specified, use
count($input) for
length.
If replacement array is specified, then
the removed elements are replaced with elements from this array.
If offset and
length are such that nothing is removed,
then the elements from the replacement
array are inserted in the place specified by the
offset. Note that keys in replacement
array are not preserved.
If replacement is just one element it is
not necessary to put array()
around it, unless the element is an array itself.
The following statements change the values of $input
the same way:
Table 1. array_splice() equivalents
| array_push($input, $x, $y) | array_splice($input, count($input), 0, array($x, $y)) |
| array_pop($input) | array_splice($input, -1) |
| array_shift($input) | array_splice($input, 0, 1) |
| array_unshift($input, $x, $y) | array_splice($input, 0, 0, array($x, $y)) |
| $input[$x] = $y // for arrays where key equals offset | array_splice($input, $x, 1, $y) |
Returns the array consisting of removed elements.
Example 1. array_splice() examples
|
See also array_slice(), unset(), and array_merge().
array_sum() returns the sum of values in an array as an integer or float.
Note: PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which most of the time converted them to zero, depending on their value).
(PHP 5)
array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback function
array_udiff_assoc() returns an array
containing all the values from array1
that are not present in any of the other arguments.
Note that the keys are used in the comparison unlike
array_diff() and array_udiff().
The comparison of arrays' data is performed by using an user-supplied
callback. In this aspect the behaviour is opposite to the behaviour of
array_diff_assoc() which uses internal function for
comparison.
Example 1. array_udiff_assoc() example
The above example will output:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback function
array_udiff_uassoc() returns an array
containing all the values from array1
that are not present in any of the other arguments.
Note that the keys are used in the comparison unlike
array_diff() and array_udiff().
The comparison of arrays' data is performed by using an user-supplied
callback : data_compare_func. In this aspect
the behaviour is opposite to the behaviour of
array_diff_assoc() which uses internal function for
comparison. The comparison of keys (indices) is done also by the
callback function key_compare_func. This
behaviour is unlike what array_udiff_assoc() does, since
the latter compares the indices by using an internal function.
Example 1. array_udiff_uassoc() example
The above example will output:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function. Keep in mind that you have to supply 2 callback functions.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_assoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff -- Computes the difference of arrays by using a callback function for data comparison
array_udiff() returns an array
containing all the values of array1
that are not present in any of the other arguments.
Note that keys are preserved. For the comparison of the data
data_compare_func is used.
It must return an integer less than, equal
to, or greater than zero if the first argument is considered to
be respectively less than, equal to, or greater than the
second. This is unlike array_diff() which uses an
internal function for comparing the data.
Example 1. array_udiff() example
The above example will output:
|
Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], "data_compare_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback function
array_uintersect_assoc() returns an array
containing all the values of array1
that are present in all the arguments. Note that the keys are used in
the comparison unlike in array_uintersect().
The data is compared by using a callback function.
Example 1. array_uintersect_assoc() example
The above example will output:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().
(PHP 5)
array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
array_uintersect_uassoc() returns an array
containing all the values of array1
that are present in all the arguments. Note that the keys are used in
the comparison unlike in array_uintersect().
Both the data and the indexes are compared by using a callback functions.
Example 1. array_uintersect_uassoc() example
The above example will output:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_assoc().
(PHP 5)
array_uintersect -- Computes the intersection of arrays, compares data by a callback function
array_uintersect() returns an array
containing all the values of array1
that are present in all the arguments.
The data is compared by using a callback function.
Example 1. array_uintersect() example
The above example will output:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_intersect(), array_uintersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().
array_unique() takes input
array and returns a new array
without duplicate values.
Note that keys are preserved. array_unique() sorts
the values treated as string at first, then will keep the first key
encountered for every value, and ignore all following keys. It does not
mean that the key of the first related value from the unsorted
array will be kept.
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
The first element will be used.
array_unshift() prepends passed elements to
the front of the array. Note that the list
of elements is prepended as a whole, so that the prepended
elements stay in the same order. All numerical array keys will be
modified to start counting from zero while literal keys won't be touched.
Returns the new number of elements in the
array.
See also array_shift(), array_push(), and array_pop().
array_values() returns all the values from the
input array and indexes numerically the
array.
See also array_keys().
Applies the user-defined function funcname to each
element of the input array. This function will recur
into deeper arrays. Typically, funcname takes on two
parameters. The input parameter's value being the first, and
the key/index second. If the optional userdata
parameter is supplied, it will be passed as the third parameter to
the callback funcname.
Returns TRUE on success or FALSE on failure.
Note: If
funcnameneeds to be working with the actual values of the array, specify the first parameter offuncnameas a reference. Then, any changes made to those elements will be made in the original array itself.
Example 1. array_walk_recursive() example
The above example will output:
You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function. |
See also array_walk(), and information about the callback type.
Returns TRUE on success or FALSE on failure.
Applies the user-defined function funcname to each
element of the array array. Typically,
funcname takes on two parameters.
The array parameter's value being the first, and
the key/index second. If the optional userdata
parameter is supplied, it will be passed as the third parameter to
the callback funcname.
If function funcname requires more parameters than
given to it, an error of level
E_WARNING will be generated each time array_walk()
calls funcname. These warnings may be suppressed by
prepending the PHP error operator
@ to the
array_walk() call, or by using
error_reporting().
Note: If
funcnameneeds to be working with the actual values of the array, specify the first parameter offuncnameas a reference. Then, any changes made to those elements will be made in the original array itself.
Note: Passing the key and userdata to
funcnamewas added in 4.0.0
array_walk() is not affected by the internal
array pointer of array.
array_walk() will walk through the entire array
regardless of pointer position.
Users may not change the array itself from the callback function. e.g. Add/delete elements, unset elements, etc. If the array that array_walk() is applied to is changed, the behavior of this function is undefined, and unpredictable.
Example 1. array_walk() example
The above example will output:
|
See also array_walk_recursive(), create_function(), list(), foreach, each(), call_user_func_array(), and array_map(), and information about the callback type.
Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.
Note: array() is a language construct used to represent literal arrays, and not a regular function.
Syntax "index => values", separated by commas, define index and values. index may be of type string or numeric. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first.
Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.
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.
Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.
This example creates a 1-based array.
As in Perl, you can access a value from the array inside double quotes. However, with PHP you'll need to enclose your array between curly braces.
See also array_pad(), list(), count(), foreach, and range().
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.
Returns TRUE on success or FALSE on failure.
The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort().
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.
Returns TRUE on success or FALSE on failure.
The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort().
compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.
For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract(). It returns the output array with all the variables added to it.
Any strings that are not set will simply be skipped.
Gotcha: Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().
Example 1. compact() example
The above example will output:
|
See also extract().
Returns the number of elements in var,
which is typically an array, since anything else
will have one element.
For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, count(), which returns the return value for the count() function.
If var is not an array or an object with
implemented Countable interface,
1 will be returned.
There is one exception, if var is NULL,
0 will be returned.
Note: The optional
modeparameter is available as of PHP 4.2.0.
If the optional mode parameter is set to
COUNT_RECURSIVE (or 1), count()
will recursively count the array. This is particularly useful for
counting all the elements of a multidimensional array. The default
value for mode is 0.
count() does not detect infinite recursion.
| Caution |
count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set. |
Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.
See also is_array(), isset(), and strlen().
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
The current() function simply returns the value of the array element that's currently being pointed to 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.
| Warning |
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. |
Note: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.
Example 1. Example use of current() and friends
|
(PHP 3, PHP 4, PHP 5)
each -- Return the current key and value pair from an array and advance the array cursor
Returns the current key and 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 contain the key name of the array
element, and 1 and
value contain the data.
If the internal pointer for the array points past the end of the array contents, each() returns FALSE.
<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?> |
$bar now contains the following key/value
pairs:
Array
(
[1] => Bob
[value] => Bob
[0] => Robert
[key] => Robert
) |
each() is typically used in conjunction with list() to traverse an array, here's an example:
After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.
| Caution |
Because assigning an array to another variable resets the original
arrays pointer, our example above would cause an endless loop had we
assigned |
See also key(), list(), current(), reset(), next(), prev(), and foreach.
end() advances array's
internal pointer to the last element, and returns its value.
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
extract -- Import variables into the current symbol table from an array
This function is used to import variables from an array into the
current symbol table. It takes an associative array
var_array and treats keys as variable
names and values as variable values. For each key/value pair it
will create a variable in the current symbol table, subject to
extract_type and
prefix parameters.
Note: Beginning with version 4.0.5, this function returns the number of variables extracted.
Note: EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS were introduced in version 4.2.0.
Note: EXTR_REFS was introduced in version 4.3.0.
extract() checks each key to see whether it
has a valid variable name. It also checks for collisions with
existing variables in the symbol table. The way invalid/numeric
keys and collisions are treated is determined by the
extract_type. It can be one of the
following values:
If there is a collision, overwrite the existing variable.
If there is a collision, don't overwrite the existing variable.
If there is a collision, prefix the variable name with
prefix.
Prefix all variable names with
prefix. Beginning with PHP 4.0.5, this includes
numeric variables as well.
Only prefix invalid/numeric variable names with
prefix. This flag was added in
PHP 4.0.5.
Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example. This flag was added in PHP 4.2.0.
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table. This flag was added in PHP 4.2.0.
Extracts variables as references. This effectively means that the
values of the imported variables are still referencing the values of
the var_array parameter. You can use this flag
on its own or combine it with any other flag by OR'ing the
extract_type. This flag was added in PHP
4.3.0.
If extract_type is not specified, it is
assumed to be EXTR_OVERWRITE.
Note that prefix is only required if
extract_type is EXTR_PREFIX_SAME,
EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID
or EXTR_PREFIX_IF_EXISTS. If
the prefixed result is not a valid variable name, it is not
imported into the symbol table. Prefixes are automatically separated from
the array key by an underscore character.
extract() returns the number of variables successfully imported into the symbol table.
| Warning |
Do not use extract() on untrusted data, like
user-input ($_GET, ...). If you do, for example, if you want to run old
code that relies on
register_globals
temporarily, make sure you use one of the non-overwriting
|
A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize().
Example 1. extract() example
The above example will output:
|
The $size wasn't overwritten, because we
specified EXTR_PREFIX_SAME, which resulted in
$wddx_size being created. If EXTR_SKIP was
specified, then $wddx_size wouldn't even have been created.
EXTR_OVERWRITE would have caused $size to have
value "medium", and EXTR_PREFIX_ALL would result in new variables
being named $wddx_color,
$wddx_size, and
$wddx_shape.
You must use an associative array, a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.
See also compact().
Searches haystack for
needle and returns TRUE
if it is found in the array, FALSE otherwise.
If the third parameter strict is set to
TRUE then the in_array() function
will also check the types of
the needle in the haystack.
Note: If
needleis a string, the comparison is done in a case-sensitive manner.
Note: In PHP versions before 4.2.0
needlewas not allowed to be an array.
Example 3. in_array() with an array as needle
The above example will output:
|
See also array_search(), array_key_exists(), and isset().
key() returns the index element of the current array position.
Example 1. key() example
|
Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.
Returns TRUE on success or FALSE on failure.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort().
See also asort(), arsort(), ksort(), sort(), natsort(), and rsort().
Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
Returns TRUE on success or FALSE on failure.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort().
See also asort(), arsort(), krsort(), uksort(), sort(), natsort(), and rsort().
Note: The second parameter was added in PHP 4.
Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.
Note: list() only works on numerical arrays and assumes the numerical indices start at 0.
Example 1. list() examples
|
Example 2. An example use of list()
|
| Warning |
list() assigns the values starting with the right-most parameter. If you are using plain variables, you don't have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn't. It's assigned in the reverse order. |
Example 3. Using list() with array indices
Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):
|
This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".
Returns TRUE on success or FALSE on failure.
natcasesort() is a case insensitive version of natsort().
Example 1. natcasesort() example
The above example will output:
For more information see: Martin Pool's Natural Order String Comparison page. |
See also sort(), natsort(), strnatcmp(), and strnatcasecmp().
This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen below:
Returns TRUE on success or FALSE on failure.
Example 1. natsort() example
The above example will output:
For more information see: Martin Pool's Natural Order String Comparison page. |
See also natcasesort(), strnatcmp(), and strnatcasecmp().
Returns the array value in the next place that's pointed to 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 value. That means it returns the next array value 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.
| Warning |
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. |
Note: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.
Example 1. Example use of next() and friends
|
Returns the array value in the previous place that's pointed to by the internal array pointer, or FALSE if there are no more elements.
| Warning |
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. |
Note: You won't be able to distinguish the beginning of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.
prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.
Example 1. Example use of prev() and friends
|
range() returns an array of elements from
low to high,
inclusive. If low > high, the sequence will be from high to low.
New parameter: The optional
stepparameter was added in 5.0.0.
If a step value is given, it will be used as the
increment between elements in the sequence. step
should be given as a positive number. If not specified,
step will default to 1.
Example 1. range() examples
|
Note: Prior to PHP 4.1.0, range() only generated incrementing integer arrays. Support for character sequences and decrementing arrays was added in 4.1.0. Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.
| Caution |
In PHP versions 4.1.0 through 4.3.2, range() sees numeric strings as strings and not integers. Instead, they will be used for character sequences. For example, "4242" is treated as "4". |
See also shuffle(), array_fill(), and foreach.
reset() rewinds array's
internal pointer to the first element and returns the value of the first
array element, or FALSE if the array is empty.
Example 1. reset() example
|
This function sorts an array in reverse order (highest to lowest).
Note: This function assigns new keys for the elements in
array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
Returns TRUE on success or FALSE on failure.
The fruits have been sorted in reverse alphabetical order.
You may modify the behavior of the sort using the optional
parameter sort_flags, for details
see sort().
See also arsort(), asort(), ksort(), krsort(), sort(), and usort().
This function shuffles (randomizes the order of the elements in) an array.
Note: This function assigns new keys for the elements in
array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.
See also arsort(), asort(), ksort(), rsort(), sort(), and usort().
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
Note: This function assigns new keys for the elements in
array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
Returns TRUE on success or FALSE on failure.
The fruits have been sorted in alphabetical order.
The optional second parameter sort_flags
may be used to modify the sorting behavior using these values:
Sorting type flags:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale. Added in PHP 4.4.0 and 5.0.2. Before PHP 6, it uses the system locale, which can be changed using setlocale(). Since PHP 6, you must use the i18n_loc_set_default() function.
Note: The second parameter was added in PHP 4.
| Warning |
Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results. |
See also arsort(), asort(), ksort(), krsort(), natsort(), natcasesort(), rsort(), usort(), array_multisort(), and uksort().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
uasort -- Sort an array with a user-defined comparison function and maintain index associationThis 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. The comparison function is user-defined.
Returns TRUE on success or FALSE on failure.
See also usort(), uksort(), sort(), asort(), arsort(), ksort(), and rsort().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
uksort -- Sort an array by keys using a user-defined comparison functionuksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
Function cmp_function should accept two
parameters which will be filled by pairs of array keys.
The comparison function must return an integer less than, equal
to, or greater than zero if the first argument is considered to
be respectively less than, equal to, or greater than the
second.
Returns TRUE on success or FALSE on failure.
Example 1. uksort() example
The above example will output:
|
See also usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort(), and rsort().
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
usort -- Sort an array by values using a user-defined comparison functionThis function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Note: If two members compare as equal, their order in the sorted array is undefined. Up to PHP 4.0.6 the user defined functions would keep the original order for those elements, but with the new sort algorithm introduced with 4.1.0 this is no longer the case as there is no solution to do so in an efficient way.
Note: This function assigns new keys for the elements in
array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
Returns TRUE on success or FALSE on failure.
Note: Obviously in this trivial case the sort() function would be more appropriate.
Example 2. usort() example using multi-dimensional array
When sorting a multi-dimensional array, The above example will output:
|
Example 3. usort() example using a member function of an object
The above example will output:
|
See also uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort(), and rsort().
The aspell() functions allows you to check the spelling on a word and offer suggestions.
Note: This extension has been removed from PHP and is no longer available as of PHP 4.3.0. If you want to use spell-checking capabilities in PHP, use pspell instead. It uses pspell library and works with newer versions of aspell.
aspell works only with very old (up to .27.* or so) versions of aspell library. Neither this module, nor those versions of aspell library are supported any longer. You need the aspell library, available from: http://aspell.sourceforge.net/.
In PHP 4, these functions are only available if PHP was
configured with --with-aspell=[DIR].
(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)
aspell_check_raw -- Check a word without changing its case or trying to trim it [deprecated]aspell_check_raw() checks the spelling of a word, without changing its case or trying to trim it in any way.
dictionary_linkThe dictionnary link identifier returned by aspell_new().
wordThe tested word.
aspell_check() checks the spelling of a word.
dictionary_linkThe dictionnary link identifier returned by aspell_new().
wordThe tested word.
aspell_new() opens up a new dictionary for use with the other aspell functions.
aspell_suggest() suggest spellings for the given
word.
dictionary_linkThe dictionnary link identifier returned by aspell_new().
wordThe tested word.
For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.
Since PHP 4.0.4, libbcmath is bundled with PHP. You don't need any external libraries for this extension.
These functions are only available if PHP was
configured with --enable-bcmath.
In PHP 3, these functions are only available if PHP was not
configured with --disable-bcmath.
The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.
The behaviour of these functions is affected by settings in php.ini.
For further details and definitions of the PHP_INI_* constants, see the Appendix H.
Here's a short explanation of the configuration directives.
Sums left_operand and
right_operand.
left_operandThe left operand, as a string.
right_operandThe right operand, as a string.
scaleThis optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
Compares the left_operand to the
right_operand and returns the result as an
integer.
left_operandThe left operand, as a string.
right_operandThe right operand, as a string.
scale
The optional scale parameter is used to set the
number of digits after the decimal place which will be used in the
comparison.
Returns 0 if the two operands are equal, 1 if the
left_operand is larger than the
right_operand, -1 otherwise.
Divides the left_operand by the
right_operand.
left_operandThe left operand, as a string.
right_operandThe right operand, as a string.
scaleThis optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
Get the modulus of the left_operand using
modulus.
Multiply the left_operand by the
right_operand.
left_operandThe left operand, as a string.
right_operandThe right operand, as a string.
scaleThis optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
Raise left_operand to the power
right_operand.
left_operandThe left operand, as a string.
right_operandThe right operand, as a string.
scaleThis optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
Use the fast-exponentiation method to raise
left_operand to the power
right_operand with respect to the modulus
modulus.
left_operandThe left operand, as a string.
right_operandThe right operand, as a string.
modulusThe modulus, as a string.
scaleThis optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
Note: Because this method uses the modulus operation, non-natural numbers may give unexpected results. A natural number is any positive non-zero integer.
The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.
Sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.
operandThe operand, as a string.
scaleThis optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
Subtracts the right_operand from the
left_operand.
left_operandThe left operand, as a string.
right_operandThe right operand, as a string.
scaleThis optional parameter is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
| Warning |
This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk. |
Bcompiler was written for several reasons:
| To encode entire script in a proprietary PHP application |
| To encode some classes and/or functions in a proprietary PHP application |
| To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe. |
| To do the feasibility study for a PHP to C converter |
The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.
To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.
bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...
In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.
short installation note:
You need at least PHP 4.3.0 for the compression to work
To install on PHP 4.3.0 and later at the Unix command prompt type pear install bcompiler
To install on Windows, until the binary package distribution mechanism is finished please search the archives of the pear-general mailing list for pre-built packages. (or send an email to it if you could not find a reference)
To install on older versions you need to make some slight changes to the build.
untar the bcompiler.tgz archive into php4/ext.(Get it directly from PECL http://pecl.php.net/get/bcompiler)
If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module).
If you are using versions before PHP 4.3.0, the you will need to copy the Makefile.in.old to Makefile.in and config.m4.old to config.m4.
run phpize in ext/bcompiler
run ./buildconf in php4
run configure with
--enable-bcompiler (and your other options)
make; make install
that's it.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at alan_k@php.net. Any help is very welcome.
Reads data from a bcompiler exe file and creates classes from the bytecodes.
Example 1. bcompiler_load() example
|
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Reads data from a bzcompressed file and creates classes from the bytecodes.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.
Reads the bytecodes of a class and calls back to a user function.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Note: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.
Reads data from a open file handle and creates classes from the bytecodes.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.
Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.
filehandleA file handle as returned by fopen().
classNameThe class name, as a string.
extends
Example 1. bcompiler_write_class() example
|
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Note: This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.
Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.
filehandleA file handle as returned by fopen().
constantNameThe name of the defined constant, as a string.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
An EXE (or self executable) file consists of 3 parts:
| The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main) |
| The Bytecodes (uncompressed only for the moment) |
| The bcompiler EXE footer |
To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.
Example 1. bcompiler_write_footer() example
|
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
This function complies specified source file into bytecodes, and writes them to the open file handle.
filehandleA file handle as returned by fopen().
filenameThe source file path, as a string.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Writes the single character \x00 to indicate End of compiled data.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).
filehandleA file handle as returned by fopen().
functionNameThe function name, as a string.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.
filehandleA file handle as returned by fopen().
fileNameThe file to be compiled. You must always include or require the file you intend to compile.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Writes the header part of a bcompiler file.
filehandleA file handle as returned by fopen().
write_verCan be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.
This module uses the functions of the bzip2 library by Julian Seward. This module requires bzip2/libbzip2 version >= 1.0.x.
Bzip2 support in PHP is not enabled by default. You will
need to use the --with-bz2[=DIR]
configuration option when compiling PHP to enable bzip2 support.
This extension defines one resource type: a file pointer identifying the bz2-file to work on.
This example opens a temporary file and writes a test string to it, then prints out the contents of the file.
Example 1. Small bzip2 Example
|
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
bzcompress() compresses the given string and returns it as bzip2 encoded data.
sourceThe string to compress.
blocksize
Specifies the blocksize used during compression and should be a number
from 1 to 9 with 9 giving the best compression, but using more
resources to do so. blocksize defaults to 4.
workfactorControls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case and 30 being the default value.
Regardless of the workfactor, the generated
output is the same.
bzdecompress() decompresses the given string containing bzip2 encoded data.
sourceThe string to decompress.
smallIf TRUE, an alternative decompression algorithm will be used which uses less memory (the maximum memory requirement drops to around 2300K) but works at roughly half the speed.
See the bzip2 documentation for more information about this feature.
Returns the error number of any bzip2 error returned by the given file pointer.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Returns the error number and error string of any bzip2 error returned by the given file pointer.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.
Gets the error string of any bzip2 error returned by the given file pointer.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Forces a write of all buffered bzip2 data for the file pointer
bz.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
bzopen() opens a bzip2 (.bz2) file for reading or writing.
filenameThe name of the file to open.
modeSimilar to the fopen() function ('r' for read, 'w' for write, etc.).
If the open fails, bzopen() returns FALSE, otherwise it returns a pointer to the newly opened file.
bzread() reads from the given bzip2 file pointer.
Reading stops when length (uncompressed) bytes have
been read or EOF is reached, whichever comes first.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
lengthIf not specified, bzread() will read 1024 (uncompressed) bytes at a time.
bzwrite() writes a string into the given bzip2 file stream.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
dataThe written data.
length
If supplied, writing will stop after length
(uncompressed) bytes have been written or the end of
data is reached, whichever comes first.
The calendar extension 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 from January 1st, 4713 B.C. 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 Julian Day Count, visit http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.
To get these functions to work, you have to compile PHP with
--enable-calendar.
The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The following constants are available since PHP 4.3.0 :
The following constants are available since PHP 5.0.0 :
(PHP 4 >= 4.1.0, PHP 5)
cal_days_in_month -- Return the number of days in a month for a given year and calendar
This function will return the number of days in the
month of year for
the specified calendar.
See also jdtounix().
cal_from_jd() converts the Julian day given in
jd into a date of the specified
calendar. Supported
calendar values are
CAL_GREGORIAN,
CAL_JULIAN,
CAL_JEWISH and
CAL_FRENCH.
Example 1. cal_from_jd() example
The above example will output:
|
See also cal_to_jd().
cal_info() returns information on the
specified calendar.
Calendar information is returned as an array containing the
elements calname, calsymbol,
month, abbrevmonth and
maxdaysinmonth. The names of the different calendars
which can be used as calendar are as follows:
0 or CAL_GREGORIAN - Gregorian Calendar
1 or CAL_JULIAN - Julian Calendar
2 or CAL_JEWISH - Jewish Calendar
3 or CAL_FRENCH - French Revolutionary Calendar
If no calendar is specified information on all
supported calendars is returned as an array. This functionality
is available beginning with PHP 5.
Example 1. cal_info() example
The above example will output:
|
cal_to_jd() calculates the Julian day count
for a date in the specified calendar.
Supported calendars are
CAL_GREGORIAN,
CAL_JULIAN,
CAL_JEWISH and
CAL_FRENCH.
See also cal_from_jd().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
easter_date -- Get Unix timestamp for midnight on Easter of a given yearReturns the Unix timestamp corresponding to midnight on Easter of the given year.
Since PHP 4.3.0, the year
parameter is optional and defaults to the current year according to the
localtime if omitted.
| Warning |
This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. before 1970 or after 2037). |
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)
See easter_days() for calculating Easter before 1970 or after 2037.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
easter_days -- Get number of days after March 21 on which Easter falls for a given yearReturns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.
Since PHP 4.3.0, the year
parameter is optional and defaults to the current year according to the
localtime if omitted.
The method parameter was also introduced in
PHP 4.3.0 and allows to calculate easter dates based
on the Gregorian calendar during the years 1582 - 1752 when set to
CAL_EASTER_ROMAN. See the calendar constants for more valid
constants.
This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)
See also easter_date().
(PHP 3, PHP 4, PHP 5)
FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day CountConverts 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.
Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.
Although this function 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.
Returns the day of the week. Can return a string or an integer depending on the 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
| Mode | Meaning | Values |
|---|---|---|
| 0 | Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
| 1 | Gregorian | January, February, March, April, May, June, July, August, September, October, November, December |
| 2 | Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
| 3 | Julian | January, February, March, April, May, June, July, August, September, October, November, December |
| 4 | Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul |
| 5 | French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra |
Converts a Julian Day Count to the French Republican Calendar.
Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".
Converts a Julian Day Count to the Jewish Calendar.
The optional hebrew and fl
parameters became available in PHP 5.0.0
If the hebrew parameter is set to TRUE, the
fl parameter is used for Hebrew, string based,
output format. The available formats are:
CAL_JEWISH_ADD_ALAFIM_GERESH,
CAL_JEWISH_ADD_ALAFIM,
CAL_JEWISH_ADD_GERESHAYIM.
Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".
This function will return a Unix timestamp corresponding to the
Julian Day given in jday or FALSE if
jday is not inside the Unix epoch
(Gregorian years between 1970 and 2037 or 2440588 <=
jday <= 2465342 ). The time returned is
localtime (and not GMT).
See also unixtojd().
Although this function 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.
Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.
Although this function 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.
| Caution |
Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count. |
Return the Julian Day for a Unix timestamp
(seconds since 1.1.1970), or for the current day if no
timestamp is given.
See also jdtounix().
These functions interface the CCVS API, allowing you to work directly with CCVS from your PHP scripts. CCVS is RedHat's solution to the "middle-man" in credit card processing. It lets you directly address the credit card clearing houses via your *nix box and a modem. Using the CCVS module for PHP, you can process credit cards directly through CCVS via your PHP Scripts. The following references will outline the process.
Note: CCVS has been discontinued by Red Hat and there are no plans to issue further keys or support contracts. Those looking for a replacement can consider MCVE by Main Street Softworks as a potential replacement. It is similar in design and has documented PHP support!
This extension has been removed from PHP and is no longer available as of PHP 4.3.0. If you want to use credit card processing features you can use MCVE instead.
To enable CCVS Support in PHP, first verify your CCVS installation
directory. You will then need to configure PHP with the --with-ccvs option. If you use this
option without specifying the path to your CCVS installation, PHP
will attempt to look in the default CCVS Install location
(/usr/local/ccvs). If CCVS is in a non-standard location,
run configure with: --with-ccvs=[DIR], where
DIR is the path to your CCVS installation. Please note that CCVS support
requires that DIR/lib and DIR/include exist, and include
cv_api.h under the include directory and
libccvs.a under the lib directory.
Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)
RedHat has discontinued support for CCVS; however, a slightly outdated manual is still available at http://www.redhat.com/docs/manuals/ccvs/.
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
(4.0.2 - 4.2.3 only)
ccvs_command -- Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API| Warning |
This function is currently not documented; only the argument list is available. |
(4.0.2 - 4.2.3 only)
ccvs_count -- Find out how many transactions of a given type are stored in the system| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which an object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).
In this example, we first define a base class and an extension
of the class. The base class describes a general vegetable,
whether it is edible or not and what is its color. The subclass
Spinach adds a method to cook it and another to
find out if it is cooked.
Example 1. classes.inc
|
We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.
Example 2. test_script.php
One important thing to note in the example above is that
the object
|
(PHP 4 >= 4.0.5, PHP 5)
call_user_method_array -- Call a user method given with an array of parameters [deprecated]| Warning |
The call_user_method_array() function is deprecated as of PHP 4.1.0, use the call_user_func_array() variety with the array(&$obj, "method_name") syntax instead. |
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
call_user_method -- Call a user method on an specific object [deprecated]| Warning |
The call_user_method() function is deprecated as of PHP 4.1.0, use the call_user_func() variety with the array(&$obj, "method_name") syntax instead. |
This function checks if the given class have been defined.
Example 2.
|
Returns an array of method names defined for the class specified by
class_name. In case of an error, it returns NULL.
Example 1. get_class_methods() example
The above example will output:
|
Get the default properties of the given class.
Returns an associative array of default public properties of the class. The resulting array elements are in the form of varname => value.
Example 1. get_class_vars() example
The above example will output:
|
Returns the name of the class of which object is an
instance. Returns FALSE if object is not an
object.
Example 1. Using get_class()
The above example will output:
|
Returns an array of the names of the declared classes in the current script.
Note: In PHP 4.0.1, three extra classes are returned at the beginning of the array: stdClass (defined in Zend/zend.c), OverloadedTestClass (defined in ext/standard/basic_functions.c) and Directory (defined in ext/standard/dir.c).
Also note that depending on what libraries you have compiled into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.
Returns an associative array of defined object properties for the
specified object. If a property have not been
assigned a value, it will be returned with a NULL value.
Example 1. Use of get_object_vars()
The above example will output:
|
Retrieves the parent class name for object or class.
Returns the name of the parent class of the class of which
object is an instance or the name.
If called without parameter outside object, this function returns FALSE.
| Version | Description |
|---|---|
| Before 5.1.0 | If called without parameter outside object, this function would have returned NULL with a warning. |
| Since 5.0.0 |
The object parameter is optional if called
from the object's method.
|
| Since 4.0.5 |
If object is a string, returns the name of the
parent class of the class with that name.
|
Example 1. Using get_parent_class()
The above example will output:
|
Checks if the given interface has been defined.
Returns TRUE if the interface given by
interface_name has been defined, FALSE otherwise.
(PHP 4 >= 4.2.0, PHP 5)
is_a -- Checks if the object is of this class or has this class as one of its parents
Checks if the given object is of this class or has
this class as one of its parents.
Note: The is_a() function is deprecated as of PHP 5 in favor of the instanceof type operator.
Returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.
Checks if the given object has the class
class_name as one of its parents.
This function returns TRUE if the object object,
belongs to a class which is a subclass of
class_name, FALSE otherwise.
Example 1. is_subclass_of() example
The above example will output:
|
Checks if the class method exists in the given
object.
Returns TRUE if the method given by method_name
has been defined for the given object, FALSE
otherwise.
This function checks if the given property exists in
the specified class (and if it is accessible from the current scope).
Note: As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.
classThe class name or an object of the class to test for
propertyThe name of the property
Returns TRUE if the property exists, FALSE if it doesn't exist or NULL in case of an error.
Example 1. A property_exists() example
|
These functions allow the dynamic manipulation of PHP classes, at runtime.
Note: This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.
This PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/classkit.
The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Note: This function cannot be used to manipulate the currently running (or chained) method.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Example 1. classkit_import() example
The above example will output:
|
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
classnameThe class to which this method will be added
methodnameThe name of the method to add
argsComma-delimited list of arguments for the newly-created method
code
The code to be evaluated when methodname
is called
flagsThe type of method to create, can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE
Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Example 1. classkit_method_add() example
The above example will output:
|
| classkit_method_copy() |
| classkit_method_redefine() |
| classkit_method_remove() |
| classkit_method_rename() |
| create_function() |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dClassDestination class for copied method
dMethodDestination method name
sClassSource class of the method to copy
sMethod
Name of the method to copy from the source class. If this parameter is
omitted, the value of dMethod is assumed.
Example 1. classkit_method_copy() example
The above example will output:
|
| classkit_method_add() |
| classkit_method_redefine() |
| classkit_method_remove() |
| classkit_method_rename() |
Note: This function cannot be used to manipulate the currently running (or chained) method.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
classnameThe class in which to redefine the method
methodnameThe name of the method to redefine
argsComma-delimited list of arguments for the redefined method
code
The new code to be evaluated when methodname
is called
flagsThe redefined method can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE
Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Example 1. classkit_method_redefine() example
The above example will output:
|
| classkit_method_add() |
| classkit_method_copy() |
| classkit_method_remove() |
| classkit_method_rename() |
Note: This function cannot be used to manipulate the currently running (or chained) method.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
classnameThe class in which to remove the method
methodnameThe name of the method to remove
| classkit_method_add() |
| classkit_method_copy() |
| classkit_method_redefine() |
| classkit_method_rename() |
Note: This function cannot be used to manipulate the currently running (or chained) method.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
classnameThe class in which to rename the method
methodnameThe name of the method to rename
newnameThe new name to give to the renamed method
ClibPDF lets you create PDF documents with PHP. ClibPDF functionality and API are similar to PDFlib. This documentation should be read alongside the ClibPDF manual since it explains the library in much greater detail.
Many functions in the native ClibPDF and the PHP module, as well as in PDFlib, have the same name. All functions except for cpdf_open() take the handle for the document as their first parameter.
Currently this handle is not used internally since ClibPDF does not support the creation of several PDF documents at the same time. Actually, you should not even try it, the results are unpredictable. I can't oversee what the consequences in a multi threaded environment are. According to the author of ClibPDF this will change in one of the next releases (current version when this was written is 1.10). If you need this functionality use the pdflib module.
A nice feature of ClibPDF (and PDFlib) is the ability to create the pdf document completely in memory without using temporary files. It also provides the ability to pass coordinates in a predefined unit length. (This feature can also be simulated by pdf_translate() when using the PDFlib functions.)
Another nice feature of ClibPDF is the fact that any page can be modified at any time even if a new page has been already opened. The function cpdf_set_current_page() allows to leave the current page and presume modifying an other page.
Most of the functions are fairly easy to use. The most difficult part is probably creating a very simple PDF document at all. The following example should help you to get started. It creates a document with one page. The page contains the text "Times-Roman" in an outlined 30pt font. The text is underlined.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.
Note: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.
In order to use the ClibPDF functions you need to install the ClibPDF package. It is available for download from FastIO, but requires that you purchase a license for commercial use. PHP requires that you use cpdflib >= 2. The development of ClibPDF library has been discontinued thus FastIO website would be most probably inaccessible.
To get these functions to work, you have to compile PHP with
--with-cpdflib[=DIR]. DIR is the cpdflib
install directory, defaults to /usr. In addition you
can specify the jpeg library and the tiff library for ClibPDF to use. To do
so add to your configure line the options
--with-jpeg-dir[=DIR]
--with-tiff-dir[=DIR].
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Example 1. Simple ClibPDF Example
|
The pdflib distribution contains a more complex example which creates a series of pages with an analog clock. Here is that example converted into PHP using the ClibPDF extension:
Example 2. pdfclock example from pdflib 2.0 distribution
|
Adds a note at the specified point.
pdf_documentThe document handle, returned by cpdf_open().
llxLower left X
llyLower left Y
urxUpper right X
uryUpper right Y
titleThe title of the annotation
textThe contents of the annotation
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Adds a bookmark with text text that points to the
current page.
pdf_documentThe document handle, returned by cpdf_open().
lastoutline
sublevel
open
pagenr
textThe bookmark text
Draws an arc.
pdf_documentThe document handle, returned by cpdf_open().
xThe x-coordinate of the center
yThe y-coordinate of the center
radiusThe arc radius
startThe starting angle, in degrees
endThe ending angle, in degrees
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Starts a text section.
The created text section must be ended with cpdf_end_text().
Draws a circle.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate of the center
y_coorThe y-coordinate of the center
radiusThe circle radius
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Closes the PDF document.
This should be the last function called, even after cpdf_finalize(), cpdf_output_buffer() or cpdf_save_to_file().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_closepath_fill_stroke -- Close, fill and stroke current pathCloses, fills the interior of the current path with the current fill color and draws current path.
| cpdf_closepath() |
| cpdf_stroke() |
| cpdf_fill() |
| cpdf_setgray_fill() |
| cpdf_setgray() |
| cpdf_setrgbcolor_fill() |
| cpdf_setrgbcolor() |
Closes the current path and draws a line along it.
cpdf_closepath_stroke() is a combination of cpdf_closepath() and cpdf_stroke().
Outputs the string in text in the next line.
Draws a Bezier curve from the current point to the point
(x3, y3) using
(x1, y1) and
(x2, y2) as control points.
pdf_documentThe document handle, returned by cpdf_open().
x1x-coordinate for the first control point
y1y-coordinate for the first control point
x2x-coordinate for the second control point
y2y-coordinate for the second control point
x3x-coordinate for the target
y3y-coordinate for the target
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Ends a text section which was started with cpdf_begin_text().
Fills the interior of the current path with the current fill color and draws current path.
| cpdf_closepath() |
| cpdf_stroke() |
| cpdf_fill() |
| cpdf_setgray_fill() |
| cpdf_setgray() |
| cpdf_setrgbcolor_fill() |
| cpdf_setrgbcolor() |
Fills the interior of the current path with the current fill color.
| cpdf_closepath() |
| cpdf_stroke() |
| cpdf_setgray_fill() |
| cpdf_setgray() |
| cpdf_setrgbcolor_fill() |
| cpdf_setrgbcolor() |
Ends the page which number is page_number.
This function is only used for saving memory. A finalized page takes less memory but cannot be modified anymore.
Ends the PDF document.
You still have to call cpdf_close().
Sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.
maxPagesThe maximum number of pages
maxFontsThe maximum number of fonts
maxImagesThe maximum number of images
maxAnnotsThe maximum number of annotations
maxObjectsThe maximum number of objects
Opens a JPEG image.
pdf_documentThe document handle, returned by cpdf_open().
file_nameThe path to the image file. The format of the image has to be JPEG
x_coorThe x-coordinate of the image
y_coorThe y-coordinate of the image
angleThe image rotation angle, in degrees
widthThe image width
heightThe image height
x_scale
y_scale
gsaveShould be non-zero to allow this function to operate correctly
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
The cpdf_lineto() function draws a line from the current point to the specified point.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate of the destination point
y_coorThe y-coordinate of the destination point
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Sets the current point to the given coordinates.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate
y_coorThe y-coordinate
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Opens a new PDF document.
compressionIf different from 0, document compression is turned on
filenameSets the file in which the document is written. - is a synonym for stdout.
If omitted, the document is created in memory and can either be written into a file with cpdf_save_to_file() or written to standard output with cpdf_output_buffer().
Note: Using stdout will not work if PHP is compiled as an apache module. You can solve this problem by skipping this parameter filename and using cpdf_output_buffer() later to output the PDF document.
doc_limitsAn array defining the document limitation. See cpdf_global_set_document_limits() for more information
Returns a document handle, needed as the first parameter for all other functions of the library.
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_output_buffer -- Outputs the pdf document in memory bufferOutputs the pdf document to stdout.
The document has to be created in memory which is the case if cpdf_open() has been called without the file name parameter.
Starts a new page.
pdf_documentThe document handle, returned by cpdf_open().
page_numberThe page number
orientation0 for portrait and 1 for landscape
heightThe page height
widthThe page width
unitThe unit for the coordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.
Places an image created with the PHP image functions on the page. The image can be scaled at the same time.
Note: This function is only available if PHP was compiled with the GD Graphics Library 1.3. See the GD extension installation instructions for further information.
pdf_documentThe document handle, returned by cpdf_open().
imageAn image created with the PHP image functions
x_coorThe x-coordinate of the image
y_coorThe y-coordinate of the image
angleThe image rotation angle, in degrees
widthThe image width
heightThe image height
gsaveShould be non-zero to allow this function to operate correctly
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Draws a rectangle.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate of the lower left corner
y_coorThe y-coordinate of the lower left corner
widthThe rectangle width
heightThe rectangle height
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Example 1. Drawing a rectangle
|
Restores the environment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.
The cpdf_rlineto() function draws a line from the current point to the given relative point.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate of the destination point
y_coorThe y-coordinate of the destination point
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Set the current point relative to the given coordinates.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate of the destination point
y_coorThe y-coordinate of the destination point
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
| Warning |
This function is currently not documented; only the argument list is available. |
Sets the rotation in degrees to angle.
Outputs the PDF document into a file if it has been created in memory.
This function is not needed if the PDF document has been open by specifying a filename as a parameter of cpdf_open().
pdf_documentThe document handle, returned by cpdf_open().
filenameThe path to the saved PDF document
Saves the current environment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects.
Sets the scaling factor in both directions.
pdf_documentThe document handle, returned by cpdf_open().
x_scaleThe X scale percent to set. Default to 0.0
y_scaleThe Y scale percent to set. Default to 0.0
| Warning |
This function is currently not documented; only the argument list is available. |
Sets the spacing between characters.
pdf_documentThe document handle, returned by cpdf_open().
spaceDistance between individual characters in a string.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_creator -- Sets the creator field in the pdf documentSets the creator of a PDF document.
pdf_documentThe document handle, returned by cpdf_open().
creatorThe creator of the document
Sets the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_directories -- Sets directories to search when using external fonts
| Warning |
This function is currently not documented; only the argument list is available. |
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_map_file -- Sets fontname to filename translation map when using external fonts
| Warning |
This function is currently not documented; only the argument list is available. |
Sets the current font face, font size and encoding.
pdf_documentThe document handle, returned by cpdf_open().
font_nameThe font name. Currently only the standard postscript fonts are supported.
See the ClibPDF Manual for more information, especially on how to support Asian fonts.
sizeThe font size
encodingCan take the following values: MacRomanEncoding, MacExpertEncoding, WinAnsiEncoding, and NULL (the font's built-in encoding).
Sets the horizontal scaling to scale percent.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_keywords -- Sets the keywords field of the pdf documentSets the keywords of the PDF document.
pdf_documentThe document handle, returned by cpdf_open().
keywordsThe keywords to set on the document
Sets the distance between text lines. This will be
used if text is output by cpdf_continue_text().
pdf_documentThe document handle, returned by cpdf_open().
distanceThe distance between text lines, as a float
Sets the transition between following pages.
pdf_documentThe document handle, returned by cpdf_open().
transition
The value of transition
can be
| 0 for none, |
| 1 for two lines sweeping across the screen reveal the page, |
| 2 for multiple lines sweeping across the screen reveal the page, |
| 3 for a box reveals the page, |
| 4 for a single line sweeping across the screen reveals the page, |
| 5 for the old page dissolves to reveal the page, |
| 6 for the dissolve effect moves from one screen edge to another, |
| 7 for the old page is simply replaced by the new page (default) |
duration
The value of duration is the number of seconds
between page flipping.
direction
orientation
inout
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_subject -- Sets the subject field of the pdf document
Sets the subject of the PDF document.
pdf_documentThe document handle, returned by cpdf_open().
subjectThe subject of the document
Sets a matrix which describes a transformation
applied on the current text font.
pdf_documentThe document handle, returned by cpdf_open().
matrixAn array of six elements describing the transformation
Sets the position of text for the next cpdf_show() call.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate of the text position
y_coorThe y-coordinate of the text position
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Determines how the text is rendered.
pdf_documentThe document handle, returned by cpdf_open().
rendermode
The possible values for rendermode are 0=fill
text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill
text and add it to clipping path, 5=stroke text and add it to
clipping path, 6=fill and stroke text and add it to clipping
path, 7=add it to clipping path.
Sets the text rising to value units.
pdf_documentThe document handle, returned by cpdf_open().
valueThe text rising, as a float
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_viewer_preferences -- How to show the document in the viewer
| Warning |
This function is currently not documented; only the argument list is available. |
Sets the spacing between words.
Sets the dash pattern to the given one. If both parameters are 0, a solid line is set.
pdf_documentThe document handle, returned by cpdf_open().
whiteWhite units, as a float
blackBlack units, as a float
pdf_documentThe document handle, returned by cpdf_open().
valueThe flatness as a float, between 0 and 100
Sets the current gray value to fill a path.
pdf_documentThe document handle, returned by cpdf_open().
valueThe gray value, as a float
Sets the current drawing color to the given gray value.
pdf_documentThe document handle, returned by cpdf_open().
gray_valueThe gray value, as a float
Sets the current drawing and filling color to the given gray value.
pdf_documentThe document handle, returned by cpdf_open().
gray_valueThe gray value, as a float
pdf_documentThe document handle, returned by cpdf_open().
value0 = butt end, 1 = round, 2 = projecting square
pdf_documentThe document handle, returned by cpdf_open().
value0 = miter, 1 = round, 2 = bevel
pdf_documentThe document handle, returned by cpdf_open().
widthThe line width, as a float
pdf_documentThe document handle, returned by cpdf_open().
valueThe miter limit. Must be greater or equal than 1
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_fill -- Sets filling color to rgb color valueSets the current rgb color value to fill a path.
pdf_documentThe document handle, returned by cpdf_open().
red_valueThe red value, as a float between 0.0 (black) and 1.0 (red)
green_valueThe green value, as a float between 0.0 (black) and 1.0 (green)
blue_valueThe blue value, as a float between 0.0 (black) and 1.0 (blue)
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color valueSets the current drawing color to the given rgb color value.
pdf_documentThe document handle, returned by cpdf_open().
red_valueThe red value, as a float between 0.0 (black) and 1.0 (red)
green_valueThe green value, as a float between 0.0 (black) and 1.0 (green)
blue_valueThe blue value, as a float between 0.0 (black) and 1.0 (blue)
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor -- Sets drawing and filling color to rgb color valueSets the current drawing and filling color to the given rgb color value.
pdf_documentThe document handle, returned by cpdf_open().
red_valueThe red value, as a float between 0.0 (black) and 1.0 (red)
green_valueThe green value, as a float between 0.0 (black) and 1.0 (green)
blue_valueThe blue value, as a float between 0.0 (black) and 1.0 (blue)
Outputs the string text at the given position.
Note: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.
pdf_documentThe document handle, returned by cpdf_open().
textThe text
x_coorThe x-coordinate of the text position
y_coorThe y-coordinate of the text position
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
Returns the width of the string in text.
This function requires a font to be set before.
Outputs the string text at the given position.
pdf_documentThe document handle, returned by cpdf_open().
textThe text
x_coorThe x-coordinate of the text position
y_coorThe y-coordinate of the text position
modeThe optional parameter mode
determines the unit length. If it is 0 or omitted the default unit as specified
for the page is used. Otherwise the coordinates are measured in postscript
points disregarding the current unit.
orientationRotation of the text in degrees
alignmodeDetermines how the text is aligned. See the ClibPDF documentation for possible values.
Sets the origin of coordinate system to the specified point.
pdf_documentThe document handle, returned by cpdf_open().
x_coorThe x-coordinate of the point
y_coorThe y-coordinate of the point
COM is an acronym for Component Object Model; it is an object orientated layer (and associated services) on top of DCE RPC (an open standard) and defines a common calling convention that enables code written in any language to call and interoperate with code written in any other language (provided those languages are COM aware). Not only can the code be written in any language, but it need not even be part of the same executable; the code can be loaded from a DLL, be found in another process running on the same machine, or, with DCOM (Distributed COM), be found in another process on a remote machine, all without your code even needing to know where a component resides.
There is a subset of COM known as OLE Automation which comprises a set of COM interfaces that allow loose binding to COM objects, so that they can be introspected and called at run-time without compile-time knowledge of how the object works. The PHP COM extension utilizes the OLE Automation interfaces to allow you to create and call compatible objects from your scripts. Technically speaking, this should really be called the "OLE Automation Extension for PHP", since not all COM objects are OLE compatible.
Now, why would or should you use COM? COM is one of the main ways to glue applications and components together on the Windows platform; using COM you can launch Microsoft Word, fill in a document template and save the result as a Word document and send it to a visitor of your web site. You can also use COM to perform administrative tasks for your network and to configure your IIS; these are just the most common uses; you can do much more with COM.
Starting with PHP 5, this extension (and this documentation) was rewritten from scratch and much of the old confusing and bogus cruft has be removed. Additionally, we support the instantiation and creation of .Net assemblies using the COM interoperability layer provided by Microsoft.
Please read this article for an overview of the changes in this extension in PHP 5.
COM functions are only available for the Windows version of PHP.
.Net support requires PHP 5 and the .Net runtime.
There is no installation needed to use these functions; they are part of the PHP core.
The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.
You are responsible for installing support for the various COM objects that you intend to use (such as MS Word); we don't and can't bundle all of those with PHP.
Starting with PHP 5, you may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In laymans terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.
Many COM objects expose their properties as arrays, or using array-style access. In PHP 4, you may use PHP array syntax to read/write such a property, but only a single dimension is allowed. If you want to read a multi-dimensional property, you could instead make the property access into a function call, with each parameter representing each dimension of the array access, but there is no way to write to such a property.
PHP 5 introduces the following new features to make your life easier:
Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.
Iterate SafeArrays ("true" arrays) using the the Section called foreach in Chapter 16 control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at the Section called For Each for more information on this topic.
This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.
The behaviour of these functions is affected by settings in php.ini.
Table 1. Com configuration options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| com.allow_dcom | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.5. |
| com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0. |
| com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0. |
| com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0. |
| com.code_page | "" | PHP_INI_ALL | Available since PHP 5.0.0. |
| com.typelib_file | "" | PHP_INI_SYSTEM | Available since PHP 4.0.5. |
Here's a short explanation of the configuration directives.
com.allow_dcomWhen this is turned on, PHP will be allowed to operate as a D-COM (Distributed COM) client and will allow the PHP script to instantiate COM objects on a remote server.
com.autoregister_typelib
When this is turned on, PHP will attempt to register constants from
the typelibrary of objects that it instantiates, if those objects
implement the interfaces required to obtain that information.
The case sensitivity of the constants it registers is controlled by the
com.autoregister_casesensitive
configuration directive.
com.autoregister_verboseWhen this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.
com.autoregister_casesensitiveWhen this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.
com.code_pageIt controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.
If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.
Note: This configuration directive was introduced with PHP 5.
com.typelib_fileWhen set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.
This extension defines a reference to a COM component returned by deprecated com_load() (this function does not exist in PHP 5; use the COM class instead).
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
For further information on COM read the COM specification or perhaps take a look at Don Box's Yet Another COM Library (YACL). You might find some additional useful information in our FAQ for Chapter 57. If you're thinking of using MS Office applications on the server side, you should read the information here: Considerations for Server-Side Automation of Office.
The COM class allows you to instantiate an OLE compatible COM object and call its methods and access its properties.
COM class constructor. The parameters have the following meanings:
Can be a ProgID, Class ID or Moniker that names the component to load.
A ProgID is typically the application or DLL name, followed by a period, followed by the object name. e.g: Word.Application.
A Class ID is the UUID that uniquely identifies a given class.
A Moniker is a special form of naming, similar in concept to a URL scheme, that identifies a resource and specifies how it should be loaded. As an example, you could load up Word and get an object representing a word document by specifying the full path to the word document as the module name, or you can use LDAP: as a moniker to use the ADSI interface to LDAP.
The name of the DCOM server on which the component should be loaded and run. If NULL, the object is run using the default for the application. The default is typically to run it on the local machine, although the administrator might have configured the application to launch on a different machine.
If you specify a non-NULL value for server, PHP will refuse to load
the object unless the
com.allow_dcom
configuration option
is set to TRUE.
If server_name is an array, it should contain the
following elements (case sensitive!). Note that they are all optional
(although you need to specify both Username and Password together); if
you omit the Server setting, the default server will be used (as
mentioned above), and the instantiation of the object will not be
affected by the
com.allow_dcom
directive.
Table 1. DCOM server name
server_name key | type | description |
|---|---|---|
| Server | string | The name of the server. |
| Username | string | The username to connect as. |
| Password | string | The password for Username. |
| Flags | integer | One or more of the following constants, logically OR'd together:
CLSCTX_INPROC_SERVER,
CLSCTX_INPROC_HANDLER,
CLSCTX_LOCAL_SERVER,
CLSCTX_REMOTE_SERVER,
CLSCTX_SERVER and
CLSCTX_ALL. The default value if not
specified here is CLSCTX_SERVER if you also
omit Server, or
CLSCTX_REMOTE_SERVER if you do specify a
server. You should consult the Microsoft documentation for
CoCreateInstance for more information on the meaning of these
constants; you will typically never have to use them.
|
Specifies the codepage that is used to convert strings to unicode-strings and vice versa. The conversion is applied whenever a PHP string is passed as a parameter or returned from a method of this COM object. The code page is sticky in PHP 5, which means that it will propagate to objects and variants returned from the object.
Possible values are CP_ACP (use system default ANSI code page - the default if this parameter is omitted), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (use codepage/locale set for the current executing thread), CP_UTF7 and CP_UTF8. You may also use the number for a given codepage; consult the Microsoft documentation for more details on codepages and their numeric values.
The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM.
Starting with PHP 5, PHP will automatically detect methods that accept parameters by reference, and will automatically convert regular PHP variables to a form that can be passed by reference. This means that you can call the method very naturally; you needn't go to any extra effort in your code.
In PHP 4, to pass parameters by reference you need to create an instance of the VARIANT class to wrap the byref parameters.
In PHP versions prior to 5, a number of not very pleasant hacks meant that the following method names were not passed through to COM and were handled directly by PHP. PHP 5 eliminates these things; read the details below to determine how to fix your scripts. These magic method names are case insensitive.
void COM::AddRef ( void )Artificially adds a reference count to the COM object.
| Warning |
You should never need to use this method. It exists as a logical complement to the Release() method below. |
Artificially removes a reference count from the COM object.
| Warning |
You should never need to use this method. Its existence in PHP is a bug designed to work around a bug that keeps COM objects running longer than they should. |
These pseudo methods are only available if com_isenum() returns TRUE, in which case, they hide any methods with the same names that might otherwise be provided by the COM object. These methods have all been eliminated in PHP 5, and you should use the Section called For Each in Reference XV, COM and .Net (Windows) instead.
variant COM::All ( void )Returns a variant representing a SafeArray that has 10 elements; each element will be an empty/null variant. This function was supposed to return an array containing all the elements from the iterator, but was never completed. Do not use.
variant COM::Next ( void )Returns a variant representing the next element available from the iterator, or FALSE when there are no more elements.
variant COM::Prev ( void )Returns a variant representing the previous element available from the iterator, or FALSE when there are no more elements.
void COM::Reset ( void )Rewinds the iterator back to the start.
Example 1. COM example (1)
|
Example 2. COM example (2)
|
The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.
DOTNET class constructor. assembly_name specifies
which assembly should be loaded, and class_name
specifices which class in that assembly to instantiate. You may
optionally specify a codepage to use for unicode
string transformations; see the COM class
for more details on code pages.
The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.
Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.
Note: You need to install the .Net runtime on your web server to take advantage of this feature.
The VARIANT is COM's equivalent of the PHP zval; it is a structure that can contain a value with a range of different possible types. The VARIANT class provided by the COM extension allows you to have more control over the way that PHP passes values to and from COM.
VARIANT class constructor. Parameters:
initial value. if omitted, or set to NULL an VT_EMPTY object is created.
specifies the content type of the VARIANT object. Possible values are one of the VT_XXX the Section called Predefined Constants in Reference XV, COM and .Net (Windows).
In PHP versions prior to PHP 5, you could force PHP to pass a variant
object by reference by OR'ing VT_BYREF
with the type. In PHP 5, this hack is not
supported; instead, PHP 5 can detect parameters passed by reference
automatically; they do not even need to be passed as VARIANT objects.
Consult the MSDN library for additional information on the VARIANT type.
specifies the codepage that is used to convert strings to unicode. See the parameter of the same name in the COM class for more information.
PHP versions prior to PHP 5 define a number of (undocumented) virtual properties for instances of the VARIANT class; these properties have all been removed in PHP 5 in favour of its more natural syntax; these differences are best highlighted by example:
The reason for the change is that, internally, the COM extension sees VARIANT, COM and DOTNET classes as the same thing, and the design philosophy for these classes is that all property and member accesses are passed through to COM with no interference. The new syntax is more natural and less effort, and most of the removed virtual properties didn't make any sense in a PHP context in any case.
Note: PHP 5 takes a much simpler approach to handling VARIANTs; when returning a value or fetching a variant property, the variant is converted to a PHP value only when there is a direct mapping between the types that would not result in a loss of information. In all other cases, the result is returned as an instance of the VARIANT class. You can force PHP to convert or evaluate the variant as a PHP native type by using a casting operator explicitly, or implicitly casting to a string by print()ing it. You may use the wide range of variant functions to perform arithmetic operations on variants without forcing a conversion or risking a loss of data.
See also variant_get_type().
Increases the components reference counter.
| Warning |
You should never need to use this function. |
Generates a Globally Unique Identifier (GUID) and returns it as a string. A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.
See also uuid_create() in the PECL uuid extension.
Instructs COM to sink events generated by
comobject into the PHP object
sinkobject. PHP will attempt to use the default
dispinterface type specified by the typelibrary associated with
comobject, but you may override this choice by
setting sinkinterface to the name of the
dispinterface that you want to use.
sinkobject should be an instance of a class with
methods named after those of the desired dispinterface; you may use
com_print_typeinfo() to help generate a template class
for this purpose.
Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.
Example 1. COM event sink example
|
See also com_print_typeinfo(), com_message_pump().
com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the Running Object Table to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.
progid must be either the ProgID or CLSID for the
object that you want to access (for example
Word.Application). code_page
acts in precisely the same way that it does for the COM class.
If the requested object is running, it will be returned to your script just like any other COM object. Otherwise a com_exception will be raised. There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.
| Warning |
Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read Considerations for Server-Side Automation of Office for more information on the general issues involved. |
Returns the value of the property of the
COM component referenced by com_object.
Returns FALSE on error.
Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.
com_invoke() invokes the method
named function_name of the COM
component referenced by com_object.
com_invoke() returns FALSE on error,
returns the function_name's return
value on success. All the extra parameters
function_parameters are passed to
the method function_name.
Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.
(PHP 4 >= 4.1.0)
com_isenum -- Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]Checks to see if a COM object can be enumerated using the Next() method hack. Returns TRUE if it can, FALSE if it cannot. See COM class for more details on these methods.
Note: This function does not exist in PHP 5; use the more natural foreach statement to iterate over the contents of COM objects. See the Section called For Each in Reference XV, COM and .Net (Windows) for more details.
Loads a type-library and registers its constants in the engine, as though
they were defined using define(). The
case_insensitive behaves in the same way as the
parameter with the same name in the define() function.
typelib_name can be one of the following:
The filename of a .tlb file or the executable module that contains the type library.
The type library GUID, followed by its version number, for example {00000200-0000-0010-8000-00AA006D2EA4},2,0.
The type library name, e.g. Microsoft OLE DB ActiveX Data Objects 1.0 Library.
Note that it is much more efficient to use the
com.typelib_file
configuration setting to pre-load and register the constants,
although not so flexible.
If you have turned on
com.autoregister_typelib
,
then PHP will attempt to automatically register the constants associated
with a COM object when you instantiate it. This depends on the
interfaces provided by the COM object itself, and may not always be
possible.
Equivalent to using the new operator to create an instance of the COM class. You should do that instead of calling this function.
Note: This function does not exist in PHP 5; use the COM class instead.
(PHP 4 >= 4.2.3, PHP 5)
com_message_pump -- Process COM messages, sleeping for up to timeoutms milliseconds
This function will sleep for up to timeoutms
milliseconds, or until a message arrives in the queue. If a message or
messages arrives before the timeout, they will be dispatched, and the
function will return TRUE. If the timeout occurs and no messages were
processed, the return value will be FALSE. If you do not specify a
value for timeoutms, then 0 will be assumed. A 0
value means that no waiting will be performed; if there are messages
pending they will be dispatched as before; if there are no messages
pending, the function will return FALSE immediately without sleeping.
The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.
(PHP 4 >= 4.2.3, PHP 5)
com_print_typeinfo -- Print out a PHP class definition for a dispatchable interfaceThe purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.
comobject should be either an instance of a COM
object, or be the name of a typelibrary (which will be resolved according
to the rules set out in com_load_typelib()).
dispinterface is the name of an IDispatch
descendant interface that you want to display. If
wantsink is TRUE, the corresponding sink
interface will be displayed instead.
See also com_event_sink(), com_load_typelib().
This function is an alias of: com_get().
Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.
This function is an alias of: com_set().
Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.
This function is an alias of: com_set().
Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.
Decreases the components reference counter.
| Warning |
You should never need to use this function. |
Note: This function has gone away in PHP 5.
Sets the value of the property of the COM
component referenced by com_object.
Returns the newly set value if succeeded, FALSE on error.
Note: This function does not exist in PHP 5; instead, you should use the regular and more natural OO syntax to access properties or call methods.
Returns the absolute value of val.
See also abs().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Adds left to right using
the following rules (taken from the MSDN library), which correspond to
those of Visual Basic:
Table 1. Variant Addition Rules
| If | Then |
|---|---|
| Both expressions are of the string type | Concatenation |
| One expression is a string type and the other a character | Addition |
| One expression is numeric and the other is a string | Addition |
| Both expressions are numeric | Addition |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | Integer subtype is returned |
See also variant_sub().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise AND operation, according to the following truth table; note that this is slightly different from a regular AND operation.
Table 1. Variant AND Rules
If left is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | TRUE |
| TRUE | FALSE | FALSE |
| TRUE | NULL | NULL |
| FALSE | TRUE | FALSE |
| FALSE | FALSE | FALSE |
| FALSE | NULL | FALSE |
| NULL | TRUE | NULL |
| NULL | FALSE | FALSE |
| NULL | NULL | NULL |
See also variant_or().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function makes a copy of variant and then
performs a variant cast operation to force the copy to have the type
given by type. type should
be one of the VT_XXX constants.
This function wraps VariantChangeType() in the COM library; consult MSDN for more information.
See also variant_set_type().
Concatenates left with
right and returns the result.
See also the Section called String Operators in Chapter 15 for the string
concatenation operator; this function is notionally equivalent to
$left . $right.
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Compares left with right
and returns one of the following values:
Table 1. Variant Comparision Results
| value | meaning |
|---|---|
| VARCMP_LT | left is less than
right
|
| VARCMP_EQ | left is equal to
right
|
| VARCMP_GT | left is greater than
right
|
| VARCMP_NULL | Either left,
right or both are NULL
|
This function will only compare scalar values, not arrays or variant records.
lcid is a valid Locale Identifier to use when
comparing strings (this affects string collation).
flags can be one or more of the following values
OR'd together, and affects string comparisons:
Table 2. Variant Comparision Flags
| value | meaning |
|---|---|
| NORM_IGNORECASE | Compare case insensitively |
| NORM_IGNORENONSPACE | Ignore nonspacing characters |
| NORM_IGNORESYMBOLS | Ignore symbols |
| NORM_IGNOREWIDTH | Ignore string width |
| NORM_IGNOREKANATYPE | Ignore Kana type |
| NORM_IGNOREKASHIDA | Ignore Arabic kashida characters |
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Converts timestamp from a unix timestamp value
into a variant of type VT_DATE. This allows easier
interopability between the unix-ish parts of PHP and COM.
See also variant_date_to_timestamp() for the inverse of this operation, mktime(), time().
Converts variant from a VT_DATE
(or similar) value into a Unix timestamp. This allows easier
interopability between the Unix-ish parts of PHP and COM.
See also variant_date_from_timestamp() for the inverse of this operation, date(), strftime().
Divides left by right and
returns the result, subject to the following rules:
Table 1. Variant Division Rules
| If | Then |
|---|---|
| Both expressions are of the string, date, character, boolean type | Double is returned |
| One expression is a string type and the other a character | Division and a double is returned |
| One expression is numeric and the other is a string | Division and a double is returned. |
| Both expressions are numeric | Division and a double is returned |
| Either expression is NULL | NULL is returned |
right is empty and
left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
left is empty and
right is anything but empty. | 0 as type double is returned |
| Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown |
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If each bit in left is equal to the corresponding
bit in right then TRUE is returned, otherwise
FALSE is returned.
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative
integer greater than or equal to the variant is returned, otherwise
returns the integer portion of the value of
variant.
See also variant_int(), variant_round(), floor(), ceil(), round().
| Warning |
This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation. |
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function returns an integer value that indicates the type of
variant, which can be an instance of
COM,
DOTNET or
VARIANT classes. The return value
can be compared to one of the VT_XXX constants.
The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.
In PHP versions prior to 5, you could obtain this information from
instances of the VARIANT class ONLY, by reading a fake
type property. See the VARIANT class for more information on
this.
Converts left and right to
integer values, and then performs integer division according the
following rules:
Table 1. Variant Integer Division Rules
| If | Then |
|---|---|
| Both expressions are of the string, date, character, boolean type | Division and integer is returned |
| One expression is a string type and the other a character | Division |
| One expression is numeric and the other is a string | Division |
| Both expressions are numeric | Division |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
See also variant_div().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise implication operation, according to the following truth table:
Table 1. Variant Implication Table
If left is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | TRUE |
| TRUE | FALSE | TRUE |
| TRUE | NULL | TRUE |
| FALSE | TRUE | TRUE |
| FALSE | FALSE | TRUE |
| FALSE | NULL | TRUE |
| NULL | TRUE | TRUE |
| NULL | FALSE | NULL |
| NULL | NULL | NULL |
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative
integer greater than or equal to the variant is returned, otherwise
returns the integer portion of the value of
variant.
See also variant_fix(), variant_round(), floor(), ceil(), round().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Divides left by right and
returns the remainder.
See also variant_div(), variant_idiv().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Multiplies left by right and
returns the result, subject to the following rules:
Table 1. Variant Multiplication Rules
| If | Then |
|---|---|
| Both expressions are of the string, date, character, boolean type | Multiplication |
| One expression is a string type and the other a character | Multiplication |
| One expression is numeric and the other is a string | Multiplication |
| Both expressions are numeric | Multiplication |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | Empty string is returned |
Boolean values are converted to -1 for FALSE and 0 for TRUE.
See also variant_div(), variant_idiv().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs logical negation of variant and returns
the result.
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs bitwise not negation on variant and
returns the result. If variant is NULL, the
result will also be NULL.
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise OR operation, according to the following truth table; note that this is slightly different from a regular OR operation.
Table 1. Variant OR Rules
If left is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | TRUE |
| TRUE | FALSE | TRUE |
| TRUE | NULL | TRUE |
| FALSE | TRUE | TRUE |
| FALSE | FALSE | FALSE |
| FALSE | NULL | NULL |
| NULL | TRUE | TRUE |
| NULL | FALSE | NULL |
| NULL | NULL | NULL |
See also variant_and(), variant_xor().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the result of left to the power of
right.
See also pow().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the value of variant rounded to
decimals decimal places.
See also round().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().
See also variant_cast().
Converts value to a variant and assigns it to the
variant object; no new variant object is created,
and the old value of variant is freed/released.
(PHP 5)
variant_sub -- subtracts the value of the right variant from the left variant value and returns the result
Subtracts right from left using
the following rules:
Table 1. Variant Subtraction Rules
| If | Then |
|---|---|
| Both expressions are of the string type | Subtraction |
| One expression is a string type and the other a character | Subtraction |
| One expression is numeric and the other is a string | Subtraction. |
| Both expressions are numeric | Subtraction |
| Either expression is NULL | NULL is returned |
| Both expressions are empty | Empty string is returned |
See also variant_add().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a logical exclusion, according to the following truth table:
Table 1. Variant XOR Rules
If left is | If right is | then the result is |
|---|---|---|
| TRUE | TRUE | FALSE |
| TRUE | FALSE | TRUE |
| FALSE | TRUE | TRUE |
| FALSE | FALSE | FALSE |
| NULL | NULL | NULL |
See also variant_and(), variant_or().
Note: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.
More information regarding CrackLib along with the library can be found at http://sourceforge.net/projects/cracklib.
This PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/crack.
In PHP 4 this PECL extensions
source can be found in the ext/ directory within the
PHP source or at the PECL link above.
In order to use these functions you must compile PHP with Crack support
by using the --with-crack[=DIR]
configuration option.
Windows users will enable php_crack.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/
The behaviour of these functions is affected by settings in php.ini.
Table 1. Crack configuration options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| crack.default_dictionary | NULL | PHP_INI_PERDIR | Available since PHP 4.0.5. |
The CrackLib extension defines a dictionary resource identifier returned by crack_opendict().
This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.
Example 1. CrackLib example
|
Note: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.
Performs an obscure check with the given password on the specified dictionary.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dictionaryThe crack lib dictionary. If not specified, the last opened dictionary is used.
passwordThe tested password.
crack_closedict() closes the specified
dictionary identifier.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
crack_getlastmessage() returns the message from the last obscure check.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
The message from the last obscure check or FALSE if there was no obscure checks made so far.
The returned message is one of:
it's WAY too short
it is too short
it does not contain enough DIFFERENT characters
it is all whitespace
it is too simplistic/systematic
it looks like a National Insurance number.
it is based on a dictionary word
it is based on a (reversed) dictionary word
strong password
crack_opendict() opens the specified CrackLib
dictionary for use with
crack_check().
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Note: Only one dictionary may be open at a time.
The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).
When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.
When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.
Passing anything else but a string or integer will return FALSE immediately.
It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.
Beginning with PHP 4.2.0 these functions are enabled by default.
For older versions you have to configure and compile PHP with
--enable-ctype. You can disable
ctype support with --disable-ctype.
The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.
Note: Builtin support for ctype is available with PHP 4.3.0.
Checks if all of the characters in the provided string,
text, are alphanumeric. In the standard
C locale letters are just [A-Za-z]
and the function is equivalent to
preg_match('/^[a-z0-9]+$/iD', $text).
Returns TRUE if every character in text is either
a letter or a digit, FALSE otherwise.
Example 1. A ctype_alnum() example (using the default locale)
The above example will output:
|
Checks if all of the characters in the provided string,
text, are alphabetic.
In the standard C locale letters are just
[A-Za-z] and ctype_alpha() is
equivalent to (ctype_upper($text) || ctype_lower($text))
if $text is just a single character, but other languages have letters that
are considered neither upper nor lower case.
Returns TRUE if every character in text is
a letter from the current locale, FALSE otherwise.
Example 1. A ctype_alpha() example (using the default locale)
The above example will output:
|
Checks if all of the characters in the provided string,
text, are control characters.
Control characters are e.g. line feed, tab, escape.
Returns TRUE if every character in text is
a control character from the current locale, FALSE otherwise.
Example 1. A ctype_cntrl() example
The above example will output:
|
Checks if all of the characters in the provided string,
text, are numerical.
Example 1. A ctype_digit() example
The above example will output:
|
Checks if all of the characters in the provided string,
text, creates visible output.
Returns TRUE if every character in text is
printable and actually creates visible output (no white space), FALSE
otherwise.
Example 1. A ctype_graph() example
The above example will output:
|
Checks if all of the characters in the provided string,
text, are lowercase letters.
Example 1. A ctype_lower() example (using the default locale)
The above example will output:
|
Checks if all of the characters in the provided string,
text, are printable.
Returns TRUE if every character in text
will actually create output (including blanks). Returns FALSE if
text contains control characters or characters
that do not have any output or control function at all.
Example 1. A ctype_print() example
The above example will output:
|
(PHP 4 >= 4.0.4, PHP 5)
ctype_punct -- Check for any printable character which is not whitespace or an alphanumeric character
Checks if all of the characters in the provided string,
text, are punctuation character.
Returns TRUE if every character in text
is printable, but neither letter, digit or blank, FALSE otherwise.
Example 1. A ctype_punct() example
The above example will output:
|
Checks if all of the characters in the provided string,
text, creates whitespace.
Returns TRUE if every character in text
creates some sort of white space, FALSE otherwise. Besides the
blank character this also includes tab, vertical tab, line feed,
carriage return and form feed characters.
Example 1. A ctype_space() example
The above example will output:
|
Checks if all of the characters in the provided string,
text, are uppercase characters.
Example 1. A ctype_upper() example (using the default locale)
The above example will output:
|
Checks if all of the characters in the provided string,
text, are hexadecimal 'digits'.
Returns TRUE if every character in text is
a hexadecimal 'digit', that is a decimal digit or a character from
[A-Fa-f] , FALSE otherwise.
Example 1. A ctype_xdigit() example
The above example will output:
|
PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
These functions have been added in PHP 4.0.2.
In order to use PHP's cURL functions you need to install the libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the
location of the directory containing the lib and include
directories. In the "include" directory there should be a folder
named "curl" which should contain the easy.h and
curl.h files. There should be a file named
libcurl.a located in the "lib" directory. Beginning
with PHP 4.3.0 you can configure PHP to use cURL for URL streams
--with-curlwrappers.
Note to Win32 Users: In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH.
You don't need libcurl.dll from the cURL site.
Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close(). Here is an example that uses the cURL functions to fetch the example.com homepage into a file:
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Available since PHP 5.2.0
Available since PHP 5.2.0
Available since PHP 5.2.0
Available since PHP 5.2.0
Available since PHP 5.2.0
Available since PHP 5.1.0
Available since PHP 6.0.0
Available since PHP 5.1.0
Available since PHP 5.1.0
Available since PHP 5.1.0
Closes a cURL session and frees all resources. The cURL handle,
ch, is also deleted.
Example 1. Initializing a new cURL session and fetching a web page
|
Copies a cURL handle keeping the same preferences.
Example 1. Copying a cURL handle
|
(PHP 4 >= 4.0.3, PHP 5)
curl_error -- Return a string containing the last error for the current sessionReturns a clear text error message for the last cURL operation.
Execute the given cURL session.
This function should be called after you initialize a cURL session and all the options for the session are set.
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
Example 1. Fetching a web page
|
chA cURL handle returned by curl_init().
optThis may be one of the following constants:
CURLINFO_EFFECTIVE_URL - Last effective URL
CURLINFO_HTTP_CODE - Last received HTTP code
CURLINFO_FILETIME - Remote time of the retrieved document, if -1 is returned the time of the document is unknown
CURLINFO_TOTAL_TIME - Total transaction time in seconds for last transfer
CURLINFO_NAMELOOKUP_TIME - Time in seconds until name resolving was complete
CURLINFO_CONNECT_TIME - Time in seconds it took to establish the connection
CURLINFO_PRETRANSFER_TIME - Time in seconds from start until just before file transfer begins
CURLINFO_STARTTRANSFER_TIME - Time in seconds until the first byte is about to be transferred
CURLINFO_REDIRECT_TIME - Time in seconds of all redirection steps before final transaction was started
CURLINFO_SIZE_UPLOAD - Total number of bytes uploaded
CURLINFO_SIZE_DOWNLOAD - Total number of bytes downloaded
CURLINFO_SPEED_DOWNLOAD - Average download speed
CURLINFO_SPEED_UPLOAD - Average upload speed
CURLINFO_HEADER_SIZE - Total size of all headers received
CURLINFO_HEADER_OUT - The request string sent. Available since PHP 6.0.0
CURLINFO_REQUEST_SIZE - Total size of issued requests, currently only for HTTP requests
CURLINFO_SSL_VERIFYRESULT - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER
CURLINFO_CONTENT_LENGTH_DOWNLOAD - content-length of download, read from Content-Length: field
CURLINFO_CONTENT_LENGTH_UPLOAD - Specified size of upload
CURLINFO_CONTENT_TYPE - Content-type of downloaded object, NULL indicates server did not send valid Content-Type: header
If opt is given, returns its value as a string.
Otherwise, returns an associative array with the following elements
(which correspond to opt):
"url"
"content_type"
"http_code"
"header_size"
"request_size"
"filetime"
"ssl_verify_result"
"redirect_count"
"total_time"
"namelookup_time"
"connect_time"
"pretransfer_time"
"size_upload"
"size_download"
"speed_download"
"speed_upload"
"download_content_length"
"upload_content_length"
"starttransfer_time"
"redirect_time"
Initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.
urlIf provided, the CURLOPT_URL option will be set to its value. You can manually set this using the curl_setopt() function.
Example 1. Initializing a new cURL session and fetching a web page
|
Adds the ch handle to the multi handle
mh
mhA cURL multi handle returned by curl_multi_init().
chA cURL handle returned by curl_init().
| Warning |
This function is currently not documented; only the argument list is available. |
(PHP 5)
curl_multi_getcontent -- Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
mhA cURL multi handle returned by curl_multi_init().
chA cURL handle returned by curl_init().
(PHP 5)
curl_multi_select -- Get all the sockets associated with the cURL extension, which can then be "selected"| Warning |
This function is currently not documented; only the argument list is available. |
Sets multiple options for a cURL session. This function is useful for setting a large amount of cURL options without repetitively calling curl_setopt().
chA cURL handle returned by curl_init().
optionsAn array specifying which options to set and their values. The keys should be valid curl_setopt() constants or their integer equivalents.
Returns TRUE if all options were successfully set. If an option could
not be successfully set, FALSE is immediately returned, ignoring any
future options in the options array.
Example 1. Initializing a new cURL session and fetching a web page
|
Prior to PHP 5.1.4 you can simulate this function with:
Sets an option on the given cURL session handle.
chA cURL handle returned by curl_init().
optionThe CURLOPT_XXX option that you want to set
value
The value to be set on option.
value should be a bool for the
following values of the option parameter:
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_AUTOREFERER | TRUE to automatically set the Referer: field in requests where it follows a Location: redirect. | Available since PHP 5.1.0. |
| CURLOPT_BINARYTRANSFER | TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used. | |
| CURLOPT_COOKIESESSION | TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies are not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. | Available since PHP 5.1.0. |
| CURLOPT_CRLF | TRUE to convert Unix newlines to CRLF newlines on transfers. | |
| CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default. | |
| CURLOPT_FAILONERROR | TRUE to fail silently if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code. | |
| CURLOPT_FILETIME |
TRUE to attempt to retrieve the modification
date of the remote document. You can then retrieve this value using
the CURLINFO_FILETIME option with
curl_getinfo().
| |
| CURLOPT_FOLLOWLOCATION | TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set). | |
| CURLOPT_FORBID_REUSE | TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse. | |
| CURLOPT_FRESH_CONNECT | TRUE to force the use of a new connection instead of a cached one. | |
| CURLOPT_FTP_USE_EPRT | TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only. | Added in PHP 5.0.0. |
| CURLOPT_FTP_USE_EPSV | TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV. | |
| CURLOPT_FTPAPPEND | TRUE to append to the remote file instead of overwriting it. | |
| CURLOPT_FTPASCII | An alias of CURLOPT_TRANSFERTEXT. Use that instead. | |
| CURLOPT_FTPLISTONLY | TRUE to only list the names of an FTP directory. | |
| CURLOPT_HEADER | TRUE to include the header in the output. | |
| CURLOPT_HTTPGET | TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed. | |
| CURLOPT_HTTPPROXYTUNNEL | TRUE to tunnel through a given HTTP proxy. | |
| CURLOPT_MUTE | TRUE to be completely silent with regards to the cURL functions. | |
| CURLOPT_NETRC | TRUE to scan your ~/.netrc file to find your username and password for the remote site that you're establishing a connection with. | |
| CURLOPT_NOBODY | TRUE to exclude the body from the output. | |
| CURLOPT_NOPROGRESS |
TRUE to disable the progress meter for cURL transfers.
| |
| CURLOPT_NOSIGNAL | TRUE to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used. | Added in cURL 7.10 and PHP 5.0.0. |
| CURLOPT_POST | TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms. | |
| CURLOPT_PUT | TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE. | |
| CURLOPT_RETURNTRANSFER | TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. | |
| CURLOPT_SSL_VERIFYPEER | FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2). | TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10. |
| CURLOPT_TRANSFERTEXT | TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode. | |
| CURLOPT_UNRESTRICTED_AUTH | TRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed. | Added in PHP 5.0.0. |
| CURLOPT_UPLOAD | TRUE to prepare for an upload. | |
| CURLOPT_VERBOSE | TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR. |
value should be an integer for the
following values of the option parameter:
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_BUFFERSIZE | The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. | Added in cURL 7.10 and PHP 5.0.0. |
| CURLOPT_CLOSEPOLICY |
Either
CURLCLOSEPOLICY_LEAST_RECENTLY_USED or
CURLCLOSEPOLICY_OLDEST.
There are three other CURLCLOSEPOLICY_
constants, but cURL does not support them yet.
| |
| CURLOPT_CONNECTTIMEOUT | The number of seconds to wait whilst trying to connect. Use 0 to wait indefinitely. | |
| CURLOPT_DNS_CACHE_TIMEOUT | The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default. | |
| CURLOPT_FTPSSLAUTH | The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide). | Added in cURL 7.12.2 and PHP 5.1.0. |
| CURLOPT_HTTP_VERSION |
CURL_HTTP_VERSION_NONE (default, lets CURL
decide which version to use),
CURL_HTTP_VERSION_1_0 (forces HTTP/1.0),
or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).
| |
| CURLOPT_HTTPAUTH |
The HTTP authentication method(s) to use. The options are:
You can use the bitwise | (or) operator to combine more than one method. If you do this, cURL will poll the server to see what methods it supports and pick the best one.
| Added in PHP 5.0.0. |
| CURLOPT_INFILESIZE | The expected size, in bytes, of the file when uploading a file to a remote site. | |
| CURLOPT_LOW_SPEED_LIMIT | The transfer speed, in bytes per second, that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider the transfer too slow and abort. | |
| CURLOPT_LOW_SPEED_TIME | The number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort. | |
| CURLOPT_MAXCONNECTS | The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close. | |
| CURLOPT_MAXREDIRS | The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION. | |
| CURLOPT_PORT | An alternative port number to connect to. | |
| CURLOPT_PROXYAUTH |
The HTTP authentication method(s) to use for the proxy connection.
Use the same bitmasks as described in
CURLOPT_HTTPAUTH. For proxy authentication,
only CURLAUTH_BASIC and
CURLAUTH_NTLM are currently supported.
| Added in cURL 7.10.7 and PHP 5.1.0. |
| CURLOPT_PROXYPORT | The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY. | Added in PHP 5.0.0. |
| CURLOPT_PROXYTYPE |
Either CURLPROXY_HTTP (default) or
CURLPROXY_SOCKS5.
| Added in cURL 7.10 and PHP 5.0.0. |
| CURLOPT_RESUME_FROM | The offset, in bytes, to resume a transfer from. | |
| CURLOPT_SSL_VERIFYHOST | 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided. | |
| CURLOPT_SSLVERSION | The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases you must set this manually. | |
| CURLOPT_TIMECONDITION |
How CURLOPT_TIMEVALUE is treated.
Use CURL_TIMECOND_IFMODSINCE to return the
page only if it has been modified since the time specified in
CURLOPT_TIMEVALUE. If it hasn't been modified,
a "304 Not Modified" header will be returned
assuming CURLOPT_HEADER is TRUE.
Use CURL_TIMECOND_ISUNMODSINCE for the reverse
effect. CURL_TIMECOND_IFMODSINCE is the
default.
| Added in PHP 5.1.0. |
| CURLOPT_TIMEOUT | The maximum number of seconds to allow cURL functions to execute. | |
| CURLOPT_TIMEVALUE |
The time in seconds since January 1st, 1970. The time will be used
by CURLOPT_TIMECONDITION. By default,
CURL_TIMECOND_IFMODSINCE is used.
|
value should be a string for the
following values of the option parameter:
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_CAINFO | The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER. | |
| CURLOPT_CAPATH | A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER. | |
| CURLOPT_COOKIE | The contents of the "Set-Cookie: " header to be used in the HTTP request. | |
| CURLOPT_COOKIEFILE | The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. | |
| CURLOPT_COOKIEJAR | The name of a file to save all internal cookies to when the connection closes. | |
| CURLOPT_CUSTOMREQUEST |
A custom request method to use instead of
"GET" or "HEAD" when doing
a HTTP request. This is useful for doing
"DELETE" or other, more obscure HTTP requests.
Valid values are things like "GET",
"POST", "CONNECT" and so on;
i.e. Do not enter a whole HTTP request line here. For instance,
entering "GET /index.html HTTP/1.0\r\n\r\n"
would be incorrect.
| |
| CURLOPT_EGBSOCKET | Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket. | |
| CURLOPT_ENCODING | The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. | Added in cURL 7.10. |
| CURLOPT_FTPPORT | The value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address. | |
| CURLOPT_INTERFACE | The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name. | |
| CURLOPT_KRB4LEVEL | The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions. | |
| CURLOPT_POSTFIELDS | The full data to post in a HTTP "POST" operation. | |
| CURLOPT_PROXY | The HTTP proxy to tunnel requests through. | |
| CURLOPT_PROXYUSERPWD | A username and password formatted as "[username]:[password]" to use for the connection to the proxy. | |
| CURLOPT_RANDOM_FILE | A filename to be used to seed the random number generator for SSL. | |
| CURLOPT_RANGE | Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M". | |
| CURLOPT_REFERER | The contents of the "Referer: " header to be used in a HTTP request. | |
| CURLOPT_SSL_CIPHER_LIST | A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists. | |
| CURLOPT_SSLCERT | The name of a file containing a PEM formatted certificate. | |
| CURLOPT_SSLCERTPASSWD | The password required to use the CURLOPT_SSLCERT certificate. | |
| CURLOPT_SSLCERTTYPE | The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". | Added in cURL 7.9.3 and PHP 5.0.0. |
| CURLOPT_SSLENGINE | The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY. | |
| CURLOPT_SSLENGINE_DEFAULT | The identifier for the crypto engine used for asymmetric crypto operations. | |
| CURLOPT_SSLKEY | The name of a file containing a private SSL key. | |
| CURLOPT_SSLKEYPASSWD |
The secret password needed to use the private SSL key specified in
CURLOPT_SSLKEY.
| |
| CURLOPT_SSLKEYTYPE | The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG". | |
| CURLOPT_URL | The URL to fetch. You can also set this when initializing a session with curl_init(). | |
| CURLOPT_USERAGENT | The contents of the "User-Agent: " header to be used in a HTTP request. | |
| CURLOPT_USERPWD | A username and password formatted as "[username]:[password]" to use for the connection. |
value should be an array for the
following values of the option parameter:
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_HTTP200ALIASES | An array of HTTP 200 responses that will be treated as valid responses and not as errors. | Added in cURL 7.10.3 and PHP 5.0.0. |
| CURLOPT_HTTPHEADER | An array of HTTP header fields to set. | |
| CURLOPT_POSTQUOTE | An array of FTP commands to execute on the server after the FTP request has been performed. | |
| CURLOPT_QUOTE | An array of FTP commands to execute on the server prior to the FTP request. |
value should be a stream resource (using
fopen(), for example) for the following values of the
option parameter:
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_FILE | The file that the transfer should be written to. The default is STDOUT (the browser window). | |
| CURLOPT_INFILE | The file that the transfer should be read from when uploading. | |
| CURLOPT_STDERR | An alternative location to output errors to instead of STDERR. | |
| CURLOPT_WRITEHEADER | The file that the header part of the transfer is written to. |
value should be a string that is the name of a valid
callback function for the following values of the
option parameter:
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_HEADERFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. Using this callback function, it becomes your responsibility to write the header data. Return the number of bytes written. | |
| CURLOPT_PASSWDFUNCTION | The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password. | |
| CURLOPT_READFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be read. Using this callback function, it becomes your responsibility to read the data. Return the number of bytes read. Return 0 to signal EOF. | |
| CURLOPT_WRITEFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. Using this callback function, it becomes your responsibility to write the data. Must return the exact number of bytes written or this will fail. |
Example 1. Initializing a new cURL session and fetching a web page
|
Returns an associative array with the following elements:
| version_number | cURL 24 bit version number |
| version | cURL version number, as a string |
| ssl_version_number | OpenSSL 24 bit version number |
| ssl_version | OpenSSL version number, as a string |
| libz_version | zlib version number, as a string |
| host | Information about the host where cURL was built |
| age | |
| features | A bitmask of the CURL_VERSION_XXX constants |
| protocols | An array of protocols names supported by cURL |
These functions are only available if the interpreter has been
compiled with the --with-cybercash=[DIR].
This extension has been moved from PHP as of PHP 4.3.0 and now CyberCash lives in PECL.
If you have questions as to the latest status of CyberCash then the following CyberCash Faq will be helpful. In short, CyberCash was bought out by VeriSign and although the CyberCash service continues to exist, VeriSign encourages users to switch. See the above faq and PECL link for details.
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).
wmkThe merchant key.
skThe session key.
inbuffURL encoded string of value pairs, i.e. order-id=12345&amount=USD+12.34&card_number=......
This extension allows you to process credit cards transactions using Credit Mutuel CyberMUT system.
CyberMUT is a popular Web Payment Service in France, provided by the Credit Mutuel bank. If you are foreign in France, these functions will not be useful for you.
The use of these functions is almost identical to the original functions, except for the parameters of return for CreerFormulaireCM and CreerReponseCM, which are returned directly by functions PHP, whereas they had passed in reference in the original functions.
Note: This extension is not available on Windows platforms.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 4.3.0
You will require the appropriate SDK for your platform, which may be sent to you after your CyberMUT's subscription (contact them via Web, or go to the nearest Credit Mutuel).
Note: These functions only provide a link to CyberMUT SDK. Be sure to read the CyberMUT Developers Guide for full details of the required parameters.
cybermut_creerformulairecm() is used to generate the HTML form of request for payment.
(4.0.5 - 4.2.3 only, PECL)
cybermut_creerreponsecm -- Generate the delivery's acknowledgement of the payment's confirmationThe parameter is "OK" if the message of confirmation of the payment were correctly authenticated by cybermut_testmac(). Any other chain is regarded as an error message.
(4.0.5 - 4.2.3 only, PECL)
cybermut_testmac -- Make sure that there was no data diddling contained in the received message of confirmation
cybermut_testmac() is used to make sure that there was
no data diddling contained in the received message of confirmation.
Pay attention to parameters code_return and
text_free, which cannot be evaluated as is,
because of the dash.
| Warning |
This function is currently not documented; only the argument list is available. |
Note: This extension is not available on Windows platforms.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.
To enable Cyrus IMAP support and to use these functions you have to compile
PHP with the --with-cyrus option.
This extension defines a Cyrus IMAP connection identifier returned by cyrus_connect().
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.
Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.
Note: The timezones referenced in this section can be found in the Appendix I.
There is no installation needed to use these functions; they are part of the PHP core.
Note: The latest version of the timezone database can be installed via PECL's timezonedb. For Windows users, a pre-compiled DLL can be downloaded from the PECL4Win site: php_timezonedb.dll.
The behaviour of these functions is affected by settings in php.ini.
Table 1. Date/Time Configuration Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| date.default_latitude | "31.7667" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.default_longitude | "35.2333" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.sunrise_zenith | "90.83" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.sunset_zenith | "90.83" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.timezone | "" | PHP_INI_ALL | Available since PHP 5.1.0. |
Here's a short explanation of the configuration directives.
date.default_latitude
floatThe default latitude.
date.default_longitude
floatThe default longitude.
date.sunrise_zenith
floatThe default sunrise zenith.
date.sunset_zenith
floatThe default sunset zenith.
date.timezone
string
The default timezone used by all date/time functions if the
TZ environment variable isn't set. The precedence
order is described in the date_default_timezone_get()
page. See Appendix I for a list of supported timezones.
Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().
The following constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).
Atom (example: 2005-08-15T15:52:01+00:00)
HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)
ISO-8601 (example: 2005-08-15T15:52:01+0000)
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)
Same as DATE_ATOM (since PHP 5.1.3)
RSS (Mon, 15 Aug 2005 15:52:01 +0000)
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)
Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().
Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.
monthThe month is between 1 and 12 inclusive.
day
The day is within the allowed number of days for the given
month. Leap years
are taken into consideration.
yearThe year is between 1 and 32767 inclusive.
timeString in a format accepted by strtotime(), defaults to "now".
timezoneTime zone of the time.
objectDateTime object.
yearYear of the date.
monthMonth of the date.
dayDay of the date.
(PHP 5 >= 5.1.0RC1)
date_default_timezone_get -- Gets the default timezone used by all date/time functions in a scriptThis functions returns the default timezone, using the following "guess" order:
The timezone set using the date_default_timezone_set() function (if any)
The TZ environment variable (if non empty)
The date.timezone ini option (if set)
"magical" guess (if the operating system supports it)
If none of the above options succeeds, return UTC
(PHP 5 >= 5.1.0RC1)
date_default_timezone_set -- Sets the default timezone used by all date/time functions in a scriptdate_default_timezone_set() sets the default timezone used by all date/time functions.
Note: Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_STRICT message if using the system settings or the
TZenvironment variable.
Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.
timezone_identifierThe timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Appendix I.
This function returns FALSE if the
timezone_identifier isn't valid, or TRUE
otherwise.
objectDateTime object.
yearYear of the date.
monthMonth of the date.
dayDay of the date.
(no version information, might be only in CVS)
date_parse -- Returns associative array with detailed info about given date
Example 1. A date_parse() example
The above example will output:
|
(no version information, might be only in CVS)
date_sun_info -- Returns an array with information about sunset/sunrise and twilight begin/end
Example 1. A date_sun_info() example
The above example will output:
|
date_sunrise() returns the sunrise time for a given
day (specified as a timestamp) and location.
timestamp
The timestamp of the day from which the sunrise
time is taken.
format
latitudeDefaults to North, pass in a negative value for South. See also: date.default_latitude
longitudeDefaults to East, pass in a negative value for West. See also: date.default_longitude
zenithDefault: date.sunrise_zenith
gmtoffsetSpecified in hours.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
Example 1. date_sunrise() example
The above example will output something similar to:
|
date_sunset() returns the sunset time for a given
day (specified as a timestamp) and location.
timestamp
The timestamp of the day from which the sunset
time is taken.
format
latitudeDefaults to North, pass in a negative value for South. See also: date.default_latitude
longitudeDefaults to East, pass in a negative value for West. See also: date.default_longitude
zenithDefault: date.sunrise_zenith
gmtoffsetSpecified in hours.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
Example 1. date_sunset() example
The above example will output something similar to:
|
objectDateTime object.
hourHour of the time.
minuteMinute of the time.
secondSecond of the time.
Returns a string formatted according to the given format string using the
given integer timestamp or the current time
if no timestamp is given. In other words, timestamp
is optional and defaults to the value of time().
formatThe format of the outputted date string. See the formatting options below.
Table 1. The following characters are recognized in the
format parameter string
format character | Description | Example returned values |
|---|---|---|
| Day | --- | --- |
| d | Day of the month, 2 digits with leading zeros | 01 to 31 |
| D | A textual representation of a day, three letters | Mon through Sun |
| j | Day of the month without leading zeros | 1 to 31 |
| l (lowercase 'L') | A full textual representation of the day of the week | Sunday through Saturday |
| N | ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday) |
| S | English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. Works well with j |
| w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
| z | The day of the year (starting from 0) | 0 through 365 |
| Week | --- | --- |
| W | ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) | Example: 42 (the 42nd week in the year) |
| Month | --- | --- |
| F | A full textual representation of a month, such as January or March | January through December |
| m | Numeric representation of a month, with leading zeros | 01 through 12 |
| M | A short textual representation of a month, three letters | Jan through Dec |
| n | Numeric representation of a month, without leading zeros | 1 through 12 |
| t | Number of days in the given month | 28 through 31 |
| Year | --- | --- |
| L | Whether it's a leap year | 1 if it is a leap year, 0 otherwise. |
| o | ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) | Examples: 1999 or 2003 |
| Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
| y | A two digit representation of a year | Examples: 99 or 03 |
| Time | --- | --- |
| a | Lowercase Ante meridiem and Post meridiem | am or pm |
| A | Uppercase Ante meridiem and Post meridiem | AM or PM |
| B | Swatch Internet time | 000 through 999 |
| g | 12-hour format of an hour without leading zeros | 1 through 12 |
| G | 24-hour format of an hour without leading zeros | 0 through 23 |
| h | 12-hour format of an hour with leading zeros | 01 through 12 |
| H | 24-hour format of an hour with leading zeros | 00 through 23 |
| i | Minutes with leading zeros | 00 to 59 |
| s | Seconds, with leading zeros | 00 through 59 |
| Timezone | --- | --- |
| e | Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores |
| I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise. |
| O | Difference to Greenwich time (GMT) in hours | Example: +0200 |
| P | Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00 |
| T | Timezone abbreviation | Examples: EST, MDT ... |
| Z | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400 |
| Full Date/Time | --- | --- |
| c | ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00 |
| r | RFC 2822 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200 |
| U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time() |
Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
Returns a formatted date string. If a non-numeric value is used for
timestamp, FALSE is returned and an
E_WARNING level error is emitted.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
| Version | Description |
|---|---|
| 5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows). |
| 5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors. |
| 5.1.1 |
There are useful constants
of standard date/time formats that can be used to specify the
format parameter.
|
Example 1. date() examples
|
You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.
It is possible to use date() and mktime() together to find dates in the future or the past.
Example 3. date() and mktime() example
|
Note: This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.
Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.
Example 4. date() Formatting
|
To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().
Note: To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's UNIX_TIMESTAMP function).
Tip: Timestamp of the start of the request is available in
$_SERVER['REQUEST_TIME']since PHP 5.1.
Returns an associative array containing the date
information of the timestamp, or the current
local time if no timestamp is given.
Returns an associative array of information related to
the typestamp. Elements from the returned
associative array are as follows:
Table 1. Key elements of the returned associative array
| Key | Description | Example returned values |
|---|---|---|
| "seconds" | Numeric representation of seconds | 0 to 59 |
| "minutes" | Numeric representation of minutes | 0 to 59 |
| "hours" | Numeric representation of hours | 0 to 23 |
| "mday" | Numeric representation of the day of the month | 1 to 31 |
| "wday" | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
| "mon" | Numeric representation of a month | 1 through 12 |
| "year" | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
| "yday" | Numeric representation of the day of the year | 0 through 365 |
| "weekday" | A full textual representation of the day of the week | Sunday through Saturday |
| "month" | A full textual representation of a month, such as January or March | January through December |
| 0 | Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). | System Dependent, typically -2147483648 through 2147483647. |
This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.
By default an array is returned. If return_float
is set, then a float is returned.
Array keys:
"sec" - seconds since the Unix Epoch
"usec" - microseconds
"minuteswest" - minutes west of Greenwich
"dsttime" - type of dst correction
Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).
Returns a formatted date string. If a non-numeric value is used for
timestamp, FALSE is returned and an
E_WARNING level error is emitted.
| Version | Description |
|---|---|
| 5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows). |
| 5.1.1 |
There are useful constants
of standard date/time formats that can be used to specify the
format parameter.
|
Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.
Like mktime(), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.
hourThe hour
minuteThe minute
secondThe second
monthThe month
dayThe day
yearThe year
is_dst
Parameters always represent a GMT date so is_dst
doesn't influence the result.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
gmstrftime -- Format a GMT/UTC time/date according to locale settingsBehaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".
Returns a number formatted according to the given format string using the
given integer timestamp or the current local time
if no timestamp is given. In other words, timestamp
is optional and defaults to the value of time().
Unlike the function date(), idate()
accepts just one char in the format parameter.
format
Table 1. The following characters are recognized in the
format parameter string
format character | Description |
|---|---|
| B | Swatch Beat/Internet Time |
| d | Day of the month |
| h | Hour (12 hour format) |
| H | Hour (24 hour format) |
| i | Minutes |
| I | returns 1 if DST is activated, 0 otherwise |
| L | returns 1 for leap year, 0 otherwise |
| m | Month number |
| s | Seconds |
| t | Days in current month |
| U | Seconds since the Unix Epoch - January 1 1970 00:00:00 GMT - this is the same as time() |
| w | Day of the week (0 on Sunday) |
| W | ISO-8601 week number of year, weeks starting on Monday |
| y | Year (1 or 2 digits - check note below) |
| Y | Year (4 digits) |
| z | Day of the year |
| Z | Timezone offset in seconds |
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
Returns an integer.
As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
The localtime() function returns an array identical to that of the structure returned by the C function call.
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
is_associativeIf set to FALSE or not supplied than the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() is an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:
"tm_sec" - seconds
"tm_min" - minutes
"tm_hour" - hour
"tm_mday" - day of the month
Months are from 0 (Jan) to 11 (Dec) and days of the week are from 0 (Sun) to 6 (Sat).
"tm_mon" - month of the year, starting with 0 for January
"tm_year" - Years since 1900
"tm_wday" - Day of the week
"tm_yday" - Day of the year
"tm_isdst" - Is daylight savings time in effect
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
Example 1. localtime() example
The above example will output something similar to:
|
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.
get_as_floatWhen called without the optional argument, this function 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. Both portions of the string are returned in units of seconds.
If the optional get_as_float is set to
TRUE then a float (in seconds) is returned.
Example 1. Timing script execution with microtime()
|
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 00:00:00 GMT) 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.
hourThe number of the hour.
minuteThe number of the minute.
secondThe number of seconds past the minute.
monthThe number of the month.
dayThe number of the day.
year
The number of the year, may be a two or four digit value,
with values between 0-69 mapping to 2000-2069 and 70-100 to
1970-2000. On systems where time_t is a 32bit signed integer, as
most common today, the valid range for year
is somewhere between 1901 and 2038, although this limitation is
overcome as of PHP 5.1.0.
is_dst
This parameter can be set to 1 if the time is during daylight savings time (DST),
0 if it is not, or -1 (the default) if it is unknown whether the time is within
daylight savings time or not. If it's unknown, PHP tries to figure it out itself.
This can cause unexpected (but not incorrect) results.
Some times are invalid if DST is enabled on the system PHP is running on or
is_dst is set to 1. If DST is enabled in e.g. 2:00, all times
between 2:00 and 3:00 are invalid and mktime() returns an undefined
(usually negative) value.
Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST
is enabled is evaluated as 23:30 of the previous day.
Note: As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.
mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
Example 1. mktime() example 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 2. Last day of next month The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29".
|
| Caution |
Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038. |
Returns a string formatted according to the given format string
using the given timestamp or the current
local time if no timestamp is given. Month and weekday names and
other language dependent strings respect the current locale set
with setlocale().
Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's strftime(). Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. %e, %T, %R and %D (there might be more) and dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. For Windows systems a complete overview of supported conversion specifiers can be found at this MSDN website.
formatThe following conversion specifiers are recognized in the format string:
%a - abbreviated weekday name according to the current locale
%A - full weekday name according to the current locale
%b - abbreviated month name according to the current locale
%B - full month name according to the current locale
%c - preferred date and time representation for the current locale
%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)
%d - day of the month as a decimal number (range 01 to 31)
%D - same as %m/%d/%y
%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')
%g - like %G, but without the century.
%G - The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead.
%h - same as %b
%H - hour as a decimal number using a 24-hour clock (range 00 to 23)
%I - hour as a decimal number using a 12-hour clock (range 01 to 12)
%j - day of the year as a decimal number (range 001 to 366)
%m - month as a decimal number (range 01 to 12)
%M - minute as a decimal number
%n - newline character
%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
%r - time in a.m. and p.m. notation
%R - time in 24 hour notation
%S - second as a decimal number
%t - tab character
%T - current time, equal to %H:%M:%S
%u - weekday as a decimal number [1,7], with 1 representing Monday
| Warning |
Sun Solaris seems to start with Sunday as 1 although ISO 9889:1999 (the current C standard) clearly specifies that it should be Monday. |
%U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week
%V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. (Use %G or %g for the year component that corresponds to the week number for the specified timestamp.)
%W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week
%w - day of the week as a decimal, Sunday being 0
%x - preferred date representation for the current locale without the time
%X - preferred time representation for the current locale without the date
%y - year as a decimal number without a century (range 00 to 99)
%Y - year as a decimal number including the century
%Z or %z - time zone or name or abbreviation
%% - a literal `%' character
timestamp
The optional timestamp parameter is an
integer Unix timestamp that defaults to the current
local time if a timestamp is not given. In other
words, it defaults to the value of time().
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
This example works if you have the respective locales installed in your system.
Example 2. ISO 8601:1988 week number example
|
Note: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page.
strptime() returns an array with the
date parsed, or FALSE on error.
Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).
Note: This function is not implemented on Windows platforms.
date (string)The string to parse (e.g. returned from strftime())
format (string)
The format used in date (e.g. the same as
used in strftime()).
For more information about the format options, read the strftime() page.
Returns an array, or FALSE on failure.
Table 1. The following parameters are returned in the array
| parameters | Description |
|---|---|
| tm_sec | Seconds after the minute (0-61) |
| tm_min | Minutes after the hour (0-59) |
| tm_hour | Hour since midnight (0-23) |
| tm_mday | Day of the month (1-31) |
| tm_mon | Months since January (0-11) |
| tm_year | Years since 1900 |
| tm_wday | Days since Sunday (0-6) |
| tm_yday | Days since January 1 (0-365) |
| unparsed | the date part which was not
recognized using the specified format |
Example 1. strptime() example
The above example will output something similar to:
|
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
strtotime -- Parse about any English textual datetime description into a Unix timestamp
The function expects to be given a string containing a US English date
format and will try to parse that format into a Unix timestamp (the
number of seconds since January 1 1970 00:00:00 GMT), relative
to the timestamp given in now, or the current time
if none is supplied.
This function will use the TZ environment variable (if
available) to calculate the timestamp. Since PHP 5.1.0 there are easier
ways to define the timezone that is used across all date/time functions.
That process is explained in the
date_default_timezone_get() function page.
Note: If the number of the year is specified in a two digit format, the values between 0-69 are mapped to 2000-2069 and 70-100 to 1970-2000.
timeThe string to parse, according to the GNU Date Input Formats syntax. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.
nowThe timestamp used to calculate the returned value.
Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.
Every call to a date/time function will generate a E_NOTICE
if the time zone is not valid, and/or a E_STRICT message
if using the system settings or the TZ environment
variable. See also date_default_timezone_set()
Example 1. A strtotime() example
|
| Warning |
In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. It differs from other versions where it is correctly computed from current time. |
| Warning |
In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1". |
Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Example 1. time() example
The above example will output something similar to:
|
Tip: Timestamp of the start of the request is available in
$_SERVER['REQUEST_TIME']since PHP 5.1.
(PHP 5 >= 5.1.0RC1)
timezone_abbreviations_list -- Returns associative array containing dst, offset and the timezone name
Example 1. A timezone_abbreviations_list() example
The above example will output something similar to:
|
(PHP 5 >= 5.1.0RC1)
timezone_identifiers_list -- Returns numerically index array with all timezone identifiers
Example 1. A timezone_identifiers_list() example
The above example will output something similar to:
|
(no version information, might be only in CVS)
timezone_name_from_abbr -- Returns the timezone name from abbrevation
abbrTime zone abbreviation.
gmtOffset
Offset from GMT in seconds. Defaults to -1 which means that first found
time zone corresponding to abbr is returned.
Otherwise exact offset is searched and only if not found then the first
time zone with any offset is returned.
isdst
Daylight saving time indicator. If abbr doesn't
exist then the time zone is searched solely by
offset and isdst.
This function returns the offset to GMT for the date/time specified in the
datetime parameter. The GMT offset is calculated
with the timezone information contained in the DateTime object being used.
objectDateTimeZone object.
datetimeDateTime that contains the date/time to compute the offset from.
Example 1. timezone_offset_get() examples
|
timezoneTime zone identifier as full name (e.g. Europe/Prague) or abbreviation (e.g. CET).
(no version information, might be only in CVS)
timezone_transitions_get -- Returns all transitions for the timezoneReturns numerically indexed array containing associative array with all transitions on success or FALSE on failure.
| Warning |
This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk. |
db++, made by the German company Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra than SQL is.
Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.
This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.
Concept asa provides db++ Demo versions and documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).
In order to build this extension yourself you need the db++ client libraries
and header files to be installed on your system (these are included in the
db++ installation archives by default). You have to run
configure with option --with-dbplus to
build this extension.
configure looks for the client libraries and header files
under the default paths /usr/dbplus,
/usr/local/dbplus and /opt/dblus.
If you have installed db++ in a different place you have add the installation
path to the configure option like this:
--with-dbplus=/your/installation/path.
Most db++ functions operate on or return
dbplus_relation resources. A
dbplus_relation is a handle to a stored
relation or a relation generated as the result of a query.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Table 1. DB++ Error Codes
| PHP Constant | db++ constant | meaning |
|---|---|---|
| DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition |
| DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple |
| DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget() |
| DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server) |
| DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close |
| DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked |
| DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked |
| DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked |
| DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation |
| DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation |
| DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed |
| DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed |
| DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length |
| DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed |
| DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing |
| DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation |
| DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation |
| DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size |
| DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage |
| DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek() |
| DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices |
| DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed |
| DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users |
| DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage |
| DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal |
| DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor |
| DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser |
| DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db |
| DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure |
| DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only) |
| DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple |
| DBPLUS_ERR_WARNING0 (integer) | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected |
| DBPLUS_ERR_PANIC (integer) | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients |
| DBPLUS_ERR_FIFO (integer) | ERR_FIFO | Can't create a fifo |
| DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied |
| DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error |
| DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only two users |
| DBPLUS_ERR_USER (integer) | ERR_USER | An error in the use of the library by an application programmer |
| DBPLUS_ERR_UNKNOWN (integer) | ERR_UNKNOWN |
relation
tuple
An array of attribute/value pairs to be inserted into the given
relation.
After successful execution this array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Executes an AQL query on the given
server and dbpath.
queryThe AQL query to be executed. Further information on the AQL A... Query Language is provided in the original db++ manual.
server
dbpath
Returns a relation handle on success. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Changes the virtual current directory where relation files will be looked for by dbplus_open().
newdirThe new directory for relation files. You can omit this parameter to query the current working directory.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Closes a relation previously opened by dbplus_open().
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Reads the data for the current tuple for the given
relation.
relationA relation opened by dbplus_open().
tupleThe data will be passed back in this parameter, as an associative array.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Returns a clear error string for the given error code.
errnoThe error code. If not provided, the result code of the last db++ operation is assumed.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Places a constraint on the given relation.
Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.
relationA relation opened by dbplus_open().
constraints
Constraints are triplets of strings containing of a domain name,
a comparison operator and a comparison value. The
constraints parameter array may consist of
a collection of string arrays, each of which contains a domain, an
operator and a value, or of a single string array containing a
multiple of three elements.
The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.
tuple
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Reads the data for the first tuple for the given
relation, makes it the current tuple and pass it
back as an associative array in tuple.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Writes all changes applied to relation since the
last flush to disk.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Releases a write lock on the given tuple previously
obtained by dbplus_getlock().
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Frees all tuple locks held on the given relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Requests a write lock on the specified tuple.
Returns zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED on failure.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Obtains a number guaranteed to be unique for the given
relation and will pass it back in the variable
given as uniqueid.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Reads the data for the last tuple for the given
relation, makes it the current tuple and pass it
back as an associative array in tuple.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Requests a write lock on the given relation.
Other clients may still query the relation, but can't alter it while it is locked.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Reads the data for the next tuple for the given
relation, makes it the current tuple and will pass
it back as an associative array in tuple.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
nameCan be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.
On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Reads the data for the previous tuple for the given
relation, makes it the current tuple and will pass
it back as an associative array in tuple.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Changes access permissions as specified by mask,
user and group. The
values for these are operating system specific.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Creates a new relation. Any existing relation sharing the same
name will be overwritten if the relation is
currently not in use and overwrite is set to TRUE.
name
domlistA combination of domains. May be passed as a single domain name string or as an array of domain names.
This parameter should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.
Note: This function will also accept a string with space delimited domain description strings, but it is recommended to use an array
overwrite
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
(4.1.0 - 4.2.3 only, PECL)
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices
dbplus_rcrtexact() will create an exact but
empty copy of the given relation under a
new name.
name
relationThe copied relation, opened by dbplus_open().
overwrite
An existing relation by the same name will only
be overwritten if this parameter is set to TRUE and no other process
is currently using the relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
(4.1.0 - 4.2.3 only, PECL)
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices
dbplus_rcrtexact() will create an empty copy
of the given relation under a new
name, but with default indices.
name
relationThe copied relation, opened by dbplus_open().
overwrite
An existing relation by the same name will only
be overwritten if this parameter is set to TRUE and no other process
is currently using the relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_resolve() will try to resolve the given
relation_name and find out internal server
id, real hostname and the database path on this host.
Returns an array containing these values under the keys sid, host and host_path or FALSE on error.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_rkeys() will replace the current
primary key for relation with the
combination of domains specified by domlist.
relationA relation opened by dbplus_open().
domlistA combination of domains. May be passed as a single domain name string or as an array of domain names.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_ropen() will open the relation
file locally for quick access without any
client/server overhead. Access is read only and only
dbplus_current() and
dbplus_next() may be applied to the returned
relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_rrename() will change the name of
relation to name.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_rsecindex() will create a new secondary
index for relation with consists of the
domains specified by domlist and is of
type type
relationA relation opened by dbplus_open().
domlistA combination of domains. May be passed as a single domain name string or as an array of domain names.
type
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_unlink() will close and remove the
relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_rzap() will remove all tuples from
relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.
dbplus_tcl() needs to pass the client
connection id the TCL script code should
be executed by. dbplus_resolve() will provide
this connection id. The function will return whatever the TCL
code returns or a TCL error message if the TCL code fails.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_tremove() removes
tuple from relation
if it perfectly matches a tuple within the
relation. current, if given, will contain
the data of the new current tuple after calling
dbplus_tremove().
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Release a write lock previously obtained by dbplus_lockrel().
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Calling dbplus_unselect() will remove a
constraint previously set by dbplus_find() on
relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
dbplus_update() replaces the old
tuple with the data from the new one, only if the
old completely matches a tuple within
relation.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Request an exclusive lock on relation preventing
even read access from other clients.
| Warning |
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function at your own risk. |
Releases an exclusive lock previously obtained by dbplus_xlockrel().
These functions build the foundation for accessing Berkeley DB style databases.
This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)
The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.
Table 1. List of DBA handlers
| Handler | Notes |
|---|---|
| dbm | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format. |
| ndbm | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated). |
| gdbm | Gdbm is the GNU database manager. |
| db2 | DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications. |
| db3 | DB3 is Sleepycat Software's DB3. |
| db4 | DB4 is Sleepycat Software's DB4. This is available since PHP 4.3.2. |
| cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library. |
| cdb_make | Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used. |
| flatfile | This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library. |
| inifile | This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE. |
| qdbm | This is available since PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net. |
When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().
By using the --enable-dba=shared
configuration option you can build a dynamic loadable module to enable PHP
for basic support of dbm-style databases. You also have to add support
for at least one of the following handlers by specifying the
--with-XXXX configure switch to your PHP
configure line.
| Warning |
After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfaunctioning single handlers but not combinations. |
Table 2. Supported DBA handlers
| Handler | Configure Switch |
|---|---|
| dbm |
To enable support for dbm add
--with-dbm[=DIR].
|
| ndbm |
To enable support for ndbm add
--with-ndbm[=DIR].
|
| gdbm |
To enable support for gdbm add
--with-gdbm[=DIR].
|
| db2 |
To enable support for db2 add
--with-db2[=DIR].
|
| db3 |
To enable support for db3 add
--with-db3[=DIR].
|
| db4 |
To enable support for db4 add
--with-db4[=DIR].
|
| cdb |
To enable support for cdb add
--with-cdb[=DIR].
|
| flatfile |
To enable support for flatfile add
--with-flatfile.
|
| inifile |
To enable support for inifile add
--with-inifile.
|
| qdbm |
To enable support for qdbm add
--with-qdbm[=DIR].
|
Note: Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such misconfigurations.
The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.
DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.
All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().
You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.
dba_close() closes the established database and frees all resources of the specified database handle.
dba_delete() deletes the specified entry from the database.
keyThe key of the entry which is deleted.
handleThe database handler, returned by dba_open() or dba_popen().
dba_exists() checks whether the specified
key exists in the database.
keyThe key the check is performed for.
handleThe database handler, returned by dba_open() or dba_popen().
dba_fetch() fetches the data specified by
key from the database specified with
handle.
keyThe key the data is specified by.
Note: When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().
skipThe number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.
handleThe database handler, returned by dba_open() or dba_popen().
dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.
dba_handlers() list all the handlers supported by this extension.
Returns an array of database handlers. If full_info
is set to TRUE, the array will be associative with the handlers names as
keys, and their version information as value. Otherwise, the result will be
an indexed array of handlers names.
Note: When the internal cdb library is used you will see cdb and cdb_make.
Example 1. dba_handlers() Example
The above example will output something similar to:
|
dba_insert() inserts the entry described with
key and value into the
database.
keyThe key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.
valueThe value to be inserted.
handleThe database handler, returned by dba_open() or dba_popen().
dba_key_split() splits a key (string representation) into an array representation.
Returns an array of the form array(0 => group, 1 =>
value_name). This function will return FALSE if
key is NULL or FALSE.
dba_nextkey() returns the next key of the database and advances the internal key pointer.
dba_open() establishes a database instance for
path with mode using
handler.
pathCommonly a regular path in your filesystem.
modeIt is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.
Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.
If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.
Note: There can only be one writer for one database file. When you use dba on a web server and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:
Table 1. DBA locking
already open mode= "rl"mode= "rlt"mode= "wl"mode= "wlt"mode= "rd"mode= "rdt"mode= "wd"mode= "wdt"not open ok ok ok ok ok ok ok ok mode= "rl"ok ok wait false illegal illegal illegal illegal mode= "wl"wait false wait false illegal illegal illegal illegal mode= "rd"illegal illegal illegal illegal ok ok wait false mode= "wd"illegal illegal illegal illegal wait false wait false
ok: the second call will be successfull. wait: the second call waits until dba_close() is called for the first. false: the second call returns false. illegal: you must not mix "l" and "d" modifiers for modeparameter.
handler
The name of the handler which
shall be used for accessing path. It is passed
all optional parameters given to dba_open() and
can act on behalf of them.
| Version | Description |
|---|---|
| 4.3.0 | It's possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found. |
| 4.3.0 |
Locking and the mode modifiers "l", "d", "-"
and "t" were added.
In previous PHP versions, you must use semaphores to guard against
simultaneous database access for any database handler with the exception
of GDBM. See System V semaphore support.
|
| before 4.3.5 | open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed). |
dba_popen() establishes a persistent database instance
for path with mode using
handler.
pathCommonly a regular path in your filesystem.
modeIt is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.
handler
The name of the handler which
shall be used for accessing path. It is passed
all optional parameters given to dba_popen() and
can act on behalf of them.
dba_replace() replaces or inserts the entry described
with key and value into the
database specified by handle.
keyThe key of the entry to be replaced.
valueThe value to be replaced.
handleThe database handler, returned by dba_open() or dba_popen().
These functions allow you to access records stored in dBase-format (dbf) databases.
dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().
The types of dBase fields available are:
Table 1. Available types of fields
| Field | dBase Type | Format | Additional information |
|---|---|---|---|
| M | Memo | n/a | This type is not supported by PHP, such field will be ignored |
| D | Date | YYYYMMDD | The field length is limited to 8 |
| N | Number | A number | You must declare a length and a precision (the number of digits after the decimal point) |
| C | String | A string | You must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length. |
| L | Boolean | T or Y for TRUE, F or N for FALSE | Stored and returned as an integer (1 or 0) |
| F | Float | A float number | Support for this type of field was added in PHP 5.2.0 |
| Warning |
There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent web server processes modifying the same dBase file will very likely ruin your database. We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers. |
In order to enable the bundled dbase library and to use these functions,
you must compile PHP with the --enable-dbase
option.
Many examples in this reference require a dBase database. We will use /tmp/test.dbf that will be created in the example of dbase_create().
Adds the given data to the database.
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
recordAn indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.
Note: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
dbase_create() creates a dBase database with the given definition.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
Note: This function is affected by open_basedir.
filenameThe name of the database. It can be a relative or absolute path to the file where dBase will store your data.
fieldsAn array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, and a precision.
Note: The fieldnames are limited in length and must not exceed 10 chars.
Returns a database link identifier if the database is successfully created, or FALSE if an error occurred.
Example 1. Creating a dBase database file
|
Marks the given record to be deleted from the database.
Note: To actually remove the record from the database, you must also call dbase_pack().
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
record_numberAn integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).
Returns information on the column structure of the given database link identifier.
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
An indexed array with an entry for each column in the database. The array index starts at 0.
Each array element contains an associative array of column information, as described here:
The name of the column
The human-readable name for the dbase type of the column (i.e. date, boolean, etc.)
The number of bytes this column can hold
The number of digits of decimal precision for the column
A suggested printf() format specifier for the column
The byte offset of the column from the start of the row
If the database header information cannot be read, FALSE is returned.
Example 1. Showing header information for a dBase database file
|
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
dbase_get_record_with_names -- Gets a record from a database as an associative arrayGets a record from a dBase database as an associative array.
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
record_numberThe index of the record.
An associative array with the record. This will also include a key 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, except:
Dates are left as strings.
Integers that would have caused an overflow (> 32 bits) are returned as strings.
On error, dbase_get_record_with_names() will return FALSE.
Example 1. Listing all the registered members in the database
|
Gets a record from a database as an indexed array.
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
record_numberThe index of the record.
An indexed array with the record. This array will also include an associative key 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, except:
Dates are left as strings.
Integers that would have caused an overflow (> 32 bits) are returned as strings.
On error, dbase_get_record() will return FALSE.
Gets the number of fields (columns) in the specified database.
Note: Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
Gets the number of records (rows) in the specified database.
Note: Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
dbase_open() opens a dBase database with the given access mode.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
Note: This function is affected by open_basedir.
filenameThe name of the database. It can be a relative or absolute path to the file where dBase will store your data.
modeAn integer which correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).
Note: You can't open a dBase file in write-only mode as the function will fail to read the headers information and thus you can't use 1 as
mode.
Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.
Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record().
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
Replaces the given record in the database with the given data.
dbase_identifierThe database link identifier, returned by dbase_open() or dbase_create().
recordAn indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.
Note: If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.
record_numberAn integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).
Example 1. Updating a record in the database
|
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).
Note: DBM support is deprecated and you are encouraged to use the Database (dbm-style) abstraction layer functions instead.
Note: This extension has been removed from PHP and is no longer available as of PHP 5.0.0.
To use this functions you have to compile PHP with support for an underlying database. See the list of supported Databases.
In order to use these functions, you must compile PHP with dbm support
by using the --with-db option. In
addition you must ensure support
for an underlying database or you can use some system libraries.
The function dbmopen() returns an database identifier which is used by the other dbm-functions.
Deletes the value for key in the database.
Returns TRUE on success or FALSE on failure. Returns FALSE if the key didn't exist in the database.
Returns TRUE if there is a value associated with the
key.
Gets the value associated with the given key.
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.
Adds the value to the database with the specified key.
dbm_identifierThe DBM link identifier, returned by dbmopen().
keyThe added key
valueThe added key value
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().)
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:
Opens the specified DBM database in the given mode.
filenameThe full-path filename of the DBM file to be opened
flagsThe file open mode which is one of r, n, c or w, for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.
Returns an identifier to be passed to the other DBM functions on success, or FALSE on failure.
Note: 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.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
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.
dbm_identifierThe DBM link identifier, returned by dbmopen().
keyThe replaced key
valueThe new value
The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.
To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:
FrontBase (available from PHP 4.1.0).
Sybase-CT (available from PHP 4.2.0).
Oracle (oci8) (available from PHP 4.3.0).
SQLite (PHP 5).
Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.
In order to have these functions available, you must compile PHP with
dbx support by using the --enable-dbx
option and all options for the databases that will be used, e.g. for
MySQL you must also specify
--with-mysql=[DIR].
To get other supported databases to work with the dbx-module refer to their
specific documentation.
The behaviour of these functions is affected by settings in php.ini.
Table 1. DBX Configuration Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. |
Here's a short explanation of the configuration directives.
dbx.colnames_case
stringColumns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().
There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.
row_aFirst row
row_bSecond row
column_keyThe compared column
flags
The flags can be set to specify comparison
direction:
DBX_CMP_ASC - ascending order
DBX_CMP_DESC - descending order
DBX_CMP_NATIVE - no type conversion
DBX_CMP_TEXT - compare items as strings
DBX_CMP_NUMBER - compare items numerically
flags parameter is
DBX_CMP_ASC | DBX_CMP_NATIVE.
Returns 0 if the row_a[$column_key]
is equal to row_b[$column_key], and 1
or -1 if the former is greater or is smaller than the
latter one, respectively, or vice versa if the flag
is set to DBX_CMP_DESC.
Example 1. dbx_compare() example
|
Opens a connection to a database.
module
The module parameter can be either a string or a
constant, though the latter form is preferred. The possible values are
given below, but keep in mind that they only work if the module is
actually loaded.
DBX_MYSQL or "mysql"
DBX_ODBC or "odbc"
DBX_PGSQL or "pgsql"
DBX_MSSQL or "mssql"
DBX_FBSQL or "fbsql" (available from PHP 4.1.0)
DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)
DBX_OCI8 or "oci8" (available from PHP 4.3.0)
DBX_SQLITE or "sqlite" (PHP 5)
hostThe SQL server host
databaseThe database name
usernameThe username
passwordThe password
persistent
The persistent parameter can be set to
DBX_PERSISTENT, if so, a persistent connection
will be created.
The host, database,
username and password
parameters are expected, but not always used depending on the connect
functions for the abstracted module.
Returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned.
The returned object has three properties:
It is the name of the currently selected database.
It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).
It is used internally by dbx only, and is actually the module number mentioned above.
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
dbx_error -- Report the error message of the latest function call in the module
Returns a string containing the error message from the last function call
of the abstracted module (e.g. mysql module). If there are multiple
connections in the same module, just the last error is given. If there are
connections on different modules, the latest error is returned for the
module specified by the link_identifier parameter.
Note: Always refer to the module-specific documentation as well.
The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.
The error message for Oracle (oci8) is not implemented yet.
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
dbx_escape_string -- Escape a string so it can safely be used in an sql-statementEscape the given string so that it can safely be used in an sql-statement.
Returns the text, escaped where necessary (such as quotes, backslashes etc). On error, NULL is returned.
Example 1. dbx_escape_string() example
|
(PHP 5 <= 5.0.4)
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag setdbx_fetch_row() fetches rows from a result identifier that had the DBX_RESULT_UNBUFFERED flag set.
When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.
As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().
Returns an object on success that contains the same information as any row would have in the dbx_query() result data property, including columns accessible by index or fieldname when the flags for dbx_query() were set that way.
Upon failure, returns 0 (e.g. when no more rows are available).
Example 1. How to handle the returned value
|
Sends a query and fetch all results.
link_identifierThe DBX link object returned by dbx_connect()
sql_statementSQL statement.
flagsThe compared column
flags
The flags parameter is used to control the amount of
information that is returned. It may be any combination of the following
constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags
override the dbx.colnames_case setting from php.ini.
It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.
If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.
It provides info about columns, such as field names and field types.
It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property.
Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.
This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row.
The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.
The case of the returned column names will not be changed.
The case of the returned column names will be changed to uppercase.
The case of the returned column names will be changed to lowercase.
flags parameter. This means
that only the following combinations are effective:
DBX_RESULT_INDEX
DBX_RESULT_INDEX | DBX_RESULT_INFO
DBX_RESULT_INDEX |
DBX_RESULT_INFO |
DBX_RESULT_ASSOC - this is the default, if
flags is not specified.
dbx_query() returns an object or 1
on success, and 0 on failure. The result object is
returned only if the query given in sql_statement
produces a result set (i.e. a SELECT query, even if the result set is
empty).
The returned object has four or five
properties depending on flags:
It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).
These contain the number of columns (or fields) and rows (or records) respectively.
It is returned only if either DBX_RESULT_INFO or
DBX_RESULT_ASSOC is specified in the
flags parameter. It is a 2 dimensional array,
that has two named rows (name and
type) to retrieve column information.
This property contains the actual resulting data, possibly associated
with column names as well depending on flags.
If DBX_RESULT_ASSOC is set, it is possible to use
$result->data[2]["field_name"].
Example 2. outputs the content of data property into HTML table
|
Example 3. How to handle UNBUFFERED queries
|
Example 4. How to handle the returned value
|
Note: Always refer to the module-specific documentation as well.
Column names for queries on an Oracle database are returned in lowercase.
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
dbx_sort -- Sort a result from a dbx_query by a custom sort functionSort a result from a dbx_query() call with a custom sort function.
resultA result set returned by dbx_query().
user_compare_functionThe user-defined comparison function. It must accept two arguments and return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Example 1. dbx_sort() example
|
PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.
This extension is only available on Windows Platforms as of PHP 5.0.0
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
One resource type is defined by this extension: a file descriptor returned by dio_open().
The dio_fcntl() function performs the
operation specified by cmd on the file
descriptor fd. Some commands require
additional arguments args to be supplied.
Note: This function is not implemented on Windows platforms.
fdThe file descriptor returned by dio_open().
cmdCan be one of the following operations:
F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.
F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.
F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.
F_DUPFD - finds the lowest numbered available
file descriptor greater than or equal to args
and returns them.
F_SETFL - Sets the file descriptors flags to
the value specified by args, which can be
O_APPEND, O_NONBLOCK or
O_ASYNC. To use O_ASYNC
you will need to use the PCNTL
extension.
args
args is an associative array, when
cmd is F_SETLK or
F_SETLLW, with the following keys:
"start" - offset where lock begins
"length" - size of locked area. zero means to end of file
"wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR
"type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)
Example 1. Setting and clearing a lock
|
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_open -- Opens a new filename with specified permissions of flags and creation permissions of modedio_open() opens a file and returns a new file descriptor for it.
filenameThe opened file.
flags
The flags parameter can also include any
combination of the following flags:
O_CREAT - creates the file, if it doesn't already exist.
O_EXCL - if both, O_CREAT and O_EXCL are set, dio_open() fails, if the file already exists.
O_TRUNC - if the file exists, and its opened for write access, the file will be truncated to zero length.
O_APPEND - write operations write data at the end of the file.
O_NONBLOCK - sets non blocking mode.
mode
If flags is O_CREAT,
mode will set the mode of the file
(creation permissions).
O_RDONLY - opens the file for read access.
O_WRONLY - opens the file for write access.
O_RDWR - opens the file for both reading and writing.
The function dio_read() reads and returns
len bytes from file with descriptor
fd.
fdThe file descriptor returned by dio_open().
lenThe number of bytes to read. If not specified, dio_read() reads 1K sized block.
The function dio_seek() is used to change the file position of the given file descriptor.
fdThe file descriptor returned by dio_open().
posThe new position.
whence
Specifies how the position pos should be
interpreted:
SEEK_SET (default) - specifies that
pos is specified from the beginning of the
file.
SEEK_CUR - Specifies that
pos is a count of characters from the current
file position. This count may be positive or negative.
SEEK_END - Specifies that
pos is a count of characters from the end of
the file. A negative count specifies a position within the current
extent of the file; a positive count specifies a position past the
current end. If you set the position past the current end, and
actually write data, you will extend the file with zeros up to that
position.
Example 1. Positioning in a file
|
dio_stat() returns information about the given file descriptor.
Returns an associative array with the following keys:
"device" - device
"inode" - inode
"mode" - mode
"nlink" - number of hard links
"uid" - user id
"gid" - group id
"device_type" - device type (if inode device)
"size" - total size in bytes
"blocksize" - blocksize
"blocks" - number of blocks allocated
"atime" - time of last access
"mtime" - time of last modification
"ctime" - time of last change
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
dio_tcsetattr -- Sets terminal attributes and baud rate for a serial port
dio_tcsetattr() sets the terminal attributes and baud
rate of the open fd.
Note: This function is not implemented on Windows platforms.
fdThe file descriptor returned by dio_open().
optionsThe currently available options are:
'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.
'bits' - data bits - can be 8,7,6 or 5. Default value is 8.
'stop' - stop bits - can be 1 or 2. Default value is 1.
'parity' - can be 0,1 or 2. Default value is 0.
Example 1. Setting the baud rate on a serial port
|
dio_truncate() truncates a file to at most
offset bytes in size.
If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.
Note: This function is not implemented on Windows platforms.
dio_write() writes up to len
bytes from data to file fd.
fdThe file descriptor returned by dio_open().
dataThe written data.
lenThe length of data to write in bytes. If not specified, the function writes all the data to the specified file.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Note: The PATH_SEPARATOR was introduced with PHP 4.3.0-RC2.
Note: When safe mode is enabled, PHP checks whether the directory in which you are about to operate has the same UID (owner) as the script that is being executed.
Changes the root directory of the current process to
directory.
This function is only available if your system supports it and you're using the CLI, CGI or Embed SAPI. Also, this function requires root privileges.
A pseudo-object oriented mechanism for reading a directory. The
given directory is opened. Two properties
are available once the 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 Please note the fashion in which dir()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.
The above example will output something similar to:
|
Note: The order in which directory entries are returned by the read method is system-dependent.
Note: This defines the internal class Directory, meaning that you will not be able to define your own classes with that name. For a full list of predefined classes in PHP, please see Predefined Classes.
Closes the directory stream indicated by
dir_handle. The stream must have previously
been opened by opendir().
Returns the current working directory on success, or FALSE on failure.
On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does. See chmod() for more information on modes and permissions.
Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.
pathThe directory path that is to be opened
context
For a description of the context parameter,
refer to the streams section of
the manual.
Returns a directory handle resource on success, or FALSE on failure.
If path is not a valid directory or the
directory can not be opened due to permission restrictions or
filesystem errors, opendir() returns FALSE and
generates a PHP error of level
E_WARNING. You can suppress the error output of
opendir() by prepending
'@' to the
front of the function name.
Example 1. opendir() example
The above example will output something similar to:
|
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.
Example 1. List all files in a directory Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").
|
Resets the directory stream indicated by
dir_handle to the beginning of the
directory.
Returns an array of files and directories from the
directory.
directoryThe directory that will be scanned.
sorting_order
By default, the sorted order is alphabetical in ascending order. If
the optional sorting_order is used (set to 1),
then the sort order is alphabetical in descending order.
context
For a description of the context parameter,
refer to the streams section of
the manual.
Returns an array of filenames on success, or FALSE on
failure. If directory is not a directory, then
boolean FALSE is returned, and an error of level
E_WARNING is generated.
Example 1. A simple scandir() example
The above example will output something similar to:
|
Example 2. PHP 4 alternatives to scandir()
The above example will output something similar to:
|
Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix N for a list of supported URL protocols.
The DOM extension allows you to operate on XML documents through the DOM API with PHP 5.
For PHP 4, use DOM XML.
The API of the module follows the DOM Level 3 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module.
This module defines a number of classes, which are explained in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.
Extends DOMNode. The DOMAttr interface represents an attribute in an DOMElement object.
Extends DOMNode.
DOMCharacterData->appendData() - Append a string to the end of the character data of the node
DOMCharacterData->deleteData() - Remove a range of characters from the node
DOMCharacterData->insertData() - Insert a string at the specified 16-bit unit offset
DOMCharacterData->replaceData() - Replace a substring within the DOMCharacterData node
DOMCharacterData->substringData() - Extracts a range of data from the node
Extends DOMNode.
DOMDocument->createAttribute() - Create new attribute
DOMDocument->createAttributeNS() - Create new attribute node with an associated namespace
DOMDocument->createCDATASection() - Create new cdata node
DOMDocument->createComment() - Create new comment node
DOMDocument->createDocumentFragment() - Create new document fragment
DOMDocument->createElement() - Create new element node
DOMDocument->createElementNS() - Create new element node with an associated namespace
DOMDocument->createEntityReference() - Create new entity reference node
DOMDocument->createProcessingInstruction() - Creates new PI node
DOMDocument->createTextNode() - Create new text node
DOMDocument->getElementById() - Searches for an element with a certain id
DOMDocument->getElementsByTagName() - Searches for all elements with given tag name
DOMDocument->getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace
DOMDocument->importNode() - Import node into current document
DOMDocument->load() - Load XML from a file
DOMDocument->loadHTML() - Load HTML from a string
DOMDocument->loadHTMLFile() - Load HTML from a file
DOMDocument->loadXML() - Load XML from a string
DOMDocument->normalizeDocument() - Normalizes the document
DOMDocument->relaxNGValidate() - Performs relaxNG validation on the document
DOMDocument->relaxNGValidateSource() - Performs relaxNG validation on the document
DOMDocument->registerNodeClass() - Register extended class used to create base node type (not DOM standard)
DOMDocument->save() - Dumps the internal XML tree back into a file
DOMDocument->saveHTML() - Dumps the internal document into a string using HTML formatting
DOMDocument->saveHTMLFile() - Dumps the internal document back into a file using HTML formatting
DOMDocument->saveXML() - Dumps the internal XML tree back into a string
DOMDocument->schemaValidate() - Validates a document based on a schema
DOMDocument->schemaValidateSource() - Validates a document based on a schema
DOMDocument->validate() - Validates the document based on its DTD
DOMDocument->xinclude() - Substitutes XIncludes in a DOMDocument Object
Table 3.
| Name | Type | Read-only | Description |
|---|---|---|---|
| actualEncoding | string | yes | |
| config | DOMConfiguration | yes | |
| doctype | DOMDocumentType | yes | The Document Type Declaration associated with this document. |
| documentElement | DOMElement | yes | This is a convenience attribute that allows direct access to the child node that is the document element of the document. |
| documentURI | string | no | The location of the document or NULL if undefined. |
| encoding | string | no | |
| formatOutput | bool | no | |
| implementation | DOMImplementation | yes | The DOMImplementation object that handles this document. |
| preserveWhiteSpace | bool | no | Do not remove redundant white space. Default to TRUE. |
| recover | bool | no | |
| resolveExternals | bool | no | Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document. |
| standalone | bool | no | |
| strictErrorChecking | bool | no | Throws DOMException on errors. Default to TRUE. |
| substituteEntities | bool | no | |
| validateOnParse | bool | no | Loads and validates against the DTD. Default to FALSE. |
| version | string | no | |
| xmlEncoding | string | yes | An attribute specifying, as part of the XML declaration, the encoding of this document. This is NULL when unspecified or when it is not known, such as when the Document was created in memory. |
| xmlStandalone | bool | no | An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified. |
| xmlVersion | string | no | An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0". |
Extends DOMNode
Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.
Table 4.
| Name | Type | Read-only | Description |
|---|---|---|---|
| publicId | string | yes | The public identifier of the external subset. |
| systemId | string | yes | The system identifier of the external subset. This may be an absolute URI or not. |
| name | string | yes | The name of DTD; i.e., the name immediately following the DOCTYPE keyword. |
| entities | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD. |
| notations | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the notations declared in the DTD. |
| internalSubset | string | yes | The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets. |
Extends DOMNode.
DOMElement->getAttribute() - Returns value of attribute
DOMElement->getAttributeNode() - Returns attribute node
DOMElement->getAttributeNodeNS() - Returns attribute node
DOMElement->getAttributeNS() - Returns value of attribute
DOMElement->getElementsByTagName() - Gets elements by tagname
DOMElement->getElementsByTagNameNS() - Get elements by namespaceURI and localName
DOMElement->hasAttribute() - Checks to see if attribute exists
DOMElement->hasAttributeNS() - Checks to see if attribute exists
DOMElement->removeAttribute() - Removes attribute
DOMElement->removeAttributeNode() - Removes attribute
DOMElement->removeAttributeNS() - Removes attribute
DOMElement->setAttribute() - Adds new attribute
DOMElement->setAttributeNode() - Adds new attribute node to element
DOMElement->setAttributeNodeNS() - Adds new attribute node to element
DOMElement->setAttributeNS() - Adds new attribute
DOMElement->setIdAttribute() - Declares the ID attribute
DOMElement->setIdAttributeNode() - Declares the ID attribute
DOMElement->setIdAttributeNS() - Declares the ID attribute
Extends DOMNode
This interface represents a known entity, either parsed or unparsed, in an XML document.
Table 6.
| Name | Type | Read-only | Description |
|---|---|---|---|
| publicId | string | yes | The public identifier associated with the entity if specified, and NULL otherwise. |
| systemId | string | yes | The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not. |
| notationName | string | yes | For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL. |
| actualEncoding | string | no | An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is NULL if it an entity from the internal subset or if it is not known. |
| encoding | string | yes | An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is NULL otherwise. |
| version | string | yes | An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is NULL otherwise. |
DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.
See also Chapter 20.
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
DOMImplementation->createDocument() - Creates a DOM Document object of the specified type with its document element
DOMImplementation->createDocumentType() - Creates an empty DOMDocumentType object
DOMImplementation->hasFeature() - Test if the DOM implementation implements a specific feature
DOMNamedNodeMap->getNamedItem() - Retrieves a node specified by name
DOMNamedNodeMap->getNamedItemNS() - Retrieves a node specified by local name and namespace URI
DOMNamedNodeMap->item() - Retrieves a node specified by index
DOMNode->appendChild() - Adds new child at the end of the children
DOMNode->cloneNode() - Clones a node
DOMNode->hasAttributes() - Checks if node has attributes
DOMNode->hasChildNodes() - Checks if node has children
DOMNode->insertBefore() - Adds a new child before a reference node
DOMNode->isDefaultNamespace() - Checks if the specified namespaceURI is the default namespace
DOMNode->isSameNode() - Indicates if two nodes are the same node
DOMNode->isSupported() - Checks if feature is supported for specified version
DOMNode->lookupNamespaceURI() - Returns namespace URI of the node based on the prefix
DOMNode->lookupPrefix() - Returns name space prefix of the node based on namespaceURI
DOMNode->normalize() - Normalizes the node
DOMNode->removeChild() - Removes child from list of children
DOMNode->replaceChild() - Replaces a child
Table 8.
| Name | Type | Read-only | Description |
|---|---|---|---|
| nodeName | string | yes | Returns the most accurate name for the current node type |
| nodeValue | string | no | The value of this node, depending on its type. |
| nodeType | int | yes | Gets the type of the node. One of the predefined XML_xxx_NODE constants |
| parentNode | DOMNode | yes | The parent of this node. |
| childNodes | DOMNodeList | yes | A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList. |
| firstChild | DOMNode | yes | The first child of this node. If there is no such node, this returns NULL. |
| lastChild | DOMNode | yes | The last child of this node. If there is no such node, this returns NULL. |
| previousSibling | DOMNode | yes | The node immediately preceding this node. If there is no such node, this returns NULL. |
| nextSibling | DOMNode | yes | The node immediately following this node. If there is no such node, this returns NULL. |
| attributes | DOMNamedNodeMap | yes | A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise. |
| ownerDocument | DOMDocument | yes | The DOMDocument object associated with this node. |
| namespaceURI | string | yes | The namespace URI of this node, or NULL if it is unspecified. |
| prefix | string | no | The namespace prefix of this node, or NULL if it is unspecified. |
| localName | string | yes | Returns the local part of the qualified name of this node. |
| baseURI | string | yes | The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI. |
| textContent | string | no | This attribute returns the text content of this node and its descendants. |
Extends DOMNode.
DOMProcessingInstruction->__construct() - construct a new DOMProcessingInstruction object
Extends DOMCharacterData.
DOMText->isWhitespaceInElementContent() - Indicates whether this text node contains whitespace
DOMText->splitText() - Breaks the node into two nodes at the specified offset
DOMXPath->registerNamespace() - Registers the namespace with the DOMXpath object
DOMXPath->evaluate() - Evaluates the given XPath expression and returns a typed result if possible
DOMXPath->query() - Evaluates the given XPath expression
Many examples in this reference require an XML file. We will use book.xml that contains the following:
Example 1. book.xml
|
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Table 14. XML constants
| Constant | Value | Description |
|---|---|---|
| XML_ELEMENT_NODE (integer) | 1 | Node is a DOMElement |
| XML_ATTRIBUTE_NODE (integer) | 2 | Node is a DOMAttr |
| XML_TEXT_NODE (integer) | 3 | Node is a DOMText |
| XML_CDATA_SECTION_NODE (integer) | 4 | Node is a DOMCharacterData |
| XML_ENTITY_REF_NODE (integer) | 5 | Node is a DOMEntityReference |
| XML_ENTITY_NODE (integer) | 6 | Node is a DOMEntity |
| XML_PI_NODE (integer) | 7 | Node is a DOMProcessingInstruction |
| XML_COMMENT_NODE (integer) | 8 | Node is a DOMComment |
| XML_DOCUMENT_NODE (integer) | 9 | Node is a DOMDocument |
| XML_DOCUMENT_TYPE_NODE (integer) | 10 | Node is a DOMDocumentType |
| XML_DOCUMENT_FRAG_NODE (integer) | 11 | Node is a DOMDocumentFragment |
| XML_NOTATION_NODE (integer) | 12 | Node is a DOMNotation |
| XML_HTML_DOCUMENT_NODE (integer) | 13 | |
| XML_DTD_NODE (integer) | 14 | |
| XML_ELEMENT_DECL_NODE (integer) | 15 | |
| XML_ATTRIBUTE_DECL_NODE (integer) | 16 | |
| XML_ENTITY_DECL_NODE (integer) | 17 | |
| XML_NAMESPACE_DECL_NODE (integer) | 18 | |
| XML_ATTRIBUTE_CDATA (integer) | 1 | |
| XML_ATTRIBUTE_ID (integer) | 2 | |
| XML_ATTRIBUTE_IDREF (integer) | 3 | |
| XML_ATTRIBUTE_IDREFS (integer) | 4 | |
| XML_ATTRIBUTE_ENTITY (integer) | 5 | |
| XML_ATTRIBUTE_NMTOKEN (integer) | 7 | |
| XML_ATTRIBUTE_NMTOKENS (integer) | 8 | |
| XML_ATTRIBUTE_ENUMERATION (integer) | 9 | |
| XML_ATTRIBUTE_NOTATION (integer) | 10 |
Table 15. DOMException constants
| Constant | Value | Description |
|---|---|---|
| DOM_INDEX_SIZE_ERR (integer) | 1 | If index or size is negative, or greater than the allowed value. |
| DOMSTRING_SIZE_ERR (integer) | 2 | If the specified range of text does not fit into a DOMString. |
| DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | If any node is inserted somewhere it doesn't belong |
| DOM_WRONG_DOCUMENT_ERR (integer) | 4 | If a node is used in a different document than the one that created it. |
| DOM_INVALID_CHARACTER_ERR (integer) | 5 | If an invalid or illegal character is specified, such as in a name. |
| DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | If data is specified for a node which does not support data. |
| DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | If an attempt is made to modify an object where modifications are not allowed. |
| DOM_NOT_FOUND_ERR (integer) | 8 | If an attempt is made to reference a node in a context where it does not exist. |
| DOM_NOT_SUPPORTED_ERR (integer) | 9 | If the implementation does not support the requested type of object or operation. |
| DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | If an attempt is made to add an attribute that is already in use elsewhere. |
| DOM_INVALID_STATE_ERR (integer) | 11 | If an attempt is made to use an object that is not, or is no longer, usable. |
| DOM_SYNTAX_ERR (integer) | 12 | If an invalid or illegal string is specified. |
| DOM_INVALID_MODIFICATION_ERR (integer) | 13 | If an attempt is made to modify the type of the underlying object. |
| DOM_NAMESPACE_ERR (integer) | 14 | If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces. |
| DOM_INVALID_ACCESS_ERR (integer) | 15 | If a parameter or an operation is not supported by the underlying object. |
| DOM_VALIDATION_ERR (integer) | 16 | If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done. |
(no version information, might be only in CVS)
DOMAttr->__construct() -- Creates a new DOMAttr objectCreates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createAttribute().
Example 1. Creating a new DOMAttr
|
(no version information, might be only in CVS)
DOMAttr->isId() -- Checks if attribute is a defined IDThis function checks if the attribute is a defined ID.
According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument->validate() or DOMDocument::validateOnParse before using this function.
Example 1. DOMAttr->isId() Example
|
(no version information, might be only in CVS)
DOMCharacterData->appendData() -- Append the string to the end of the character data of the node
Append the string data to the end of the character data of the node.
| DOMCharacterData->deleteData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->replaceData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->deleteData() -- Remove a range of characters from the node
Deletes count characters starting from position
offset.
offsetThe offset from which to start removing.
count
The number of characters to delete. If the sum of
offset and count exceeds
the length, then all characters to the end of the data are deleted.
Raised if offset is negative or greater than the
number of 16-bit units in data, or if count is
negative.
| DOMCharacterData->appendData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->replaceData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->insertData() -- Insert a string at the specified 16-bit unit offset
Inserts string data at position offset.
Raised if offset is negative or greater than the
number of 16-bit units in data.
| DOMCharacterData->appendData() |
| DOMCharacterData->deleteData() |
| DOMCharacterData->replaceData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->replaceData() -- Replace a substring within the DOMCharacterData node
Replace count characters starting from position
offset with data.
offsetThe offset from which to start replacing.
count
The number of characters to replace. If the sum of
offset and count exceeds
the length, then all characters to the end of the data are replaced.
dataThe string with which the range must be replaced.
Raised if offset is negative or greater than the
number of 16-bit units in data, or if count is
negative.
| DOMCharacterData->appendData() |
| DOMCharacterData->deleteData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->substringData() -- Extracts a range of data from the nodeReturns the specified substring.
The specified substring. If the sum of offset
and count exceeds the length, then all 16-bit units
to the end of the data are returned.
Raised if offset is negative or greater than the
number of 16-bit units in data, or if count is
negative.
| DOMCharacterData->appendData() |
| DOMCharacterData->deleteData() |
| DOMCharacterData->insertData() |
| DOMCharacterData->replaceData() |
(no version information, might be only in CVS)
DOMComment->__construct() -- Creates a new DOMComment objectCreates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createComment().
Example 1. Creating a new DOMComment
|
(no version information, might be only in CVS)
DOMDocument->__construct() -- Creates a new DOMDocument objectCreates a new DOMDocument object.
versionThe version number of the document as part of the XML declaration.
encodingThe encoding of the document as part of the XML declaration.
(no version information, might be only in CVS)
DOMDocument->createAttribute() -- Create new attributeThis function creates a new instance of class DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
| DOMNode->appendChild() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createAttributeNS() -- Create new attribute node with an associated namespaceThis function creates a new instance of class DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
namespaceURIThe URI of the namespace.
qualifiedNameThe tag name and prefix of the attribute, as prefix:tagname.
Raised if qualifiedName contains an invalid character.
Raised if qualifiedName is a malformed qualified
name, or if qualifiedName has a prefix and
namespaceURI is NULL.
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createCDATASection() -- Create new cdata nodeThis function creates a new instance of class DOMCDATASection. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createComment() -- Create new comment nodeThis function creates a new instance of class DOMComment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createDocumentFragment() -- Create new document fragmentThis function creates a new instance of class DOMDocumentFragment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElement() -- Create new element nodeThis function creates a new instance of class DOMElement. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
nameThe tag name of the element.
valueThe value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.
Example 1. Creating a new element and inserting it as root
The above example will output:
|
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElementNS() -- Create new element node with an associated namespaceThis function creates a new element node with an associated namespace. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
namespaceURIThe URI of the namespace.
qualifiedNameThe qualified name of the element, as prefix:tagname.
valueThe value of the element. By default, an empty element will be created. You can also set the value later with DOMElement->nodeValue.
Raised if qualifiedName contains an invalid character.
Raised if qualifiedName is a maformed qualified
name.
Example 1. Creating a new element and inserting it as root
The above example will output:
|
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createEntityReference() -- Create new entity reference nodeThis function creates a new instance of class DOMEntityReference. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
nameThe content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createProcessingInstruction() |
| DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createProcessingInstruction() -- Creates new PI nodeThis function creates a new instance of class DOMProcessingInstruction. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
targetThe target of the processing instruction.
dataThe content of the processing instruction.
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createTextNode() |
This function creates a new instance of class DOMText. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
| DOMNode->appendChild() |
| DOMDocument->createAttribute() |
| DOMDocument->createAttributeNS() |
| DOMDocument->createCDATASection() |
| DOMDocument->createComment() |
| DOMDocument->createDocumentFragment() |
| DOMDocument->createElement() |
| DOMDocument->createElementNS() |
| DOMDocument->createEntityReference() |
| DOMDocument->createProcessingInstruction() |
(no version information, might be only in CVS)
DOMDocument->getElementById() -- Searches for an element with a certain idThis function is similar to DOMDocument->getElementsByTagName() but searches for an element with a given id.
For this function to work, you will need either to set some ID attributes with DOMElement->setIdAttribute() or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument->validate() or DOMDocument->validateOnParse before using this function.
Example 1. DOMDocument->getElementById() Example
The above example will output:
|
(no version information, might be only in CVS)
DOMDocument->getElementsByTagName() -- Searches for all elements with given tag nameThis function returns a new instance of class DOMNodeList containing the elements with a given tag name.
(no version information, might be only in CVS)
DOMDocument->getElementsByTagNameNS() -- Searches for all elements with given tag name in specified namespaceReturns a DOMNodeList of all elements with a given local name and a namespace URI.
namespaceURIThe namespace URI of the elements to match on. The special value * matches all namespaces.
localNameThe local name of the elements to match on. The special value * matches all local names.
Example 1. Get all the XInclude elements
The above example will output:
|
(no version information, might be only in CVS)
DOMDocument->importNode() -- Import node into current documentThis function returns a copy of the node to import and associates it with the current document.
importedNodeThe node to import.
deep
If set to TRUE, this method will recursively import the subtree under
the importedNode.
Loads an XML document from a file.
Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument.
The function parses the HTML contained in the string source.
Unlike loading XML, HTML does not have to be well-formed to load. This
function may also be called statically to load and create a
DOMDocument object. The static invocation may be
used when no DOMDocument properties need to be
set prior to loading.
The function parses the HTML document in the file named
filename. Unlike loading XML, HTML does not have
to be well-formed to load.
This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.
Loads an XML document from a string.
This method may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.
Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument.
(no version information, might be only in CVS)
DOMDocument->normalizeDocument() -- Normalizes the documentThis method acts as if you saved and then loaded the document, putting the document in a "normal" form.
(no version information, might be only in CVS)
DOMDocument->registerNodeClass() -- Register extended class used to create base node typeThis method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension.
This method is not part of the DOM standard.
baseclassThe DOM class that you want to extend. You can find a list of these classes in the chapter introduction.
Of course, you won't be able to register a class extending DOMDocument but you can always start your document by instanciating your own extending class.
extendedclass
Your extended class name. If NULL is provided, any previously
registered class extending baseclass will
be removed.
Example 1. Adding a new method to DOMElement to ease our code
The above example will output:
|
(no version information, might be only in CVS)
DOMDocument->relaxNGValidate() -- Performs relaxNG validation on the documentPerforms relaxNG validation on the document based on the given RNG schema.
| DOMDocument->relaxNGValidateSource() |
| DOMDocument->schemaValidate() |
| DOMDocument->schemaValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->relaxNGValidateSource() -- Performs relaxNG validation on the documentPerforms relaxNG validation on the document based on the given RNG source.
| DOMDocument->relaxNGValidate() |
| DOMDocument->schemaValidate() |
| DOMDocument->schemaValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->save() -- Dumps the internal XML tree back into a fileCreates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
filenameThe path to the saved XML document.
optionsAdditional Options. Currently only LIBXML_NOEMPTYTAG is supported.
Example 1. Saving a DOM tree into a file
|
(no version information, might be only in CVS)
DOMDocument->saveHTML() -- Dumps the internal document into a string using HTML formattingCreates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Example 1. Saving a HTML tree into a string
|
(no version information, might be only in CVS)
DOMDocument->saveHTMLFile() -- Dumps the internal document into a file using HTML formattingCreates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Example 1. Saving a HTML tree into a file
|
(no version information, might be only in CVS)
DOMDocument->saveXML() -- Dumps the internal XML tree back into a stringCreates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
nodeUse this parameter to output only a specific node without XML declaration rather than the entire document.
optionsAdditional Options. Currently only LIBXML_NOEMPTYTAG is supported.
Example 1. Saving a DOM tree into a string
The above example will output:
|
(no version information, might be only in CVS)
DOMDocument->schemaValidate() -- Validates a document based on a schemaValidates a document based on the given schema file.
| DOMDocument->schemaValidateSource() |
| DOMDocument->relaxNGValidate() |
| DOMDocument->relaxNGValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->schemaValidateSource() -- Validates a document based on a schemaValidates a document based on a schema defined in the given string.
| DOMDocument->schemaValidate() |
| DOMDocument->relaxNGValidate() |
| DOMDocument->relaxNGValidateSource() |
| DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->validate() -- Validates the document based on its DTDValidates the document based on its DTD.
You can also use the validateOnParse property of DOMDocument to make a DTD validation.
Returns TRUE on success or FALSE on failure. If the document have no DTD attached, this method will return FALSE.
| DOMDocument->schemaValidate() |
| DOMDocument->schemaValidateSource() |
| DOMDocument->relaxNGValidate() |
| DOMDocument->relaxNGValidateSource() |
(no version information, might be only in CVS)
DOMDocument->xinclude() -- Substitutes XIncludes in a DOMDocument ObjectThis method substitutes XIncludes in a DOMDocument object.
Note: Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.
Example 1. DOMDocument->xinclude() example
The above example will output something similar to:
|
(no version information, might be only in CVS)
DOMDocumentFragment->appendXML() -- Append raw XML dataAppends raw XML data to a DOMDocumentFragment.
This method is not part of the DOM standard. It was created as a simplier approach for appending an XML DocumentFragment in a DOMDocument.
If you want to stick to the standards, you will have to create a temporary DOMDocument with a dummy root and then loop through the child nodes of the root of your XML data to append them.
Example 1. Appending XML data to your document
The above example will output:
|
(no version information, might be only in CVS)
DOMElement->__construct() -- Creates a new DOMElement objectCreates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createElement() or DOMDocument->createElementNS().
nameThe tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.
valueThe value of the element.
namespaceURIA namespace URI to create the element within a specific namespace.
Example 1. Creating a new DOMElement
|
(no version information, might be only in CVS)
DOMElement->getAttribute() -- Returns value of attribute
Gets the value of the attribute with name name
for the current node.
The value of the attribute, or an empty string if no attribute with the
given name is found.
(no version information, might be only in CVS)
DOMElement->getAttributeNode() -- Returns attribute node
Returns the attribute node with name name for the
current element.
(no version information, might be only in CVS)
DOMElement->getAttributeNodeNS() -- Returns attribute node
Returns the attribute node in namespace namespaceURI
with local name localName for the current node.
| DOMElement->hasAttributeNS() |
| DOMElement->setAttributeNodeNS() |
| DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->getAttributeNS() -- Returns value of attribute
Gets the value of the attribute in namespace namespaceURI
with local name localName for the current node.
The value of the attribute, or an empty string if no attribute with the
given localName and namespaceURI
is found.
(no version information, might be only in CVS)
DOMElement->getElementsByTagName() -- Gets elements by tagname
This function returns a new instance of the class
DOMNodeList of all descendant elements with a
given tag name, in the order in which they are
encountered in a preorder traversal of this element tree.
This function returns a new instance of the class DOMNodeList of all matched elements.
(no version information, might be only in CVS)
DOMElement->getElementsByTagNameNS() -- Get elements by namespaceURI and localName
This function fetch all the descendant elements with a given
localName and namespaceURI.
namespaceURIThe namespace URI.
localNameThe local name. Use * to return all elements within the element tree.
This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.
(no version information, might be only in CVS)
DOMElement->hasAttribute() -- Checks to see if attribute exists
Indicates whether attribute named name
exists as a member of the element.
| DOMElement->hasAttributeNS() |
| DOMElement->getAttribute() |
| DOMElement->setAttribute() |
| DOMElement->removeAttribute() |
(no version information, might be only in CVS)
DOMElement->hasAttributeNS() -- Checks to see if attribute exists
Indicates whether attribute in namespace namespaceURI
named localName exists as a member of the element.
| DOMElement->hasAttribute() |
| DOMElement->getAttributeNS() |
| DOMElement->setAttributeNS() |
| DOMElement->removeAttributeNS() |
Removes attribute named name from the element.
(no version information, might be only in CVS)
DOMElement->removeAttributeNode() -- Removes attribute
Removes attribute oldnode from the element.
Raised if the node is readonly.
Raised if oldnode is not an attribute of the element.
Removes attribute is namespace namespaceURI
named localName from the element.
Sets an attribute with name name to the given
value. If the attribute does not exist, it will be created.
(no version information, might be only in CVS)
DOMElement->setAttributeNode() -- Adds new attribute node to element
Adds new attribute node attr to element.
(no version information, might be only in CVS)
DOMElement->setAttributeNodeNS() -- Adds new attribute node to element
Adds new attribute node attr to element.
| DOMElement->hasAttributeNS() |
| DOMElement->getAttributeNodeNS() |
| DOMElement->removeAttributeNode() |
Sets an attribute with namespace namespaceURI and
name name to the given value. If the attribute
does not exist, it will be created.
namespaceURIThe namespace URI.
qualifiedNameThe qualified name of the attribute, as prefix:tagname.
valueThe value of the attribute.
Raised if the node is readonly.
Raised if qualifiedName is a malformed qualified
name, or if qualifiedName has a prefix and
namespaceURI is NULL.
(no version information, might be only in CVS)
DOMElement->setIdAttribute() -- Declares the attribute specified by name to be of type ID
Declares the attribute name to be of type ID.
nameThe name of the attribute.
isId
Set it to TRUE if you want name to be of type
ID, FALSE otherwise.
Raised if the node is readonly.
Raised if name is not an attribute of this element.
| DOMDocument->getElementById() |
| DOMElement->setIdAttributeNode() |
| DOMElement->setIdAttributeNS() |
(no version information, might be only in CVS)
DOMElement->setIdAttributeNode() -- Declares the attribute specified by node to be of type ID
Declares the attribute specified by attr to be of
type ID.
attrThe attribute node.
isId
Set it to TRUE if you want name to be of type
ID, FALSE otherwise.
Raised if the node is readonly.
Raised if name is not an attribute of this element.
(no version information, might be only in CVS)
DOMElement->setIdAttributeNS() -- Declares the attribute specified by local name and namespace URI to be of type ID
Declares the attribute specified by localName and
namespaceURI to be of type ID.
namespaceURIThe namespace URI of the attribute.
localNameThe local name of the attribute, as prefix:tagname.
isId
Set it to TRUE if you want name to be of type
ID, FALSE otherwise.
Raised if the node is readonly.
Raised if name is not an attribute of this element.
(no version information, might be only in CVS)
DOMEntityReference->__construct() -- Creates a new DOMEntityReference objectCreates a new DOMEntityReference object.
Example 1. Creating a new DOMEntityReference
|
(no version information, might be only in CVS)
DOMImplementation->__construct() -- Creates a new DOMImplementation objectCreates a new DOMImplementation object.
(no version information, might be only in CVS)
DOMImplementation->createDocument() -- Creates a DOMDocument object of the specified type with its document elementCreates a DOMDocument object of the specified type with its document element.
namespaceURIThe namespace URI of the document element to create.
qualifiedNameThe qualified name of the document element to create.
doctypeThe type of document to create or NULL.
A new DOMDocument object. If
namespaceURI, qualifiedName,
and doctype are null, the returned
DOMDocument is empty with no document element
Raised if doctype has already been used with a
different document or was created from a different implementation.
Raised if there is an error with the namespace, as determined by
namespaceURI and qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->createDocumentType() -- Creates an empty DOMDocumentType objectCreates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.
qualifiedNameThe qualified name of the document type to create.
publicIdThe external subset public identifier.
systemIdThe external subset system identifier.
Example 1. Creating a document with an attached DTD
The above example will output:
|
Raised if there is an error with the namespace, as determined by
qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->hasFeature() -- Test if the DOM implementation implements a specific feature
Test if the DOM implementation implements a specific
feature.
You can find a list of all features in the Conformance section of the DOM specification.
featureThe feature to test.
version
The version number of the feature to test. In
level 2, this can be either 2.0 or
1.0.
Example 1. Testing your DOM Implementation
|
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItem() -- Retrieves a node specified by nameRetrieves a node specified by its nodeName.
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItemNS() -- Retrieves a node specified by local name and namespace URI
Retrieves a node specified by localName and
namespaceURI.
namespaceURIThe namespace URI of the node to retrieve.
localNameThe local name of the node to retrieve.
A node (of any type) with the specified local name and namespace URI, or NULL if no node is found.
(no version information, might be only in CVS)
DOMNamedNodeMap->item() -- Retrieves a node specified by index
Retrieves a node specified by index within the
DOMNamedNodeMap object.
The node at the indexth position in the map, or NULL
if that is not a valid index (greater than or equal to the number of nodes
in this map).
(no version information, might be only in CVS)
DOMNode->appendChild() -- Adds new child at the end of the childrenThis functions appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument->createElement(), DOMDocument->createTextNode() etc. or simply by using any other node.
Raised if this node is readonly or if the previous parent of the node being inserted is readonly.
Raised if this node is of a type that does not allow children of the
type of the newnode node, or if the node to
append is one of this node's ancestors or this node itself.
Raised if newnode was created from a different
document than the one that created this node.
deepIndicates whether to copy all descendant nodes. This parameter is defaulted to FALSE.
(no version information, might be only in CVS)
DOMNode->hasAttributes() -- Checks if node has attributesThis method checks if the node has attributes. The tested node have to be an XML_ELEMENT_NODE.
(no version information, might be only in CVS)
DOMNode->hasChildNodes() -- Checks if node has childrenThis function checks if the node has children.
(no version information, might be only in CVS)
DOMNode->insertBefore() -- Adds a new child before a reference nodeThis function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.
newnodeThe new node.
refnode
The reference node. If not supplied, newnode is
appended to the children.
Raised if this node is readonly or if the previous parent of the node being inserted is readonly.
Raised if this node is of a type that does not allow children of the
type of the newnode node, or if the node to
append is one of this node's ancestors or this node itself.
Raised if newnode was created from a different
document than the one that created this node.
Raised if refnode is not a child of this node.
(no version information, might be only in CVS)
DOMNode->isDefaultNamespace() -- Checks if the specified namespaceURI is the default namespace or not
Tells whether namespaceURI is the default namespace.
(no version information, might be only in CVS)
DOMNode->isSameNode() -- Indicates if two nodes are the same nodeThis function indicates if two nodes are the same node. The comparison is not based on content
(no version information, might be only in CVS)
DOMNode->isSupported() -- Checks if feature is supported for specified version
Checks if the asked feature is supported for the
specified version.
featureThe feature to test. See the example of DOMImplementation->hasFeature() for a list of features.
version
The version number of the feature to test.
(no version information, might be only in CVS)
DOMNode->lookupNamespaceURI() -- Gets the namespace URI of the node based on the prefix
Gets the namespace URI of the node based on the
prefix.
(no version information, might be only in CVS)
DOMNode->lookupPrefix() -- Gets the namespace prefix of the node based on the namespace URIGets the namespace prefix of the node based on the namespace URI.
(no version information, might be only in CVS)
DOMNode->removeChild() -- Removes child from list of childrenThis functions removes a child from a list of children.
Raised if this node is readonly.
Raised if oldnode is not a child of this node.
The following example will delete the chapter element of our XML document.
Example 1. Removing a child
The above example will output:
|
This function replaces the child oldnode
with the passed new node. If the new node is already a child it
will not be added a second time. If the replacement succeeds the
old node is returned.
newnodeThe new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument->importNode().
oldnodeThe old node.
Raised if this node is readonly or if the previous parent of the node being inserted is readonly.
Raised if this node is of a type that does not allow children of the
type of the newnode node, or if the node to
put in is one of this node's ancestors or this node itself.
Raised if newnode was created from a different
document than the one that created this node.
Raised if oldnode is not a child of this node.
(no version information, might be only in CVS)
DOMNodelist->item() -- Retrieves a node specified by index
Retrieves a node specified by index within the
DOMNodeList object.
Tip: If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.
The node at the indexth position in the
DOMNodeList, or NULL if that is not a valid
index.
Example 1. Traversing all the entries of the table
Alternatively, you can use foreach, which is a much more convenient way:
The above example will output:
|
(no version information, might be only in CVS)
DOMProcessingInstruction->__construct() -- Creates a new DOMProcessingInstruction objectCreates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument->createProcessingInstruction().
nameThe tag name of the processing instruction.
valueThe value of the processing instruction.
Example 1. Creating a new DOMProcessingInstruction
The above example will output:
|
(no version information, might be only in CVS)
DOMText->__construct() -- Creates a new DOMText object(no version information, might be only in CVS)
DOMText->isWhitespaceInElementContent() -- Indicates whether this text node contains whitespaceIndicates whether this text node contains whitespace. The text node is determined to contain whitespace in element content during the load of the document.
(no version information, might be only in CVS)
DOMText->splitText() -- Breaks this node into two nodes at the specified offset
Breaks this node into two nodes at the specified offset,
keeping both in the tree as siblings.
After being split, this node will contain all the content up to the
offset. If the original node had a parent node,
the new node is inserted as the next sibling of the original node.
When the offset is equal to the length of this node,
the new node has no data.
The new node of the same type, which contains all the content at and after the
offset.
(no version information, might be only in CVS)
DOMXPath->__construct() -- Creates a new DOMXPath object(no version information, might be only in CVS)
DOMXPath->evaluate() -- Evaluates the given XPath expression and returns a typed result if possible.
Executes the given XPath expression and returns
a typed result if possible.
expressionThe XPath expression to execute.
contextnode
The optional contextnode can be specified for
doing relative XPath queries. By default, the queries are relative to
the root element.
Returns a typed result if possible or a DOMNodeList
containing all nodes matching the given XPath expression.
Example 1. Getting the count of all the english books
The above example will output:
|
(no version information, might be only in CVS)
DOMXPath->query() -- Evaluates the given XPath expression
Executes the given XPath expression.
expressionThe XPath expression to execute.
contextnode
The optional contextnode can be specified for
doing relative XPath queries. By default, the queries are relative to
the root element.
Returns a DOMNodeList containing all nodes matching
the given XPath expression. Any expression which do
not return nodes will return an empty DOMNodeList.
Example 1. Getting all the english books
The above example will output:
We can also use the
|
(no version information, might be only in CVS)
DOMXPath->registerNamespace() -- Registers the namespace with the DOMXPath object
Registers the namespaceURI and
prefix with the DOMXPath object.
This function takes the node node of class
SimpleXML and makes it into a
DOMElement node. This new object can then be used
as a native DOMElement node.
Example 1. Import SimpleXML into DOM with dom_import_simplexml()
|
The DOM XML extension has been overhauled in PHP 4.3.0 to better comply with the DOM standard. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.
The extension allows you to operate on an XML document with the DOM API. It also provides a function domxml_xmltree() to turn the complete XML document into a tree of PHP objects. Currently, this tree should be considered read-only - you can modify it, but this would not make any sense since DomDocument_dump_mem() cannot be applied to it. Therefore, if you want to read an XML file and write a modified version, use DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. and finally the DomDocument_dump_mem() function.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.0.0.
This extension makes use of the GNOME XML library. Download and install this library. You will need at least libxml-2.4.14. To use DOM XSLT features you can use the libxslt library and EXSLT enhancements from http://www.exslt.org/. Download and install these libraries if you plan to use (enhanced) XSLT features. You will need at least libxslt-1.0.18.
This PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/domxml.
In PHP 4 this PECL extensions
source can be found in the ext/ directory within the
PHP source or at the PECL link above.
This extension is only available if PHP was configured with
--with-dom[=DIR]. Add
--with-dom-xslt[=DIR] to include DOM
XSLT support. DIR is the libxslt install directory. Add
--with-dom-exslt[=DIR] to include DOM
EXSLT support, where DIR is the libexslt install directory.
Windows users will enable php_domxml.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/ Also, there is one additional DLL that must be made available to your system's PATH in order for this extension to work. In PHP 4 this is in the dlls/ directory. It's name: For PHP <= 4.2.0, it's libxml2.dll. For PHP >= 4.3.0, it's iconv.dll. And as of PHP 5.0.0, iconv is compiled into your Windows PHP binaries by default so no extra DLL is needed.
There are quite a few functions that do not fit into the DOM standard and should no longer be used. These functions are listed in the following table. The function DomNode_append_child() has changed its behaviour. It now adds a child and not a sibling. If this breaks your application, use the non-DOM function DomNode_append_sibling().
Table 1. Deprecated functions and their replacements
| Old function | New function |
|---|---|
| xmldoc | domxml_open_mem() |
| xmldocfile | domxml_open_file() |
| domxml_new_xmldoc | domxml_new_doc() |
| domxml_dump_mem | DomDocument_dump_mem() |
| domxml_dump_mem_file | DomDocument_dump_file() |
| DomDocument_dump_mem_file | DomDocument_dump_file() |
| DomDocument_add_root | DomDocument_create_element() followed by DomNode_append_child() |
| DomDocument_dtd | DomDocument_doctype() |
| DomDocument_root | DomDocument_document_element() |
| DomDocument_children | DomNode_child_nodes() |
| DomDocument_imported_node | No replacement. |
| DomNode_add_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child(). |
| DomNode_children | DomNode_child_nodes() |
| DomNode_parent | DomNode_parent_node() |
| DomNode_new_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child(). |
| DomNode_set_content | Create a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child(). |
| DomNode_get_content | Content is just a text node and can be accessed with DomNode_child_nodes(). |
| DomNode_set_content | Content is just a text node and can be added with DomNode_append_child(). |
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Table 2. XML constants
| Constant | Value | Description |
|---|---|---|
| XML_ELEMENT_NODE (integer) | 1 | Node is an element |
| XML_ATTRIBUTE_NODE (integer) | 2 | Node is an attribute |
| XML_TEXT_NODE (integer) | 3 | Node is a piece of text |
| XML_CDATA_SECTION_NODE (integer) | 4 | |
| XML_ENTITY_REF_NODE (integer) | 5 | |
| XML_ENTITY_NODE (integer) | 6 | Node is an entity like |
| XML_PI_NODE (integer) | 7 | Node is a processing instruction |
| XML_COMMENT_NODE (integer) | 8 | Node is a comment |
| XML_DOCUMENT_NODE (integer) | 9 | Node is a document |
| XML_DOCUMENT_TYPE_NODE (integer) | 10 | |
| XML_DOCUMENT_FRAG_NODE (integer) | 11 | |
| XML_NOTATION_NODE (integer) | 12 | |
| XML_GLOBAL_NAMESPACE (integer) | 1 | |
| XML_LOCAL_NAMESPACE (integer) | 2 | |
| XML_HTML_DOCUMENT_NODE (integer) | ||
| XML_DTD_NODE (integer) | ||
| XML_ELEMENT_DECL_NODE (integer) | ||
| XML_ATTRIBUTE_DECL_NODE (integer) | ||
| XML_ENTITY_DECL_NODE (integer) | ||
| XML_NAMESPACE_DECL_NODE (integer) | ||
| XML_ATTRIBUTE_CDATA (integer) | ||
| XML_ATTRIBUTE_ID (integer) | ||
| XML_ATTRIBUTE_IDREF (integer) | ||
| XML_ATTRIBUTE_IDREFS (integer) | ||
| XML_ATTRIBUTE_ENTITY (integer) | ||
| XML_ATTRIBUTE_NMTOKEN (integer) | ||
| XML_ATTRIBUTE_NMTOKENS (integer) | ||
| XML_ATTRIBUTE_ENUMERATION (integer) | ||
| XML_ATTRIBUTE_NOTATION (integer) | ||
| XPATH_UNDEFINED (integer) | ||
| XPATH_NODESET (integer) | ||
| XPATH_BOOLEAN (integer) | ||
| XPATH_NUMBER (integer) | ||
| XPATH_STRING (integer) | ||
| XPATH_POINT (integer) | ||
| XPATH_RANGE (integer) | ||
| XPATH_LOCATIONSET (integer) | ||
| XPATH_USERS (integer) | ||
| XPATH_NUMBER (integer) |
The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module. Though the API is object-oriented, there are many functions which can be called in a non-object-oriented way by passing the object to operate on as the first argument. These functions are mainly to retain compatibility to older versions of the extension, and should not be used when creating new scripts.
This API differs from the official DOM API in two ways. First, all class attributes are implemented as functions with the same name. Secondly, the function names follow the PHP naming convention. This means that a DOM function lastChild() will be written as last_child().
This module defines a number of classes, which are listed - including their method - in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.
Table 3. List of classes
| Class name | Parent classes |
|---|---|
| DomAttribute | DomNode |
| DomCData | DomNode |
| DomComment | DomCData : DomNode |
| DomDocument | DomNode |
| DomDocumentType | DomNode |
| DomElement | DomNode |
| DomEntity | DomNode |
| DomEntityReference | DomNode |
| DomProcessingInstruction | DomNode |
| DomText | DomCData : DomNode |
| Parser | Currently still called DomParser |
| XPathContext |
Table 4. DomDocument class (DomDocument : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| doctype | DomDocument_doctype() | |
| document_element | DomDocument_document_element() | |
| create_element | DomDocument_create_element() | |
| create_text_node | DomDocument_create_text_node() | |
| create_comment | DomDocument_create_comment() | |
| create_cdata_section | DomDocument_create_cdata_section() | |
| create_processing_instruction | DomDocument_create_processing_instruction() | |
| create_attribute | DomDocument_create_attribute() | |
| create_entity_reference | DomDocument_create_entity_reference() | |
| get_elements_by_tagname | DomDocument_get_elements_by_tagname() | |
| get_element_by_id | DomDocument_get_element_by_id() | |
| dump_mem | DomDocument_dump_mem() | not DOM standard |
| dump_file | DomDocument_dump_file() | not DOM standard |
| html_dump_mem | DomDocument_html_dump_mem() | not DOM standard |
| xpath_init | xpath_init | not DOM standard |
| xpath_new_context | xpath_new_context | not DOM standard |
| xptr_new_context | xptr_new_context | not DOM standard |
Table 5. DomElement class (DomElement : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| tagname | DomElement_tagname() | |
| get_attribute | DomElement_get_attribute() | |
| set_attribute | DomElement_set_attribute() | |
| remove_attribute | DomElement_remove_attribute() | |
| get_attribute_node | DomElement_get_attribute_node() | |
| set_attribute_node | DomElement_set_attribute_node() | |
| get_elements_by_tagname | DomElement_get_elements_by_tagname() | |
| has_attribute | DomElement_has_attribute() |
Table 6. DomNode class
| Method name | Remark |
|---|---|
| DomNode_node_name() | |
| DomNode_node_value() | |
| DomNode_node_type() | |
| DomNode_last_child() | |
| DomNode_first_child() | |
| DomNode_child_nodes() | |
| DomNode_previous_sibling() | |
| DomNode_next_sibling() | |
| DomNode_parent_node() | |
| DomNode_owner_document() | |
| DomNode_insert_before() | |
| DomNode_append_child() | |
| DomNode_append_sibling() | Not in DOM standard. This function emulates the former behaviour of DomNode_append_child(). |
| DomNode_remove_child() | |
| DomNode_has_child_nodes() | |
| DomNode_has_attributes() | |
| DomNode_clone_node() | |
| DomNode_attributes() | |
| DomNode_unlink_node() | Not in DOM standard |
| DomNode_replace_node() | Not in DOM standard |
| DomNode_set_content() | Not in DOM standard, deprecated |
| DomNode_get_content() | Not in DOM standard, deprecated |
| DomNode_dump_node() | Not in DOM standard |
| DomNode_is_blank_node() | Not in DOM standard |
Table 7. DomAttribute class (DomAttribute : DomNode)
| Method name | Remark | |
|---|---|---|
| name | DomAttribute_name() | |
| value | DomAttribute_value() | |
| specified | DomAttribute_specified() |
Table 8. DomProcessingInstruction class (DomProcessingInstruction : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| target | DomProcessingInstruction_target() | |
| data | DomProcessingInstruction_data() |
Table 10. XPathContext class
| Method name | Function name | Remark |
|---|---|---|
| eval | XPathContext_eval() | |
| eval_expression | XPathContext_eval_expression() | |
| register_ns | XPathContext_register_ns() |
Table 11. DomDocumentType class (DomDocumentType : DomNode)
| Method name | Function name | Remark |
|---|---|---|
| name | DomDocumentType_name() | |
| entities | DomDocumentType_entities() | |
| notations | DomDocumentType_notations() | |
| public_id | DomDocumentType_public_id() | |
| system_id | DomDocumentType_system_id() | |
| internal_subset | DomDocumentType_internal_subset() |
The classes DomDtd is derived from DomNode. DomComment is derived from DomCData.
Many examples in this reference require an XML string. Instead of repeating this string in every example, it will be put into a file which will be included by each example. This include file is shown in the following example section. Alternatively, you could create an XML document and read it with DomDocument_open_file().
Example 1. Include file example.inc with XML string
|
(no version information, might be only in CVS)
DomAttribute->set_value -- Sets the value of an attributeThis function sets the value of an attribute.
(no version information, might be only in CVS)
DomAttribute->specified -- Checks if attribute is specifiedChecks if the attribute was explicitly given a value in the original document.
Note: This method is not implemented yet.
This function returns the value of the attribute.
Example 1. Getting all the attributes of a node
The above example will output:
|
(no version information, might be only in CVS)
DomDocument->add_root -- Adds a root node [deprecated]Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.
This function returns a new instance of class DomAttribute. The name of the attribute is the value of the first parameter. The value of the attribute is the value of the second parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_cdata_section -- Create new cdata nodeThis function returns a new instance of class DomCData. The content of the cdata is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_comment -- Create new comment nodeThis function returns a new instance of class DomComment. The content of the comment is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_element_ns -- Create new element node with an associated namespace
This function returns a new instance of class
DomElement. The tag name of the element is the
value of the passed parameter name. The URI of the
namespace is the value of the passed parameter uri.
If there is already a namespace declaration with the same uri in the root-node
of the document, the prefix of this is taken, otherwise it will take the one provided
in the optional parameter prefix or generate a random one.
This node will not show up in the document unless it
is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domdocument_create_element_ns(), domnode_add_namespace(), domnode_set_namespace(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_element -- Create new element nodeThis function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_entity_reference -- Create an entity referenceThis function returns a new instance of class DomEntityReference. The content of the entity reference is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute(), and domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_processing_instruction -- Creates new PI nodeThis function returns a new instance of class DomCData. The content of the pi is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference(), and domnode_insert_before().
This function returns a new instance of class DomText. The content of the text is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. domnode_append_child().
The return value is FALSE if an error occurred.
See also domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().
This function returns an object of class DomDocumentType. In versions of PHP before 4.3 this has been the class Dtd, but the DOM Standard does not know such a class.
See also the methods of class DomDocumentType.
(no version information, might be only in CVS)
DomDocument->document_element -- Returns root element nodeThis function returns the root element node of a document.
The following example returns just the element with name CHAPTER and prints it. The other node -- the comment -- is not returned.
Example 1. Retrieving root element
The above example will output:
|
(no version information, might be only in CVS)
DomDocument->dump_file -- Dumps the internal XML tree back into a file
Creates an XML document from the dom representation. This function
usually is called after building a new dom document from scratch
as in the example below. The
format specifies whether the output should be
neatly formatted, or not. The first parameter specifies the name of the
filename and the second parameter, whether it should be compressed or not.
Example 1. Creating a simple HTML document header
|
See also domdocument_dump_mem(), and domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->dump_mem -- Dumps the internal XML tree back into a string
Creates an XML document from the dom representation. This function
usually is called after building a new dom document from scratch
as in the example below. The
format specifies whether the output should be
neatly formatted, or not.
Example 1. Creating a simple HTML document header
|
Note: The first parameter was added in PHP 4.3.0.
See also domdocument_dump_file(), and domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->get_element_by_id -- Searches for an element with a certain idThis function is similar to domdocument_get_elements_by_tagname() but searches for an element with a given id. According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID, though the current implementation simply does an xpath search for "//*[@ID = '%s']". This does not comply to the DOM standard which requires to return null if it is not known which attribute is of type id. This behaviour is likely to be fixed, so do not rely on the current behaviour.
(no version information, might be only in CVS)
DomDocument->get_elements_by_tagname -- Returns array with nodes with given tagname in document or empty array, if not found
See also domdocument_add_root()
(no version information, might be only in CVS)
DomDocument->html_dump_mem -- Dumps the internal XML tree back into a string as HTMLCreates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.
Example 1. Creating a simple HTML document header
The above example will output:
|
See also domdocument_dump_file(), and domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->xinclude -- Substitutes XIncludes in a DomDocument ObjectThis function substitutes XIncludes in a DomDocument object.
Example 1. Substituting Xincludes
The above example will output:
If include.xml doesn't exist, you'll see:
|
(no version information, might be only in CVS)
DomDocumentType->entities() -- Returns list of entities
| Warning |
This function is currently not documented; only the argument list is available. |
(no version information, might be only in CVS)
DomDocumentType->internal_subset() -- Returns internal subset
| Warning |
This function is currently not documented; only the argument list is available. |
(no version information, might be only in CVS)
DomDocumentType->name() -- Returns name of document typeThis function returns the name of the document type.
(no version information, might be only in CVS)
DomDocumentType->notations() -- Returns list of notations
| Warning |
This function is currently not documented; only the argument list is available. |
(no version information, might be only in CVS)
DomDocumentType->public_id() -- Returns public id of document typeThis function returns the public id of the document type.
(no version information, might be only in CVS)
DomDocumentType->system_id() -- Returns the system id of document typeReturns the system id of the document type.
(no version information, might be only in CVS)
DomElement->get_attribute_node() -- Returns the node of the given attributeReturns the node of the given attribute in the current element.
Returns the node of the attribute as a DomAttribute
or FALSE if no attribute with the given name is
found.
Example 1. Getting an attribute node
|
(no version information, might be only in CVS)
DomElement->get_attribute() -- Returns the value of the given attributeReturns the value of the given attribute in the current element.
Since PHP 4.3, if no attribute with given name is
found, an empty string is returned.
Returns the name of the attribute as a string or an empty string if no
attribute with the given name is found.
(no version information, might be only in CVS)
DomElement->get_elements_by_tagname() -- Gets elements by tagname
Gets all the sub elements with the specific name
within the current element.
(no version information, might be only in CVS)
DomElement->has_attribute() -- Checks to see if an attribute exists in the current node
This functions checks to see if an attribute named
name exists in the current node.
Example 1. Testing the existence of an attribute
|
Removes an attribute from the current DomElement node.
(no version information, might be only in CVS)
DomElement->set_attribute_node() -- Adds new attribute
| Warning |
This function is currently not documented; only the argument list is available. |
(no version information, might be only in CVS)
DomElement->set_attribute() -- Sets the value of an attribute
Sets an attribute with name name to the given
value.
nameThe name of the attribute. If this attribute doesn't exist, it will be created.
valueThe value of the attribute.
Returns the old DomAttribute node, or the new one if you are creating the attribute for the first time.
(no version information, might be only in CVS)
DomElement->tagname() -- Returns the name of the current elementReturns the name of the current node. Calling this function is the same as accessing the tagname property, or calling DomNode->node_name on the current node.
(no version information, might be only in CVS)
DomNode->add_namespace -- Adds a namespace declaration to a nodeThis method adds a namespace declaration to a node.
Note: This method is not part of the DOM specification.
You can set the namespace URI and prefix of a DOMElement or a DOMAttr at creation time by using DOMDocument->createElementNS() or DOMDocument->createAttributeNS().
Note: Remember the an attribute does not inherit its namespace from the element it is attached to.
(no version information, might be only in CVS)
DomNode->append_child -- Adds a new child at the end of the childrenThis functions appends a child to an existing list of children or creates a new list of children.
newnodeThe node being appended. It can be created with e.g. DomDocument->create_element, DomDocument->create_text_node etc. or simply by using any other node.
Note: You can not append a DOMAttribute using this method. Use DomElement->set_attribute() instead.
| Version | Description |
|---|---|
| 4.3.0 | You are not allowed anymore to insert a node from another document. |
| 4.3.0 | Prior to PHP 4.3.0, the new child is duplicated before being appended. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the appended child. If you plan to do further modifications on the appended child you must use the returned node. |
| 4.3.0 and 4.3.1 |
The new child newnode is first unlinked from
its existing context, if it's already a child of DomNode. Therefore
the newnode is moved and not copies anymore.
This is the behaviour according to the W3C specifications. If you
need the old behaviour, use DomNode->clone_node before appending.
|
| 4.3.2 |
The new child newnode is first unlinked from
its existing context, if it's already in the tree. Same rules apply.
|
The following example adds a new element node to a fresh document and sets the attribute align to left.
The above example could also be written as the following:
A more complex example is the one below. It first searches for a certain element, duplicates it including its children and adds it as a sibling. Finally a new attribute is added to one of the children of the new sibling and the whole document is dumped.
Example 3. Adding a child
|
The above example could also be done with DomNode->insert_before instead of DomNode->append_child.
This functions appends a sibling to an existing node. The child can be created with e.g. domdocument_create_element(), domdocument_create_text() etc. or simply by using any other node.
Before a new sibling is added it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the added sibling. If you plan to do further modifications on the added sibling you must use the returned node.
This function has been added to provide the behaviour of domnode_append_child() as it works till PHP 4.2.
See also domnode_append_before().
This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.
(PHP >= 4.3 only) If no attributes are found, NULL is returned.
Returns all children of the node.
See also domnode_next_sibling(), and domnode_previous_sibling().
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
See also domdocument_dump_mem().
Returns the first child of the node.
(PHP >= 4.3 only) If no first child is found, NULL is returned.
See also domnode_last_child(), and domnode_next_sibling(), domnode_previous_sibling().
This function returns the content of the actual node.
Example 1. Getting a content
|
(no version information, might be only in CVS)
DomNode->has_attributes -- Checks if node has attributesThis function checks if the node has attributes.
See also domnode_has_child_nodes().
(no version information, might be only in CVS)
DomNode->has_child_nodes -- Checks if node has childrenThis function checks if the node has children.
See also domnode_child_nodes().
This function inserts the new node newnode right
before the node refnode. The return value is the
inserted node. If you plan to do further modifications on the appended
child you must use the returned node.
(PHP >= 4.3 only) If newnode already is part of a
document, it will be first unlinked from its existing context. If
refnode is NULL, then newnode
will be inserted at the end of the list of children.
domnode_insert_before() is very similar to domnode_append_child() as the following example shows which does the same as the example at domnode_append_child().
Example 1. Adding a child
|
See also domnode_append_child().
| Warning |
This function is currently not documented; only the argument list is available. |
Returns the last child of the node.
(PHP >= 4.3 only) If no last child is found, NULL is returned.
See also domnode_first_child(), and domnode_next_sibling(), domnode_previous_sibling().
(no version information, might be only in CVS)
DomNode->next_sibling -- Returns the next sibling of nodeThis function returns the next sibling of the current node. If there is no next sibling it returns FALSE (< 4.3) or null (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.
Example 1. Iterate over children
|
See also domnode_previous_sibling().
Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.
Table 1. Meaning of value
| Type | Meaning |
|---|---|
| DomAttribute | value of attribute |
| DomAttribute | |
| DomCDataSection | #cdata-section |
| DomComment | #comment |
| DomDocument | #document |
| DomDocumentType | document type name |
| DomElement | tag name |
| DomEntity | name of entity |
| DomEntityReference | name of entity reference |
| DomNotation | notation name |
| DomProcessingInstruction | target |
| DomText | #text |
Returns the type of the node. All possible types are listed in the table in the introduction.
Example 1.
The above example will output:
|
Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.
Table 1. Meaning of value
| Type | Meaning |
|---|---|
| DomAttribute | value of attribute |
| DomAttribute | |
| DomCDataSection | content |
| DomComment | content of comment |
| DomDocument | null |
| DomDocumentType | null |
| DomElement | null |
| DomEntity | null |
| DomEntityReference | null |
| DomNotation | null |
| DomProcessingInstruction | entire content without target |
| DomText | content of text |
(no version information, might be only in CVS)
DomNode->owner_document -- Returns the document this node belongs toThis function returns the document the current node belongs to.
The following example will create two identical lists of children.
See also domnode_insert_before().
(no version information, might be only in CVS)
DomNode->parent_node -- Returns the parent of the nodeThis function returns the parent node.
(PHP >= 4.3 only) If no parent is found, NULL is returned.
The following example will show two identical lists of children.
(no version information, might be only in CVS)
DomNode->previous_sibling -- Returns the previous sibling of nodeThis function returns the previous sibling of the current node. If there is no previous sibling it returns FALSE (< 4.3) or NULL (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.
See also domnode_next_sibling().
(no version information, might be only in CVS)
DomNode->remove_child -- Removes child from list of childrenThis functions removes a child from a list of children. If child cannot be removed or is not a child the function will return FALSE. If the child could be removed the functions returns the old child.
Example 1. Removing a child
|
See also domnode_append_child().
(PHP 4.2) This function replaces the child oldnode
with the passed new node. If the new node is already a child it
will not be added a second time. If the old node cannot be found
the function returns FALSE. If the replacement succeeds the old node
is returned.
(PHP 4.3) This function replaces the child oldnode
with the passed newnode, even if the new node already
is a child of the DomNode. If newnode was already
inserted in the document it is first unlinked from its existing context.
If the old node cannot be found the function returns FALSE. If the replacement
succeeds the old node is returned. (This behaviour is according to the W3C specs).
See also domnode_append_child()
(PHP 4.2) This function replaces an existing node with the passed
new node. Before the replacement
newnode is copied if it has a parent to
make sure a node which is
already in the document will not be inserted a second time. This
behaviour enforces doing all modifications on the node before the
replacement or to refetch the inserted node afterwards with functions like
domnode_first_child(),
domnode_child_nodes() etc..
(PHP 4.3) This function replaces an existing node with the passed new node. It is not
copied anymore. If newnode was already inserted in the document
it is first unlinked from its existing context. If the replacement succeeds the old
node is returned.
See also domnode_append_child()
| Warning |
This function is currently not documented; only the argument list is available. |
Sets the namespace of a node to uri.
If there is already a namespace declaration with the same uri in one of the parent nodes
of the node, the prefix of this is taken, otherwise it will take the one provided
in the optional parameter prefix or generate a random one.
See also domdocument_create_element_ns(), and domnode_add_namespace()
| Warning |
This function is currently not documented; only the argument list is available. |
(no version information, might be only in CVS)
DomProcessingInstruction->data -- Returns the data of ProcessingInstruction nodeThis method gets the data of the ProcessingInstruction node.
(no version information, might be only in CVS)
DomProcessingInstruction->target -- Returns the target of a ProcessingInstruction nodeThis method gets the target of the ProcessingInstruction node.
(no version information, might be only in CVS)
DomXsltStylesheet->process() -- Applies the XSLT-Transformation on a DomDocument ObjectApplies an XSLT Transformation on the given DomDocument object.
xml_docThe XML document being transformed, as a DomDocument object.
xslt_paramsAn associative array that takes pairs of parameter names and values.
is_xpath_param
If set to FALSE the values of the xslt_params
will be quoted. This is the default behavior. It allows you to pass
the values as PHP strings.
Note: If your strings contains both single and double quotes, you must take care of quoting all the values by yourself and set this parameter to TRUE.
profile_filenameSet this to the path of a filename, if you want profiling information.
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_file() -- Dumps the result from a XSLT-Transformation into a fileSince DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.
This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction on how to use it.
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_mem() -- Dumps the result from a XSLT-Transformation back into a stringSince DomXsltStylesheet->process() always returns a well-formed XML DomDocument, no matter what output method was declared in <xsl:output> and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.
This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction on how to use it.
Creates a new Dom document from scratch and returns it.
The function parses the XML document in the given file.
filenameThe path to the XML file. The file is accessed in read-only mode.
modeThis optional parameter can be used to change the behavior of this function.
You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.
error
If used, it will contain the error messages.
error must be passed in by reference.
The function parses the XML document in the given string.
strThe contents of the XML file.
modeThis optional parameter can be used to change the behavior of this function.
You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.
error
If used, it will contain the error messages.
error must be passed in by reference.
The function parses the XML document in str and
returns a tree PHP objects as the parsed document.
This function is isolated from the other functions, which means you cannot access the tree with any of the other functions. Modifying it, for example by adding nodes, makes no sense since there is currently no way to dump it as an XML file.
However this function may be valuable if you want to read a file and investigate the content.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_doc -- Creates a DomXsltStylesheet Object from a DomDocument ObjectCreates a DomXsltStylesheet object from the given XSL document.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_file -- Creates a DomXsltStylesheet Object from an XSL document in a fileCreates a DomXsltStylesheet object from the given XSL file.
Call XSLTProcessor::importStylesheet with DOMDocument::load($xsl_file) as parameter.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet -- Creates a DomXsltStylesheet object from an XSL document in a stringCreates a DomXsltStylesheet object from the given XSL buffer.
Call XSLTProcessor::importStylesheet with DOMDocument::loadXML($xsl_buf) as parameter.
(PHP 4 >= 4.0.4, PECL)
xpath_eval_expression -- Evaluates the XPath Location Path in the given string
Example 1. xpath_eval_expression() Example
The above example will output:
|
See also xpath_eval().
The optional contextnode can be specified for doing relative XPath queries.
See also xpath_new_context().
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
Enchant is the PHP binding for the Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."
Enchat supports the following backends:
Aspell/Pspell (intends to replace Ispell)
Ispell (old as sin, could be interpreted as a defacto standard)
MySpell/Hunspell (an OOo projects, also used by Mozilla)
Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")
Hspell (Hebrew)
AppleSpell (Mac OSX)
This version uses the functions of the Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/enchant.
There are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.
Example 1. Enchant Usage Example
|
Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().
Example 1. List the backends provided by the given broker
The above example will output something similar to:
|
Tells if a dictionary exists or not, using a non-empty tags
Free a broker resource with all its dictionaries.
Returns the last error which occurred in this broker.
(no version information, might be only in CVS)
enchant_broker_list_dicts -- Returns a list of available dictionariesReturns a list of available dictionaries with their details.
Example 1. List all available dictionaries for one broker
The above example will output something similar to:
|
create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)
Example 1. A enchant_broker_request_dict() example Check if a dictionary exists using enchant_broker_dict_exists() and request it.
|
(PECL)
enchant_broker_request_pwl_dict -- creates a dictionary using a PWL file. A PWL file is personal word file one word per line.creates a dictionary using a PWL file. A PWL file is personal word file one word per line.
Declares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.
brokerBroker resource
tagLanguage tag. The special "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.
orderingComma delimited list of provider names
Add a word to personal word list of the given dictionary.
Add a word to the given dictionary. It will be added only for the active spell-checking session.
If the word is correctly spelled return TRUE, otherwise return FALSE
Example 1. A enchant_dict_describe() example Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.
The above example will output something similar to:
|
Returns the last error of the current spelling-session
Tells whether or not a word already exists in the current session.
If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable is provided, fill it with spelling alternatives.
dictDictionary resource
wordThe word to check
suggestionsIf the word is not correctly spelled, this variable will contain an array of suggestions.
Example 1. A enchant_dict_quick_check() example
The above example will output something similar to:
|
Add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.
(PECL)
enchant_dict_suggest -- Will return a list of values if any of those pre-conditions are not met.
Example 1. A enchant_dict_suggest() example
|
These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.
With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.
The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.
The behaviour of these functions is affected by settings in php.ini.
Table 1. Errors and Logging Configuration Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| error_reporting | NULL | PHP_INI_ALL | |
| display_errors | "1" | PHP_INI_ALL | |
| display_startup_errors | "0" | PHP_INI_ALL | Available since PHP 4.0.3. |
| log_errors | "0" | PHP_INI_ALL | |
| log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_errors | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_source | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0. |
| track_errors | "0" | PHP_INI_ALL | |
| html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.2. |
| docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0. |
| docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2. |
| error_prepend_string | NULL | PHP_INI_ALL | |
| error_append_string | NULL | PHP_INI_ALL | |
| error_log | NULL | PHP_INI_ALL | |
| warn_plus_overloading | NULL | PHP_INI?? |
Here's a short explanation of the configuration directives.
error_reporting
integerSet the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.
In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.
Note: Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.
Note: In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.
PHP Constants outside of PHP: Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647.
In PHP 3, the default setting is (E_ERROR | E_WARNING | E_PARSE), meaning the same thing. Note, however, that since constants are not supported in PHP 3's php3.ini, the error_reporting setting there must be numeric; hence, it is 7.
display_errors
booleanThis determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.
Note: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).
Note: Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
display_startup_errors
booleanEven when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.
log_errors
booleanTells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.
Note: You're strongly advised to use error logging in place of error displaying on production web sites.
log_errors_max_len
integerSet the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
ignore_repeated_errors
booleanDo not log repeated messages. Repeated errors must occur in the same file on the same line until ignore_repeated_source is set true.
ignore_repeated_source
booleanIgnore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.
report_memleaks
booleanIf this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list
track_errors
booleanIf enabled, the last error message will always be present in the variable $php_errormsg.
html_errors
booleanTurn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.
docref_root
stringThe new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by '/manual/' you can simply use docref_root=/manual/. Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html. It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"
Most of the time you want the docref_root value to end with a slash '/'. But see the second example above which does not have nor need it.
Note: This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).
docref_ext
stringSee docref_root.
Note: The value of docref_ext must begin with a dot '.'.
error_prepend_string
stringString to output before an error message.
error_append_string
stringString to output after an error message.
error_log
stringName of the file where script errors should be logged. The file should be writable by the web server's user. 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. See also: syslog(). If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI.
warn_plus_overloading
booleanIf 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 (.). This option doesn't exist as of PHP 4.
The constants below are always available as part of the PHP core.
Note: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.
Table 2. Errors and Logging
| Value | Constant | Description | Note |
|---|---|---|---|
| 1 | E_ERROR (integer) | Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. | |
| 2 | E_WARNING (integer) | Run-time warnings (non-fatal errors). Execution of the script is not halted. | |
| 4 | E_PARSE (integer) | Compile-time parse errors. Parse errors should only be generated by the parser. | |
| 8 | E_NOTICE (integer) | Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. | |
| 16 | E_CORE_ERROR (integer) | Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. | since PHP 4 |
| 32 | E_CORE_WARNING (integer) | Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. | since PHP 4 |
| 64 | E_COMPILE_ERROR (integer) | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. | since PHP 4 |
| 128 | E_COMPILE_WARNING (integer) | Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. | since PHP 4 |
| 256 | E_USER_ERROR (integer) | User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4 |
| 512 | E_USER_WARNING (integer) | User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4 |
| 1024 | E_USER_NOTICE (integer) | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4 |
| 2048 | E_STRICT (integer) | Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | since PHP 5 |
| 4096 | E_RECOVERABLE_ERROR (integer) | Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR. | since PHP 5.2.0 |
| 8191 | E_ALL (integer) | All errors and warnings, as supported, except of level E_STRICT in PHP < 6. | 6143 in PHP 5.2.x and 2047 previously |
The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini, however, and that no bitwise operators will be understood within php3.ini.
Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.
Example 1. Using error handling in a script
|
Returns an associative array. The possible returned elements are as follows:
Table 1. Possible returned elements from debug_backtrace()
| Name | Type | Description |
|---|---|---|
| function | string | The current function name. See also __FUNCTION__. |
| line | integer | The current line number. See also __LINE__. |
| file | string | The current file name. See also __FILE__. |
| class | string | The current class name. See also __CLASS__ |
| object | object | The current object. |
| type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned. |
| args | array | If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s). |
Example 1. debug_backtrace() example
Results similar to the following when executing /tmp/b.php:
|
debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.
Example 1. debug_print_backtrace() example
The above example will output something similar to:
|
Returns an associative array describing the last error with keys "type", "message", "file" and "line". Returns NULL if there hasn't been an error yet.
Sends an error message to the web server's error log, a TCP port or to a file.
messageThe error message that should be logged.
message_typeSays where the error should go. The possible message types are as follows:
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. This is the default option.
|
| 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.
|
| 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. This option is only available in PHP 3.
|
| 3 |
message is appended to the file
destination. A newline is not automatically
added to the end of the message string.
|
destination
The destination. Its meaning depends on the
message_type parameter as described above.
extra_headers
The extra headers. It's used when the message_type
parameter is set to 1.
This message type uses the same internal function as
mail() does.
Example 1. error_log() examples
|
The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.
levelThe new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.
The available error level constants are listed below. The actual meanings of these error levels are described in the predefined constants.
Table 1. error_reporting() level constants and bit values
| value | constant |
|---|---|
| 1 | E_ERROR |
| 2 | E_WARNING |
| 4 | E_PARSE |
| 8 | E_NOTICE |
| 16 | E_CORE_ERROR |
| 32 | E_CORE_WARNING |
| 64 | E_COMPILE_ERROR |
| 128 | E_COMPILE_WARNING |
| 256 | E_USER_ERROR |
| 512 | E_USER_WARNING |
| 1024 | E_USER_NOTICE |
| 6143 | E_ALL |
| 2048 | E_STRICT |
| 4096 | E_RECOVERABLE_ERROR |
Example 1. error_reporting() examples
|
| Warning |
Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa). |
Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).
Example 1. restore_error_handler() example Decide if unserialize() caused an error, then restore the original error handler.
The above example will output:
|
Used after changing the exception handler function using set_exception_handler(), to revert to the previous exception handler (which could be the built-in or a user defined function).
Sets a user function (error_handler) to handle
errors in a script.
This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).
It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.
Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.
The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.
If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.
error_handlerThe user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:
handler ( int errno, string errstr [, string errfile [, int errline [, array errcontext]]] )
errno
The first parameter, errno, contains the
level of the error raised, as an integer.
errstr
The second parameter, errstr, contains the
error message, as a string.
errfile
The third parameter is optional, errfile,
which contains the filename that the error was raised in, as a string.
errline
The fourth parameter is optional, errline,
which contains the line number the error was raised at, as an integer.
errcontext
The fifth parameter is optional, errcontext,
which is an array that points to the active symbol table at the point
the error occurred. In other words, errcontext
will contain an array of every variable that existed in the scope the
error was triggered in.
User error handler must not modify error context.
error_types
Can be used to mask the triggering of the
error_handler function just like the error_reporting ini setting
controls which errors are shown. Without this mask set the
error_handler will be called for every error
regardless to the setting of the error_reporting setting.
Returns a string containing the previously defined error handler (if any), or NULL on error. If the previous handler was a class method, this function will return an indexed array with the class and the method name.
| Version | Description |
|---|---|
| 5.2.0 | The error handler must return FALSE to populate $php_errormsg. |
| 5.0.0 |
The error_types parameter was introduced.
|
| 4.3.0 |
Instead of a function name, an array containing an object reference
and a method name can also be supplied as the
error_handler.
|
| 4.0.2 |
Three optional parameters for the error_handler
user function was introduced. These are the filename, the line number,
and the context.
|
Example 1. Error handling with set_error_handler() and trigger_error() The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:
The above example will output something similar to:
|
| error_reporting() |
| restore_error_handler() |
| trigger_error() |
| error level constants |
| information about the callback type |
Sets the default exception handler if an exception is not caught within a
try/catch block. Execution will stop after the
exception_handler is called.
exception_handlerName of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.
Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.
restore_exception_handler(), restore_error_handler(), error_reporting(), information about the callback type, and PHP 5 Exceptions.
Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).
This function is useful when you need to generate a particular response to an exception at runtime.
error_msgThe designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.
error_typeThe designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.
Example 1. trigger_error() example See set_error_handler() for a more extensive example.
|
With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers of the JPEG and TIFF images.
Your PHP must be compiled in with --enable-exif. PHP does not require any additional library for the exif module. Windows users must also have the mbstring extension enabled.
To enable exif-support configure PHP with
--enable-exif
Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.
The behaviour of these functions is affected by settings in php.ini.
Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.
Table 1. Exif configuration options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0. |
| exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0. |
| exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0. |
| exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0. |
| exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0. |
| exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0. |
Here's a short explanation of the configuration directives.
exif.encode_unicode
stringexif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non Asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.
exif.decode_unicode_motorola
stringexif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.
exif.decode_unicode_intel
stringexif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.
exif.encode_jis
stringexif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.
exif.decode_jis_motorola
stringexif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.
exif.decode_jis_intel
stringexif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The exif_imagetype() lists several related built-in constants.
exif_imagetype() reads the first bytes of an image and checks its signature.
exif_imagetype() can be used to avoid calls to other
exif functions with unsupported file types
or in conjunction with $_SERVER['HTTP_ACCEPT'] to check
whether or not the viewer is able to see a specific image in the browser.
When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.
The following constants are defined, and represent possible exif_imagetype() return values:
Table 1. Imagetype Constants
| Value | Constant |
|---|---|
| 1 | IMAGETYPE_GIF |
| 2 | IMAGETYPE_JPEG |
| 3 | IMAGETYPE_PNG |
| 4 | IMAGETYPE_SWF |
| 5 | IMAGETYPE_PSD |
| 6 | IMAGETYPE_BMP |
| 7 | IMAGETYPE_TIFF_II (intel byte order) |
| 8 | IMAGETYPE_TIFF_MM (motorola byte order) |
| 9 | IMAGETYPE_JPC |
| 10 | IMAGETYPE_JP2 |
| 11 | IMAGETYPE_JPX |
| 12 | IMAGETYPE_JB2 |
| 13 | IMAGETYPE_SWC |
| 14 | IMAGETYPE_IFF |
| 15 | IMAGETYPE_WBMP |
| 16 | IMAGETYPE_XBM |
exif_read_data() reads the EXIF headers from a JPEG or TIFF image file. This way you can read meta data generated by digital cameras.
Exif headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.
Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.
When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent in the Exif 2.10 standard, the COMPUTED section will return both entries Copyright.Photographer and Copyright.Editor while the IFD0 sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The COMPUTED will also contain the entry Copyright which is either the original copyright string, or a comma separated list of the photo and editor copyright.
The tag UserComment has the same problem as the Copyright tag. It can store two values. First the encoding used, and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.
exif_read_data() also validates EXIF data tags according to the EXIF specification (http://exif.org/Exif2-2.PDF, page 20).
Note: Windows ME/XP can both wipe the Exif headers when connecting to a camera. More information available at http://www.canon.co.jp/Imaging/NOTICE/011214-e.html.
filenameThe name of the image file being read. This cannot be an URL.
sectionsIs a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is FALSE.
| FILE | FileName, FileSize, FileDateTime, SectionsFound |
| COMPUTED | html, Width, Height, IsColor, and more if available. Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML. |
| ANY_TAG | Any information that has a Tag e.g. IFD0, EXIF, ... |
| IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth. |
| THUMBNAIL | A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section. |
| COMMENT | Comment headers of JPEG images. |
| EXIF | The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related. |
arrays
Specifies whether or not each section becomes an array. The
sections COMPUTED,
THUMBNAIL, and COMMENT
always become arrays as they may contain values whose names conflict
with other sections.
thumbnailWhen set to TRUE the thumbnail itself is read. Otherwise, only the tagged data is read.
It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, exif_read_data() will return FALSE.
| Version | Description |
|---|---|
| 4.3.0 | Can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in a THUMBNAIL subarray, and can return thumbnails in TIFF format. Also, there is no longer a maximum length for returned values (not until the memory limit has been reached) |
| 4.3.0 | If PHP has mbstring support, the user comment can automatically change encoding. Also, if the user comment uses Unicode or JIS encoding this encoding will automatically be changed according to the exif ini settings in php.ini |
| 4.3.0 | If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. Also, COMPUTED and UserComment no longer only contain the first copyright entry if the datatype was wrong. |
Example 1. exif_read_data() example
The first call fails because the image has no header information. The above example will output something similar to:
|
| Warning |
This function is currently not documented; only the argument list is available. |
exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image.
If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.
It is possible that exif_thumbnail() cannot create an
image but can determine its size. In this case, the return value is
FALSE but width and height
are set.
filenameThe name of the image file being read. This image contains an embedded thumbnail.
widthThe return width of the returned thumbnail.
heightThe returned height of the returned thumbnail.
imagetypeThe returned image type of the returned thumbnail. This is either TIFF or JPEG.
Example 1. exif_thumbnail() example
|
This extension allows to interact with processes through PTY. You may consider using the expect:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.
This module uses the functions of the expect library. You need libexpect version >= 5.43.0.
This PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/expect.
In PHP 4 this PECL extensions
source can be found in the ext/ directory within the
PHP source or at the PECL link above.
In order to use these functions you must compile PHP with expect support
by using the --with-expect[=DIR]
configure option.
Windows users will enable php_expect.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. The DLL for this PECL extension may be downloaded from either the PHP Downloads page or from http://pecl4win.php.net/
The behaviour of these functions is affected by settings in php.ini.
In order to configure expect extension, there are configuration options in the configuration file php.ini.
Table 1. Expect Configure Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| expect.timeout | "10" | PHP_INI_ALL | |
| expect.loguser | "1" | PHP_INI_ALL | |
| expect.logfile | "" | PHP_INI_ALL |
Here's a short explanation of the configuration directives.
expect.timeout
integerThe timeout period for waiting for the data, when using the expect_expectl() function.
A value of "-1" disables a timeout from occurring.
Note: A value of "0" causes the expect_expectl() function to return immediately.
expect.loguser
booleanWhether expect should send any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation.
expect.logfile
stringName of the file, where the output from the spawned process will be written. If this file doesn't exist, it will be created.
Note: If this configuration is not empty, the output is written regardless of the value of expect.loguser.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Indicates that the pattern is a glob-style string pattern.
Indicates that the pattern is an exact string.
Indicates that the pattern is a regexp-style string pattern.
Value, returned by expect_expectl(), when EOF is reached.
Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout
Value, returned by expect_expectl() if no pattern have been matched.
This example connects to the remote host via SSH, and prints the remote uptime.
Example 1. Expect Usage Example
|
(no version information, might be only in CVS)
expect_expectl -- Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seenWaits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.
If match is provided, then it is filled with the result of search.
The matched string can be found in match[0].
The match substrings (according to the parentheses) in the original pattern can be found
in match[1], match[2], and so
on, up to match[9] (the limitation of libexpect).
expectAn Expect stream, previously opened with expect_popen().
casesAn array of expect cases. Each expect case is an indexed array, as described in the following table:
Table 1. Expect Case Array
| Index Key | Value Type | Description | Is Mandatory | Default Value |
|---|---|---|---|---|
| 0 | string | pattern, that will be matched against the output from the stream | yes | |
| 1 | mixed | value, that will be returned by this function, if the pattern matches | yes | |
| 2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB |
Returns value associated with the pattern that was matched.
On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER
Example 1. expect_expectl() example
|
(no version information, might be only in CVS)
expect_popen -- Execute command via Bourne shell, and open the PTY stream to the processExecute command via Bourne shell, and open the PTY stream to the process.
Returns an open PTY stream to the process'es stdio, stdout and stderr.
On failure this function returns FALSE.
FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at http://oss.sgi.com/projects/fam/.
A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.
The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.1.0.
Note: This extension is not available on Windows platforms.
This extension uses the functions of the FAM library, developed by SGI. Therefore you have to download and install the FAM library.
To use PHP's FAM support you must compile PHP --with-fam[=DIR] where DIR is the
location of the directory containing the lib and include
directories.
There are two resource types used in the FAM module. The first one is the connection to the FAM service returned by fam_open(), the second a monitoring resource returned by the fam_monitor_XXX functions.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Table 1. FAM event constants
| Constant | Description |
|---|---|
| FAMChanged (integer) | Some value which can be obtained with fstat(1) changed for a file or directory. |
| FAMDeleted (integer) | A file or directory was deleted or renamed. |
| FAMStartExecuting (integer) | An executable file started executing. |
| FAMStopExecuting (integer) | An executable file that was running finished. |
| FAMCreated (integer) | A file was created in a directory. |
| FAMMoved (integer) | This event never occurs. |
| FAMAcknowledge (integer) | An event in response to fam_cancel_monitor(). |
| FAMExists (integer) | An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued. |
| FAMEndExist (integer) | Event after the last FAMEExists event. |
Terminates monitoring on a resource.
In addition an FAMAcknowledge event occurs.
famA resource representing a connection to the FAM service returned by fam_open()
fam_monitorA resource returned by one of the fam_monitor_XXX functions
Requests monitoring for a collection of files within a directory.
A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.
famA resource representing a connection to the FAM service returned by fam_open()
dirnameDirectory path to the monitored files
depth
The maximum search depth starting from this
directory
mask
A shell pattern mask restricting the file names
to look for
| fam_monitor_file() |
| fam_monitor_directory() |
| fam_cancel_monitor() |
| fam_suspend_monitor() |
| fam_resume_monitor() |
Requests monitoring for a directory and all contained files.
A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) changes.
The possible event codes are described in detail in the constants part of this section.
famA resource representing a connection to the FAM service returned by fam_open()
dirnamePath to the monitored directory
| fam_monitor_file() |
| fam_monitor_collection() |
| fam_cancel_monitor() |
| fam_suspend_monitor() |
| fam_resume_monitor() |
Requests monitoring for a single file. A FAM event will be generated whenever the file status changes (i.e. the result of function stat() on that file).
The possible event codes are described in detail in the constants part of this section.
famA resource representing a connection to the FAM service returned by fam_open()
filenamePath to the monitored file
| fam_monitor_directory() |
| fam_monitor_collection() |
| fam_cancel_monitor() |
| fam_suspend_monitor() |
| fam_resume_monitor() |
Returns the next pending FAM event.
The function will block until an event is available which can be checked for using fam_pending().
Returns an array that contains a FAM event code in the 'code' element, the path of the file this event applies to in the 'filename' element and optionally a hostname in the 'hostname' element.
The possible event codes are described in detail in the constants part of this section.
Returns a resource representing a connection to the FAM service on success or FALSE on errors.
Returns non-zero if events are available to be fetched using fam_next_event(), zero otherwise.
Resumes monitoring of a resource previously suspended using fam_suspend_monitor().
famA resource representing a connection to the FAM service returned by fam_open()
fam_monitorA resource returned by one of the fam_monitor_XXX functions
fam_suspend_monitor() temporarily suspend monitoring of a resource.
Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.
famA resource representing a connection to the FAM service returned by fam_open()
fam_monitorA resource returned by one of the fam_monitor_XXX functions
Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at http://partners.adobe.com/asn/acrobat/forms.jsp for more information on what FDF is and how it is used in general.
The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType application/vnd.fdf. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.
If you look at an FDF-document with a text editor you will find a catalogue object with the name FDF. Such an object may contain a number of entries like Fields, F, Status etc.. The most commonly used entries are Fields which points to a list of input fields, and F which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..
You need the FDF toolkit SDK available from http://partners.adobe.com/asn/acrobat/forms.jsp. As of PHP 4.3.0 you need at least SDK version 5.0. The FDF toolkit library is available in binary form only, platforms supported by Adobe are Win32, Linux, Solaris and AIX.
You must compile PHP with
--with-fdftk[=DIR].
Note: If you run into problems configuring PHP with fdftk support, check whether the header file fdftk.h and the library libfdftk.so are at the right place. The configure script supports both the directory structure of the FDF SDK distribution and the usual DIR/include / DIR/lib layout, so you can point it either directly to the unpacked distribution directory or put the header file and the appropriate library for your platform into e.g. /usr/local/include and /usr/local/lib and configure with
--with-fdftk=/usr/local.
Note to Win32 Users: In order for this extension to work, there are DLL files that must be available to the Windows system PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the systems PATH), it is not recommended. This extension requires the following files to be in the PATH: fdftk.dll
Most fdf functions require a fdf resource
as their first parameter. A fdf resource
is a handle to an opened fdf file. fdf
resources may be obtained using fdf_create(),
fdf_open() and fdf_open_string().
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The following examples shows just the evaluation of form data.
Example 1. Evaluating a FDF document
|
Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
script_nameThe script name.
script_codeThe script code. It is strongly suggested to use \r for linebreaks within the script code.
Example 1. Adding JavaScript code to a FDF
will create a FDF like this:
|
| Warning |
This function is currently not documented; only the argument list is available. |
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
Creates a new FDF document.
This function is needed if one would like to populate input fields in a PDF document with data.
Example 1. Populating a PDF document
|
| Warning |
This function is currently not documented; only the argument list is available. |
Gets the error code set by the last FDF function call.
A textual description of the error may be obtained using with fdf_error().
Gets a textual description for the FDF error code given in
error_code.
error_codeAn error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.
Gets the appearance of a field (i.e. the value of
the /AP key) and stores it in a file.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
field
faceThe possible values are FDFNormalAP, FDFRolloverAP and FDFDownAP.
filenameThe appearance will be stored in this parameter.
Extracts a file uploaded by means of the "file selection" field
fieldname and stores it under
savepath.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldname
savepathMay be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.
Note: There seems to be no other way to find out the original filename but to store the file using a directory as
savepathand check for the basename it was stored under.
The returned array contains the following fields:
path - path were the file got stored
size - size of the stored file in bytes
type - mimetype if given in the FDF
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
Returns the encoding as a string. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
| Warning |
This function is currently not documented; only the argument list is available. |
| Warning |
This function is currently not documented; only the argument list is available. |
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
Gets the value for the requested field.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldnameName of the FDF field, as a string.
whichElements of an array field can be retrieved by passing this optional parameter, starting at zero. For non-array fields, this parameter will be ignored.
Return the FDF version for the given document, or the toolkit API version number if no parameter is given.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
Returns the version as a string. For the current FDF toolkit 5.0 the API version number is 5.0 and the document version number is either 1.2, 1.3 or 1.4.
This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.
Gets the name of the field after the given field. This name can be used with several functions.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldnameName of the FDF field, as a string. If not given, the first field will be assumed.
Reads form data from a string.
You can use fdf_open_string() together with
$HTTP_FDF_DATA to process FDF form input from a remote
client.
fdf_dataThe data as returned from a PDF form or created using fdf_create() and fdf_save_string().
Opens a file with form data.
You can also use fdf_open_string() to process the results of a PDF form POST request.
filenamePath to the FDF file. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().
| Warning |
This function is currently not documented; only the argument list is available. |
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
Example 1. Retrieving FDF as a string
The above example will output:
|
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
filenameIf provided, the resulting FDF will be written in this parameter. Otherwise, this function will write the FDF to the default PHP output stream.
Sets the appearance of a field (i.e. the value of the /AP key).
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
field_name
faceThe possible values FDFNormalAP, FDFRolloverAP and FDFDownAP.
filename
page_number
Sets the character encoding for the FDF document.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
encodingThe encoding name. The following values are supported: "Shift-JIS", "UHC", "GBK" and "BigFive".
An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.
Selects a different PDF document to display the form results in then the form it originated from.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
urlShould be given as an absolute URL.
target_frameUse this parameter to specify the frame in which the document will be displayed. You can also set the default value for this parameter using fdf_set_target_frame().
Example 1. Passing FDF data to a second form
|
Sets certain flags of the given field.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldnameName of the FDF field, as a string.
whichFlags
newFlags
Sets a javascript action for the given field.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldnameName of the FDF field, as a string.
trigger
script
(PHP 4 >= 4.3.0, PHP 5)
fdf_set_on_import_javascript -- Adds javascript code to be executed when Acrobat opens the FDF| Warning |
This function is currently not documented; only the argument list is available. |
Sets options of the given field.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldnameName of the FDF field, as a string.
element
str1
str2
Sets the value of the /STATUS key. When a client receives a FDF with a status set it will present the value in an alert box.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
status
Sets a submit form action for the given field.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldnameName of the FDF field, as a string.
trigger
script
flags
Sets the target frame to display a result PDF defined with fdf_save_file() in.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
frame_nameThe frame name, as a string.
Sets the value for the given field.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
fieldnameName of the FDF field, as a string.
valueThis parameter will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.
isNameNote: In older versions of the FDF toolkit last parameter determined if the field value was to be converted to a PDF Name (= 1) or set to a PDF String (= 0).
The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter beginning with PHP 4.3, but ignored internally.
Sets the FDF version for the given document.
Some features supported by this extension are only available in newer FDF versions.
fdf_documentThe FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().
versionThe version number. For the current FDF toolkit 5.0, this may be either 1.2, 1.3 or 1.4.
The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.netfileinfo
There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
No special handling.
Follow symlinks.
Return a mime string, instead of a textual description.
Decompress compressed files.
Look at the contents of blocks or character special devices.
Return all matches, not just the first.
If possible preserve the original access time.
Don't translate unprintable characters to a \ooo octal representation.
This function is used to get information about binary data in a string.
finfoFileinfo resource returned by finfo_open().
stringContent of a file to be checked.
optionsOne or disjunction of more Fileinfo constants.
__destruct();
}This function closes the resource opened by finfo_open().
This function is used to get information about a file.
finfoFileinfo resource returned by finfo_open().
file_nameName of a file to be checked.
optionsOne or disjunction of more Fileinfo constants.
contextFor a description of contexts, refer to Reference CLIX, Stream Functions.
Returns a textual description of the contents of the
filename argument, or FALSE if an error occurred.
Example 1. A finfo_file() example
The above example will output something similar to:
|
This function opens a magic database and returns its resource.
optionsOne or disjunction of more Fileinfo constants.
magic_fileName of a magic database file, usually something like /path/to/magic.mime. If not specified, MAGIC environment variable is used. If this variable is not set neither, /usr/share/misc/magic is used. .mime and/or .mgc is added if appropriate.
This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.
finfoFileinfo resource returned by finfo_open().
optionsOne or disjunction of more Fileinfo constants.
These functions allow read-only access to data stored in filePro databases.
filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at http://www.fptech.com/.
Note: This extension has been moved to the PECL repository and is no longer bundled with PHP as of PHP 5.2.0.
filePro support in PHP is not enabled by default. To
enable the bundled read-only filePro support you need
to use the--enable-filepro configuration
option when compiling PHP.
Returns the number of fields (columns) in the opened filePro database.
Returns the name of the field corresponding to
field_number.
Returns the edit type of the field corresponding to field_number.
Returns the width of the field corresponding to field_number.
Returns the data from the specified location in the database.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
row_numberThe row number. Must be between zero and the total number of rows minus one (0..filepro_rowcount() - 1)
field_numberThe field number. Accepts values between zero and the total number of fields minus one (0..filepro_fieldcount() - 1)
Returns the number of rows in the opened filePro database.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
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.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
No external libraries are needed to build this extension, but if you want PHP to support LFS (large files) on Linux, then you need to have a recent glibc and you need compile PHP with the following compiler flags: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.
The behaviour of these functions is affected by settings in php.ini.
Table 1. Filesystem and Streams Configuration Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.3.4. Available since PHP 4.0.4. |
| allow_url_include | "0" | PHP_INI_SYSTEM | Available since PHP 5.2.0. |
| user_agent | NULL | PHP_INI_ALL | Available since PHP 4.3.0. |
| default_socket_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.0. |
| from | "" | PHP_INI_ALL | |
| auto_detect_line_endings | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
Here's a short explanation of the configuration directives.
allow_url_fopen
booleanThis option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.
Note: This setting can only be set in php.ini due to security reasons.
Note: This option was introduced immediately after the release of version 4.0.3. For versions up to and including 4.0.3 you can only disable this feature at compile time by using the configuration switch
--disable-url-fopen-wrapper.
| Warning |
On Windows versions prior to PHP 4.3.0, the following functions do not support remote file accessing: include(), include_once(), require(), require_once() and the imagecreatefromXXX functions in the Reference LXIV, Image Functions extension. |
allow_url_include
booleanThis option allows the use of URL-aware fopen wrappers with the following functions: include(), include_once(), require(), require_once().
Note: This setting requires allow_url_fopen to be on.
user_agent
stringDefine the user agent for PHP to send.
default_socket_timeout
integerDefault timeout (in seconds) for socket based streams.
Note: This configuration option was introduced in PHP 4.3.0
from
stringDefine the anonymous ftp password (your email address).
auto_detect_line_endings
booleanWhen turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.
This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.
Note: This configuration option was introduced in PHP 4.3.0
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Since PHP 5.2.0.
For related functions, see also the Directory and Program Execution sections.
For a list and explanation of the various URL wrappers that can be used as remote files, see also Appendix N.
Given a string containing a path to a file, this function will
return the base name of the file.
If the filename ends in suffix this will
also be cut off.
On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).
Note: The
suffixparameter was added in PHP 4.1.0.
See also dirname().
Attempts to change the group of the file filename
to group (specified by name or number). 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 or FALSE on failure.
Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
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, so strings (such as "g+w") will
not work properly. To ensure the expected operation,
you need to prefix mode with a zero (0):
<?php
chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode
?> |
The mode parameter consists of three octal
number components specifying access restrictions for the owner,
the user group in which the owner is in, and to everybody else in
this order. One component can be computed by adding up the needed
permissions for that target user base. Number 1 means that you
grant execute rights, number 2 means that you make the file
writeable, number 4 means that you make the file readable. Add
up these numbers to specify needed rights. You can also read more
about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.
<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);
// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);
// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?> |
Returns TRUE on success or FALSE on failure.
Note: The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.
Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.
Attempts to change the owner of the file filename
to user user (specified by name or number). Only
the superuser may change the owner of a file.
Returns TRUE on success or FALSE on failure.
Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.
Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed.
See also chmod().
When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.
You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return FALSE until you create the file. If you create the file, it will return TRUE even if you then delete the file.
Note: This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached.
Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().
Makes a copy of the file source to
dest. Returns TRUE on success or FALSE on failure.
If you wish to move a file, use the rename() function.
Note: As of PHP 4.3.0, both
sourceanddestmay be URLs if the "fopen wrappers" have been enabled. See fopen() for more details. Ifdestis a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.
| Warning |
If the destination file already exists, it will be overwritten. |
Note: Windows compatibility: If you copy a file with no size, copy() will return FALSE, but the file will be correctly copied.
See also move_uploaded_file(), rename(), and the section of the manual about handling file uploads.
This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.
See also unlink() to delete files, unset() to delete variables.
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 directory separator character. In other environments, it is the forward slash (/).
Note: In PHP 4.0.3, dirname() was fixed to be POSIX-compliant. Essentially, this means that if there are no slashes in
path, a dot ('.') is returned, indicating the current directory. Otherwise, the returned string ispathwith any trailing /component removed. Note that this means that you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.
dirname() has changed its behaviour in PHP 4.3.0. Check the following examples:
<?php
//before PHP 4.3.0
dirname('c:/'); // returned '.'
//after PHP 4.3.0
dirname('c:/'); // returns 'c:'
?> |
dirname() has been binary safe since PHP 5.0.0
See also basename(), pathinfo(), and realpath().
Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.
Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.
See also disk_total_space()
Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition.
Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.
See also disk_free_space()
The file pointed to by handle is closed.
Returns TRUE on success or FALSE on failure.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
| Warning |
If a connection opened by fsockopen() wasn't closed by the server, feof() will wait until a timeout has been reached to return TRUE. The default timeout value is 60 seconds. You may use stream_set_timeout() to change this value. |
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
| Warning | |
If passed file pointer is not valid you may get an infinite loop, because EOF fails to return TRUE. |
This function forces a write of all buffered output to the
resource pointed to by the file handle handle.
Returns TRUE on success or FALSE on failure.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
Returns a string containing a single character read from the
file pointed to by handle.
Returns FALSE on EOF.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).
| Warning |
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. |
Note: This function is binary-safe.
See also fread(), fopen(), popen(), fsockopen(), and fgets().
handleA valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
length (Optional)Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is not limited, which is slightly slower.
delimiter (Optional)Set the field delimiter (one character only). Defaults as a comma.
enclosure (Optional)Set the field enclosure character (one character only). Defaults as a double quotation mark. Added in PHP 4.3.0.
Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
fgetcsv() returns FALSE on error, including end of file.
Note: A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.