# PHP Manual

2014-03-28

Copyright © 1997 - 2014 by the PHP Documentation Group. This material may be distributed only subject to the terms and conditions set forth in the Creative Commons Attribution 3.0 License or later. A copy of the Creative Commons Attribution 3.0 license is distributed with this manual. The latest version is presently available at » http://creativecommons.org/licenses/by/3.0/.

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

# Preface

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.

# Authors and Contributors

We highlight the currently most active people on front page of the manual, but there are many more contributors who currently help in our work or have provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful for. All of the lists provided below are in alphabetical order.

# Authors and Editors

The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Peter Cowburn, Daniel Egeberg, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Justin Martin, Rafael Martinez, Rick McGuire, Moacir de Oliveira Miranda Júnior, Kalle Sommer Nielsen, Yasuo Ohgaki, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yannick Torres, Michael Wallner, 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.

# User Note Maintainers

The currently most active maintainers are: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda and Maciek Sokolewicz.

These people have also put a lot of effort into managing user notes: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles and Jeroen van Wolffelaar.

# What is PHP?

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.

Nice, but what does that mean? An example:

Example #1 An introductory example

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    "http://www.w3.org/TR/html4/loose.dtd"><html>    <head>        <title>Example</title>    </head>    <body>        <?php            echo "Hi, I'm a PHP script!";        ?>    </body></html> 

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> 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, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. 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.

# What can PHP do?

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, IIS, and many others. And this includes any web server that can utilize the FastCGI PHP binary, like lighttpd and nginx. PHP works as either a module, or 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 (OOP), or a mixture of them both.

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 using one of the database specific extensions (e.g., for mysql), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB.

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.

PHP has useful text processing features, which includes the Perl compatible regular expressions (PCRE), and many extensions and tools to parse and access XML documents. PHP standardizes all of the XML extensions on the solid base of libxml2, and extends the feature set adding SimpleXML, XMLReader and XMLWriter support.

And many other interesting extensions exist, which are categorized both alphabetically and by category. And there are additional PECL extensions that may or may not be documented within the PHP manual itself, like » XDebug.

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.

# A simple tutorial

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.

# What do I need?

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.

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). If 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:

Example #1 Our first PHP script: hello.php

 <html> <head>  <title>PHP Test</title> </head> <body> <?php echo '<p>Hello World</p>'; ?>  </body></html> 

Use your browser to access the file with your web server's URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

<html>
<title>PHP Test</title>
<body>
<p>Hello World</p>
</body>
</html>


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.

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

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

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

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

Example #2 Get system information from PHP

 <?php phpinfo(); ?> 

# Something Useful

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_*_VARS arrays 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:

Example #1 Printing a variable (Array element)

 <?phpecho $_SERVER['HTTP_USER_AGENT'];?>  A sample output of this script may be: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) 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 Example using control structures and functions

 <?phpif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) { echo 'You are using Internet Explorer.<br />';}?>  A sample output of this script may be: You are using Internet Explorer.<br />  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. 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 #3 Mixing both HTML and PHP modes

 <?phpif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {?><h3>strpos() must have returned non-false</h3><p>You are using Internet Explorer</p><?php} else {?><h3>strpos() must have returned false</h3><p>You are not using Internet Explorer</p><?php}?>  A sample output of this script may be: <h3>strpos() must have returned non-false</h3> <p>You are using Internet Explorer</p>  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. # Dealing with Forms 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 external sources for more information and examples on using forms with PHP. Here is an example HTML form: Example #1 A simple HTML form <form action="action.php" method="post"> <p>Your name: <input type="text" name="name" /></p> <p>Your age: <input type="text" name="age" /></p> <p><input type="submit" /></p> </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: Example #2 Printing data from our form  Hi <?php echo htmlspecialchars($_POST['name']); ?>.You are <?php echo (int)$_POST['age']; ?> years old.  A sample output of this script may be: Hi Joe. You are 22 years old.  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. # Using old code with new versions of PHP 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, also exist. 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.
For more details on these changes, see the section on predefined variables and links therein.

# What's next?

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.

To view various slide presentations that show more of what PHP can do, see the PHP Conference Material Site: » http://talks.php.net/

# General Installation Considerations

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.

# Installation on Unix systems

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
• A web server
• Any module specific components (such as GD, PDF libs, etc.)

When building directly from Git sources or after custom modifications you might also need:

• autoconf: 2.13+ (for PHP < 5.4.0), 2.59+ (for PHP >= 5.4.0)
• automake: 1.4+
• libtool: 1.4.x+ (except 1.4.2)
• re2c: Version 0.13.4 or newer
• flex: Version 2.5.4 (for PHP <= 5.2)
• bison: Version 1.28 (preferred), 1.35, or 1.75

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.

## Apache 1.3.x on Unix systems

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 #1 Installation Instructions (Apache Shared Module Version) for PHP

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx

10. Now, configure your PHP.  This is where you customize your PHP
with various options, like which extensions will be enabled.  Do a
./configure --help for a list of available options.  In our example
we'll do a simple configure with Apache 1 and MySQL support.  Your
path to apxs may differ from our example.

./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

If you decide to change your configure options after installation,
you only need to repeat the last three steps. You only need to
restart apache for the new module to take effect. A recompile of
Apache is not needed.

Note that unless told otherwise, 'make install' will also install PEAR,
various PHP tools such as phpize, install the PHP CLI, and more.

cp php.ini-development /usr/local/lib/php.ini

You may edit your .ini file to set PHP options.  If you prefer your
php.ini in another location, use --with-config-file-path=/some/path in
step 10.

of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
side of the LoadModule statement must point to the path of the PHP
module on your system.  The make install from above may have already
added this for you, but be sure to check.

15. And in the AddModule section of httpd.conf, somewhere under the

16. Tell Apache to parse certain extensions as PHP.  For example,
let's have Apache parse the .php extension as PHP.  You could
have any extension(s) parse as PHP by simply adding more, with
each separated by a space.  We'll add .phtml to demonstrate.

It's also common to setup the .phps extension to show highlighted PHP
source, this can be done with:

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


Alternatively, to install PHP as a static object:

Example #2 Installation Instructions (Static Module Installation for Apache) for PHP

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-5.x.y.tar.gz | tar xf -
6.  cd php-5.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
(The above line is correct! Yes, we know libphp5.a does not exist at this
stage. It isn't supposed to. It will be created.)

12. make
(you should now have an httpd binary which you can copy to your Apache bin dir if
it is your first install then you need to "make install" as well)

13. cd ../php-5.x.y
14. cp php.ini-development /usr/local/lib/php.ini

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


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 #3 Example commands for restarting Apache

1. Several Linux and SysV variants:
/etc/rc.d/init.d/httpd restart

2. Using apachectl scripts:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Using mod_ssl, or another SSL server, you may want to manually
stop and start:
/path/to/apachectl stop
/path/to/apachectl startssl

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:

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

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

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

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

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

This will create a 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. The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

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

Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from 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:

User nobody
Group "#-1"
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.

## Apache 2.x on Unix systems

This section contains notes and hints specific to Apache 2.x installs of PHP on Unix systems.

Warning

We do not recommend using a threaded MPM in production with Apache 2. Use the prefork MPM, which is the default MPM with Apache 2.0 and 2.2. For information on why, read the related FAQ entry on using Apache2 with a threaded MPM

The » Apache Documentation is the most authoritative source of information on the Apache 2.x server. More information about installation options for Apache may be found there.

The most recent version of Apache HTTP Server may be obtained from » Apache download site, and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.x and PHP. For more information read the » Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. In the examples below, 'NN' should be replaced with the specific version of Apache being used.

There are currently two versions of Apache 2.x - there's 2.0 and 2.2. While there are various reasons for choosing each, 2.2 is the current latest version, and the one that is recommended, if that option is available to you. However, the instructions here will work for either 2.0 or 2.2.

1. Obtain the Apache HTTP server from the location listed above, and unpack it:

gzip -d httpd-2_x_NN.tar.gz
tar -xf httpd-2_x_NN.tar

2. Likewise, obtain and unpack the PHP source:

gunzip php-NN.tar.gz
tar -xf php-NN.tar

3. Build and install Apache. Consult the Apache install documentation for more details on building Apache.

cd httpd-2_x_NN
./configure --enable-so
make
make install

4. Now you have Apache 2.x.NN available under /usr/local/apache2, configured with loadable module support and the standard MPM prefork. To test the installation use your normal procedure for starting the Apache server, e.g.:

/usr/local/apache2/bin/apachectl start

and stop the server to go on with the configuration for PHP:
/usr/local/apache2/bin/apachectl stop


5. Now, configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support.

If you built Apache from source, as described above, the below example will match your path for apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs accordingly. Note that some distros may rename apxs to apxs2.

cd ../php-NN
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
make
make install


If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed.

Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more.

cp php.ini-development /usr/local/lib/php.ini


You may edit your .ini file to set PHP options. If you prefer having php.ini in another location, use --with-config-file-path=/some/path in step 5.

If you instead choose php.ini-production, be certain to read the list of changes within, as they affect how PHP behaves.

7. Edit your httpd.conf to load the PHP module. The path on the right hand side of the LoadModule statement must point to the path of the PHP module on your system. The make install from above may have already added this for you, but be sure to check.

LoadModule php5_module modules/libphp5.so
8. Tell Apache to parse certain extensions as PHP. For example, let's have Apache parse .php files as PHP. Instead of only using the Apache AddType directive, we want to avoid potentially dangerous uploads and created files such as exploit.php.jpg from being executed as PHP. Using this example, you could have any extension(s) parse as PHP by simply adding them. We'll add .php to demonstrate.

<FilesMatch \.php$> SetHandler application/x-httpd-php </FilesMatch> Or, if we wanted to allow .php, .php2, .php3, .php4, .php5, .php6, and .phtml files to be executed as PHP, but nothing else, we'd use this: <FilesMatch "\.ph(p[2-6]?|tml)$">
SetHandler application/x-httpd-php
</FilesMatch>

And to allow .phps files to be handled by the php source filter, and displayed as syntax-highlighted source code, use this:

<FilesMatch "\.phps$"> SetHandler application/x-httpd-php-source </FilesMatch> mod_rewrite may be used To allow any arbitrary .php file to be displayed as syntax-highlighted source code, without having to rename or copy it to a .phps file: RewriteEngine On RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source] The php source filter should not be enabled on production systems, where it may expose confidential or otherwise sensitive information embedded in source code. 9. Use your normal procedure for starting the Apache server, e.g.: /usr/local/apache2/bin/apachectl start  OR service httpd restart  Following the steps above you will have a running Apache2 web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree. Apache may be built multithreaded by selecting the worker MPM, rather than the standard prefork MPM, when Apache is built. This is done by adding the following option to the argument passed to ./configure, in step 3 above: --with-mpm=worker This should not be undertaken without being aware of the consequences of this decision, and having at least a fair understanding of the implications. The Apache documentation regarding » MPM-Modules discusses MPMs in a great deal more detail. Note: The Apache MultiViews FAQ discusses using multiviews with PHP. Note: To build a multithreaded version of Apache, the target system must support threads. In this case, PHP should also be built with experimental Zend Thread Safety (ZTS). Under this configuration, not all extensions will be available. The recommended setup is to build Apache with the default prefork MPM-Module. ## Nginx 1.4.x on Unix systems This documentation will cover installing and configuring PHP with PHP-FPM for a Nginx 1.4.x HTTP server. This guide will assume that you have built Nginx from source and therefore all binaries and configuration files are located at /usr/local/nginx. If this is not the case and you have obtained Nginx through other means then please refer to the » Nginx Wiki in order translate this manual to your setup. This guide will cover the basics of configuring an Nginx server to process PHP applications and serve them on port 80, it is recommended that you study the Nginx and PHP-FPM documentation if you wish to optimise your setup past the scope of this documentation. Please note that throughout this documentation version numbers have been replaced with an 'x' to ensure this documentation stays correct in the future, please replace these as necessary with the corresponding version numbers. 1. It is recomended that you visit the Nginx Wiki » install page in order to obtain and install Nginx on your system. 2. Obtain and unpack the PHP source: tar zxf php-x.x.x  3. Configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with PHP-FPM and MySQL support. cd ../php-x.x.x ./configure --enable-fpm --with-mysql make sudo make install  4. Obtain and move configuration files to their correct locations cp php.ini-development /usr/local/php/php.ini cp /usr/local/etc/php-fpm.conf.default /usr/local/etc/php-fpm.conf cp sapi/fpm/php-fpm /usr/local/bin  5. It is important that we prevent Nginx from passing requests to the PHP-FPM backend if the file does not exists, allowing us to prevent arbitrarily script injection. We can fix this by setting the cgi.fix_pathinfo directive to 0 within our php.ini file. Load up php.ini: vim /usr/local/php/php.ini  Locate cgi.fix_pathinfo= and modify it as follows: cgi.fix_pathinfo=0  6. php-fpm.conf must be modified to specify that php-fpm must run as the user www-data and the group www-data before we can start the service: vim /usr/local/etc/php-fpm.conf  Find and modify the following: ; Unix user/group of processes ; Note: The user is mandatory. If the group is not set, the default user's group ; will be used. user = www-data group = www-data  The php-fpm service can now be started: /usr/local/bin/php-fpm  This guide will not configure php-fpm any further, if you are interested in further configuring php-fpm then please consult the documentation. 7. Nginx must now be configured to support the processing of PHP applications: vim /usr/local/nginx/conf/nginx.conf  Modify the default location block to be aware it must attempt to serve .php files: location / { root html; index index.php index.html index.htm; } The next step is to ensure that .php files are passed to the PHP-FPM backend, blow the commented default PHP location block, enter the following: location ~* \.php$ {
fastcgi_index   index.php;
fastcgi_pass    127.0.0.1:9000;
include         fastcgi_params;
fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param   SCRIPT_NAME        $fastcgi_script_name; } Restart Nginx. sudo /usr/local/nginx/sbin/nginx -s stop sudo /usr/local/nginx/sbin/nginx  8. Create a test file rm /usr/local/nginx/html/index.html echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/index.php  Now navigate to http://localhost. The phpinfo() should now be shown. Following the steps above you will have a running Nginx web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree. ## Lighttpd 1.4 on Unix systems This section contains notes and hints specific to Lighttpd 1.4 installs of PHP on Unix systems. Please use the » Lighttpd trac to learn how to install Lighttpd properly before continuing. Fastcgi is the preferred SAPI to connect PHP and Lighttpd. Fastcgi is automagically enabled in php-cgi in PHP 5.3, but for older versions configure PHP with --enable-fastcgi. To confirm that PHP has fastcgi enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3, fastcgi was enabled on the php binary (there was no php-cgi). ### Letting Lighttpd spawn php processes To configure Lighttpd to connect to php and spawn fastcgi processes, edit lighttpd.conf. Sockets are preferred to connect to fastcgi processes on the local system. Example #1 Partial lighttpd.conf server.modules += ( "mod_fastcgi" ) fastcgi.server = ( ".php" => (( "socket" => "/tmp/php.socket", "bin-path" => "/usr/local/bin/php-cgi", "bin-environment" => ( "PHP_FCGI_CHILDREN" => "16", "PHP_FCGI_MAX_REQUESTS" => "10000" ), "min-procs" => 1, "max-procs" => 1, "idle-timeout" => 20 )) )  The bin-path directive allows lighttpd to spawn fastcgi processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The "bin-environment" directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives "min-procs" and "max-procs" should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If "min-procs" is set to something greater than 1, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders). ### Spawning with spawn-fcgi Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier. ### Spawning php-cgi It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders. Example #2 Spawning FastCGI Responders #!/bin/sh # Location of the php-cgi binary PHP=/usr/local/bin/php-cgi # PID File location PHP_PID=/tmp/php.pid # Binding to an address #FCGI_BIND_ADDRESS=10.0.1.1:10000 # Binding to a domain socket FCGI_BIND_ADDRESS=/tmp/php.sock PHP_FCGI_CHILDREN=16 PHP_FCGI_MAX_REQUESTS=10000 env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \$PHP -b $FCGI_BIND_ADDRESS & echo$! > "$PHP_PID"  ### Connecting to remote FCGI instances Fastcgi instances can be spawned on multiple remote machines in order to scale applications. Example #3 Connecting to remote php-fastcgi instances fastcgi.server = ( ".php" => (( "host" => "10.0.0.2", "port" => 1030 ), ( "host" => "10.0.0.3", "port" => 1030 )) )  ## Sun, iPlanet and Netscape servers on Sun Solaris 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. 1. 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) 2. 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. 3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4). 4. tar xvf php-x.x.x.tar 5. Change to your extracted PHP directory: cd ../php-x.x.x 6. 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 7. 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/. 1. Add the following line to mime.types (you can do that by the administration server): type=magnus-internal/x-httpd-php exts=php  2. 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"]  (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory. 3. 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>  (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On" 4. 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>  After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html. 5. 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>  6. 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"). ### CGI environment and recommended modifications in php.ini 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 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


### Special use for error pages or self-made directory listings (PHP >= 4.3.3)

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

where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE']. 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...]  For both error and directory listing pages the original URI and translated URI are in the variables$_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED']. ### Note about nsapi_virtual() and subrequests (PHP >= 4.3.3) 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!!! ## CGI and command line setups By default, PHP is built as both a CLI and CGI program, which can be used for CGI processing. If you are running a web server that 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 A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such attacks. ### Testing If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later. ### Using Variables 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'. ## HP-UX specific installation notes 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 ## OpenBSD installation notes This section contains notes and hints specific to installing PHP on » OpenBSD 3.6. ### Using Binary Packages 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 #1 OpenBSD Package Install Example # pkg_add php4-core-4.3.8.tgz # /usr/local/sbin/phpxs -s # cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini (add in mysql) # pkg_add php4-mysql-4.3.8.tgz # /usr/local/sbin/phpxs -a mysql (add in imap) # pkg_add php4-imap-4.3.8.tgz # /usr/local/sbin/phpxs -a imap (remove mysql as a test) # pkg_delete php4-mysql-4.3.8 # /usr/local/sbin/phpxs -r mysql (install the PEAR libraries) # pkg_add php4-pear-4.3.8.tgz Read the » packages(7) manual page for more information about binary packages on OpenBSD. ### Using Ports 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. ### Common Problems • 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 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). ## Solaris specific installation tips This section contains notes and hints specific to installing PHP on Solaris systems. ### Required software 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. For unpacking the PHP distribution you need • tar • gzip or • bzip2 For compiling PHP you need • gcc (recommended, other C compilers may work) • make • GNU sed For building extra extensions or hacking the code of PHP you might also need • flex (up to PHP 5.2) • re2c • bison • m4 • autoconf • automake In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL. ### Using Packages You can simplify the Solaris install process by using pkgadd to install most of your needed components. The Image Packaging System (IPS) for Solaris 11 Express also contains most of the required components for installation using the pkg command. ## Debian GNU/Linux installation notes This section contains notes and hints specific to installing PHP on » Debian GNU/Linux. Warning Unofficial builds from third-parties are not supported here. Any bugs should be reported to the Debian team unless they can be reproduced using the latest builds from our » download area. While the instructions for building PHP on Unix apply to Debian as well, this manual page contains specific information for other options, such as using either the apt-get or aptitude commands. This manual page uses these two commands interchangeably. ### Using APT First, note that other related packages may be desired like libapache2-mod-php5 to integrate with Apache 2, and php-pear for PEAR. Second, before installing a package, it's wise to ensure the package list is up to date. Typically, this is done by running the command apt-get update. Example #1 Debian Install Example with Apache 2 # apt-get install php5-common libapache2-mod-php5 php5-cli APT will automatically install the PHP 5 module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example: Example #2 Stopping and starting Apache once PHP is installed # /etc/init.d/apache2 stop # /etc/init.d/apache2 start ### Better control of configuration In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt-get command. Example #3 Methods for listing additional PHP 5 packages # apt-cache search php5 # aptitude search php5 # aptitude search php5 |grep -i mysql The examples will show a lot of packages including several PHP specific ones like php5-cgi, php5-cli and php5-dev. Determine which are needed and install them like any other with either apt-get or aptitude. And because Debian performs dependency checks, it'll prompt for those so for example to install MySQL and cURL: Example #4 Install PHP with MySQL, cURL # apt-get install php5-mysql php5-curl APT will automatically add the appropriate lines to the different php.ini related files like /etc/php5/apache2/php.ini, /etc/php5/conf.d/pdo.ini, etc. and depending on the extension will add entries similar to extension=foo.so. However, restarting the web server (like Apache) is required before these changes take affect. ### Common Problems • If the PHP scripts are not parsing via the web server, then it's likely that PHP was not added to the web server's configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details. • If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation. • There are two basic commands for installing packages on Debian (and other linux variants): apt-get and aptitude. However, explaining the subtle differences between these commands goes beyond the scope of this manual. # Installation on Mac OS X ## Table of Contents This section contains notes and hints specific to installing PHP on Mac OS X. PHP is bundled with Macs, and compiling is similar to the Unix installation guide. ## Using Packages 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: ## Using the bundled PHP 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: 1. Locate and open the Apache configuration file. By default, the location is as follows: /private/etc/apache2/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 /private/etc/apache2/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key. Note: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP and Apache. As such, the Apache configuration file on legacy machines may be /etc/httpd/httpd.conf. 2. 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 php5_module libexec/httpd/libphp5.so # AddModule mod_php5.c  Notice the location/path. When building PHP in the future, the above files should be replaced or commented out. 3. 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_php5.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>  Note: Before OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which case the above instructions will differ slightly by changing 5's to 4's. 4. 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. 5. 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. 6. 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 7. 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(); ?>  8. 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. ## Compiling PHP on Mac OS X Use the Unix installation guide to compile PHP on Mac OS X. # Installation on Windows systems ## Table of Contents 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. Note: Windows 98/Me/NT4 is no longer supported as of PHP 5.3.0. Note: Windows 95 is no longer supported as of PHP 4.3.0. If you have a development environment such as 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. ## Manual Installation Steps This section contains instructions for manually installing and configuring PHP on Microsoft Windows. ### Selecting and downloading the PHP distribution package Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are several different versions of the zip package - choose the version that is suitable for the web server being used: • If PHP is used with IIS then choose PHP 5.3 VC9 Non Thread Safe or PHP 5.2 VC6 Non Thread Safe; • If PHP is used with IIS7 or greater and PHP 5.3+, then the VC9 binaries of PHP should be used. • If PHP is used with Apache 1 or Apache 2 then choose PHP 5.3 VC6 or PHP 5.2 VC6. Note: VC9 Versions are compiled with the Visual Studio 2008 compiler and have improvements in performance and stability. The VC9 versions require you to have the » Microsoft 2008 C++ Runtime (x86) or the » Microsoft 2008 C++ Runtime (x64) installed. ### The PHP package structure and content Unpack the content of the zip archive into a directory of your choice, for example C:\PHP\. The directory and file structure extracted from the zip will look as below: Example #1 PHP 5 package structure  c:\php | +--dev | | | |-php5ts.lib -- php5.lib in non thread safe version | +--ext -- extension DLLs for PHP | | | |-php_bz2.dll | | | |-php_cpdf.dll | | | |-... | +--extras -- empty | +--pear -- initial copy of PEAR | | |-go-pear.bat -- PEAR setup script | |-... | |-php-cgi.exe -- CGI executable | |-php-win.exe -- executes scripts without an opened command prompt | |-php.exe -- Command line PHP executable (CLI) | |-... | |-php.ini-development -- default php.ini settings | |-php.ini-production -- recommended php.ini settings | |-php5apache2_2.dll -- does not exist in non thread safe version | |-php5apache2_2_filter.dll -- does not exist in non thread safe version | |-... | |-php5ts.dll -- core PHP DLL ( php5.dll in non thread safe version) | |-...  Below is the list of the modules and executables included in the PHP zip distribution: • go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details. • php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI. • php-win.exe - the PHP executable for executing PHP scripts without using a command line window (for example PHP applications that use Windows GUI). • php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI). • php5apache2_2.dll - Apache 2.2.X module. • php5apache2_2_filter.dll - Apache 2.2.X filter. ### Changing the php.ini file After the php package content has been extracted, copy the php.ini-production into php.ini in the same folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that will require additional configuration steps as described in PHP Configuration. The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in. Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these are optional. There are many other directives that may be relevant to your environment - refer to the list of php.ini directives for more information. Required directives: • extension_dir = <path to extension directory> - The extension_dir needs to point to the directory where PHP extensions files are stored. The path can be absolute (i.e. "C:\PHP\ext") or relative (i.e. ".\ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir. • extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding "extension=" directive that tells PHP which extensions in the extension_dir to load at startup time. • log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a service (i.e. syslog) and works in conjunction with the error_log directive below. When running under IIS, the log_errors should be enabled, with a valid error_log. • error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative path to the file where PHP errors should be logged. This file needs to be writable for the web server. The most common places for this file are in various TEMP directories, for example "C:\inetpub\temp\php-errors.log". • cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security facility required by many other web servers. However, enabling it under IIS will cause the PHP engine to fail on Windows. • cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI implementation needs this set. • fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. • fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any messages of any class are treated by FastCGI as error conditions which will cause IIS to generate an HTTP 500 exception. Optional directives • max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend executing any given script. The default for this is 30 seconds. Increase the value of this directive if PHP application take long time to execute. • memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The default is 128, which is fine for most PHP applications. Some of the more complex ones might need more. • display_errors = Off - This directive tells PHP whether to include any error messages in the stream that it returns to the Web server. If this is set to "On", then PHP will send whichever classes of errors that you define with the error_reporting directive back to web server as part of the error stream. For security reasons it is recommended to set it to "Off" on production servers in order not to reveal any security sensitive information that is often included in the error messages. • open_basedir = <paths to directories, separated by semicolon>, e.g. openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". This directive specified the directory paths where PHP is allowed to perform file system operations. Any file operation outside of the specified paths will result in an error. This directive is especially useful for locking down the PHP installation in shared hosting environments to prevent PHP scripts from accessing any files outside of the web site's root directory. • upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an uploaded file and post data respectively. The values of these directives should be increased if PHP applications need to perform large uploads, such as for example photos or video files. 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. In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script. See Command Line PHP on Microsoft Windows for further details. ## Microsoft IIS This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS). ## Microsoft IIS 5.1 and IIS 6.0 This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later. ### Configuring IIS to process PHP requests Download and install PHP in accordance to the instructions described in manual installation steps Note: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases. Configure the CGI- and FastCGI-specific settings in php.ini file as shown below: Example #1 CGI and FastCGI settings in php.ini fastcgi.impersonate = 1 fastcgi.logging = 0 cgi.fix_pathinfo=1 cgi.force_redirect = 0 Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform. Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file. Example #2 Configuring FastCGI extension to handle PHP requests cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^ -extension:php -path:"C:\PHP\php-cgi.exe"  This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests. Note: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS. ### Impersonation and file system access It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site. For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those. To determine which user account is used by IIS anonymous authentication, follow these steps: 1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok"; 2. Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties"; 3. Click the "Directory Security" tab; 4. Take note of a "User name:" field in the "Authentication Methods" dialog To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command. Example #3 Configuring file access permissions icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)  ### Set index.php as a default document in IIS The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps: 1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok"; 2. Right-click on the "Web Sites" node in the tree view and select "Properties"; 3. Click the "Documents" tab; 4. Click the "Add..." button and enter "index.php" for the "Default content page:". ### FastCGI and PHP Recycling configuration Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS. Example #4 Configuring FastCGI and PHP recycling cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -InstanceMaxRequests:10000 cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000  ### Configuring FastCGI timeout settings Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings. Example #5 Configuring FastCGI timeout settings cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -ActivityTimeout:90 cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -RequestTimeout:90  ### Changing the Location of php.ini file PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable. Example #6 Changing the location of php.ini file cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -EnvironmentVars:PHPRC:"C:\Some\Directory\"  ## Microsoft IIS 7.0 and later This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0. ### Enabling FastCGI support in IIS FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used. To enable FastCGI support on Windows Vista SP1 and Windows 7: 1. In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok"; 2. In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox; 3. Click OK and wait until the installation is complete. To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2: 1. In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok"; 2. If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles"; 3. If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group; 4. Click "Next" and then "Install" and wait for the installation to complete. ### Configuring IIS to process PHP requests Download and install PHP in accordance to the instructions described in manual installation steps Note: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases. Configure the CGI- and FastCGI-specific settings in php.ini file as shown below: Example #1 CGI and FastCGI settings in php.ini fastcgi.impersonate = 1 fastcgi.logging = 0 cgi.fix_pathinfo=1 cgi.force_redirect = 0 Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool. #### Using IIS Manager user interface to create a handler mapping for PHP Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface: 1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok"; 2. In the IIS Manager user interface select the server node in the "Connections" tree view; 3. In the "Features View" page open the "Handler Mappings" feature; 4. In the "Actions" pane click "Add Module Mapping..."; 5. In the "Add Module Mapping" dialog enter the following: • Request path: *.php • Module: FastCgiModule • Executable: C:\[Path to PHP installation]\php-cgi.exe • Name: PHP_via_FastCGI 6. Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder; 7. Click OK on all the dialogs to save the configuration. #### Using command line tool to create a handler mapping for PHP Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file. Example #2 Creating IIS FastCGI process pool %windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^ /+[fullPath='c:\PHP\php-cgi.exe']  Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file. Example #3 Creating handler mapping for PHP requests %windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^ /+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^ scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']  This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module. Note: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS. ### Impersonation and file system access It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site. For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those. To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute. Example #4 Determining the account used as IIS anonymous identity %windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^ /section:anonymousAuthentication <system.webServer> <security> <authentication> <anonymousAuthentication enabled="true" userName="IUSR" /> </authentication> </security> </system.webServer>  Note: If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site. To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command. Example #5 Configuring file access permissions icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)  ### Set index.php as a default document in IIS The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command: Example #6 Set index.php as a default document in IIS %windir%\system32\inetsrv\appcmd.exe set config ^ -section:system.webServer/defaultDocument /+"files.[value='index.php']" ^ /commit:apphost  ### FastCGI and PHP Recycling configuration Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS. Example #7 Configuring FastCGI and PHP recycling %windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^ /[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000 %windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^ /+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^ [name='PHP_FCGI_MAX_REQUESTS',value='10000']"  ### FastCGI timeout settings Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file. Example #8 Configuring FastCGI timeout settings %windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^ /[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90" /commit:apphost %windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^ /[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90" /commit:apphost  ### Changing the Location of php.ini file PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable. Example #9 Changing the location of php.ini file appcmd.exe set config -section:system.webServer/fastCgi ^ /+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^ [name='PHPRC',value='C:\Some\Directory\']" /commit:apphost  ## Apache 1.3.x on Microsoft Windows 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 should be converted to forward slashes: c:/directory/file.ext. A trailing slash may also be necessary for directories. ### Installing as an Apache module You should add the following lines to your Apache httpd.conf file: Example #1 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: # Add to the end of the LoadModule section # Don't forget to copy this file from the sapi directory! LoadModule php4_module "C:/php/php4apache.dll" # Add to the end of the AddModule section AddModule mod_php4.c For PHP 5: # Add to the end of the LoadModule section LoadModule php5_module "C:/php/php5apache.dll" # Add to the end of the AddModule section AddModule mod_php5.c For both: # Add this line inside the <IfModule mod_mime.c> conditional brace AddType application/x-httpd-php .php # For syntax highlighted .phps files, also add AddType application/x-httpd-php-source .phps ### Installing as a CGI binary 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: Example #2 PHP and Apache 1.3.x as CGI ScriptAlias /php/ "c:/php/" AddType application/x-httpd-php .php # For PHP 4 Action application/x-httpd-php "/php/php.exe" # For PHP 5 Action application/x-httpd-php "/php/php-cgi.exe" # specify the directory where php.ini is SetEnv PHPRC C:/php Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP. Warning A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such 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'); ?>. ## Apache 2.x on Microsoft Windows This section contains notes and hints specific to Apache 2.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! Note: Apache 2.2 Support Users of Apache 2.2 should note that the DLL file for Apache 2.2 is named php5apache2_2.dll rather than php5apache2.dll and is available only for PHP 5.2.0 and later. See also » http://snaps.php.net/ You are strongly encouraged to consult the » Apache Documentation to get a basic understanding of the Apache 2.x Server. Also consider reading the » Windows specific notes for Apache 2.x before reading on here. Apache 2.x is designed to run on the Windows version designated as server platforms, such as Windows NT 4.0, Windows 2000, Windows XP, or Windows 7. While Apache 2.x works tolerably well on Windows 9x, support on these platforms is incomplete, and some things will not work correctly. There is no plan to remedy this situation. Download the most recent version of » Apache 2.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 three ways to set up PHP to work with Apache 2.x on Windows. You can run PHP as a handler, as a CGI, or under FastCGI. Note: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext should be converted to forward slashes: c:/directory/file.ext. A trailing slash may also be necessary for directories. ### Installing as an Apache handler You need to insert the following lines into your Apache httpd.conf configuration file to load the PHP module for Apache 2.x: Example #1 PHP and Apache 2.x as handler # LoadModule php5_module "c:/php/php5apache2.dll" AddHandler application/x-httpd-php .php # configure the path to php.ini PHPIniDir "C:/php" Note: Remember to substitute your actual path to PHP for the C:/php/ in the above examples. Take care to use either php5apache2.dll or php5apache2_2.dll in your LoadModule directive and verify that the referenced file is in fact located at the file path that you point to in this directive. The above configuration will enable PHP handling of any file that has a .php extension, even if there are other file extensions. For example, a file named example.php.txt will be executed by the PHP handler. To ensure that only files that end in .php are executed, use the following configuration instead: <FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>

### Running PHP as CGI

You should consult the » Apache CGI documentation for a more complete understanding of running CGI on Apache.

To run PHP as CGI, you'll need to place your php-cgi files in a directory designated as a CGI directory using the ScriptAlias directive.

You will then need to insert a #! line in the PHP files, pointing to the location of your PHP binary:

Example #2 PHP and Apache 2.x as CGI

#!C:/php/php.exe
<?php
phpinfo();
?>


Warning

A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such attacks.

### Running PHP under FastCGI

Running PHP under FastCGI has a number of advantages over running it as a CGI. Setting it up this way is fairly straightforward:

Obtain mod_fcgid from » http://httpd.apache.org/mod_fcgid/. Win32 binaries are available for download from that site. Install the module according to the instructions that will come with it.

Configure your web server as shown below, taking care to adjust any paths to reflect your how you have installed things on your particular system:

Example #3 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so

# Where is your php.ini file?
FcgidInitialEnv PHPRC        "c:/php"

FcgidWrapper "c:/php/php-cgi.exe" .php

Files with a .php extension will now be executed by the PHP FastCGI wrapper.

## Sun, iPlanet and Netscape servers on Microsoft Windows

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.

### CGI setup on Sun, iPlanet and Netscape servers

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

### NSAPI setup on Sun, iPlanet and Netscape servers

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"]

(PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.

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

(PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

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

After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

• 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 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  ### Special use for error pages or self-made directory listings (PHP >= 4.3.3) 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...]  where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with$_SERVER['ERROR_TYPE'].

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

For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and$_SERVER['PATH_TRANSLATED'].

### Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

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"

where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

You can check the status by using the phpinfo() function.

Note:

But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!

## Sambar Server on Microsoft Windows

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

Example #1 ISAPI configuration of Sambar

#for PHP 4
*.php = c:\php\php4isapi.dll

#for PHP 5
*.php = c:\php\php5isapi.dll

(This line assumes that PHP was installed in c:\php.)

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

## Xitami on Microsoft Windows

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.

Note: 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 A server deployed in CGI mode is open to several possible vulnerabilities. Please read our CGI security section to learn how to defend yourself from such 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. ## Building from source This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Installation on Unix systems. See the Wiki documentation at: » http://wiki.php.net/internals/windows/stepbystepbuild ## Installation of extensions on Windows 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: extension_dir = C:\php\extensions • 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 #1 Enable Bzip2 extension for PHP-Windows // change the following line from ... ;extension=php_bz2.dll // ... to extension=php_bz2.dll • 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. 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_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_dba.dll DBA: DataBase (dbm-style) Abstraction layer functions None php_dbase.dll dBase functions None php_dbx.dll dbx functions php_domxml.dll PHP 4 domxml 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 functions Requires: Ingres 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_overload.dll PHP 4 Object overloading functions Built in since PHP 4.3.0, removed as of PHP 5.0.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 ## Command Line PHP on Microsoft Windows This section contains notes and hints specific to getting PHP running from the command line for Windows. Note: You should read the manual installation steps first! Getting PHP to run from the command line can be performed without making any changes to Windows. C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3  But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence. Note: Both PATH and PATHEXT are important pre-existing system variables in Windows, and care should be taken to not overwrite either variable, only to add to them. • Append the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry. • Append the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable. Note: The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name. • Associate the .PHP extension with a file type. This is done by running the following command: assoc .php=phpfile  • Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command: ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2  Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing. The example below details some of the registry changes that can be made manually. Example #1 Registry changes Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php] @="phpfile" "Content Type"="application/php" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile] @="PHP Script" "EditFlags"=dword:00000000 "BrowserFlags"=dword:00000008 "AlwaysShowExt"="" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon] @="C:\\PHP5\\php-win.exe,0" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell] @="Open" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open] @="&Open" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command] @="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"  With these changes the same command can be written as: "C:\PHP Scripts\script" -arg1 -arg2 -arg3  or, if your "C:\PHP Scripts" path is in the PATH environment variable: script -arg1 -arg2 -arg3  Note: There is a small problem if you intend to use this technique and use your PHP scripts as a command line filter, like the example below: dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3  or dir | script -arg1 -arg2 -arg3  You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change. Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer] "InheritConsoleHandles"=dword:00000001  Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788. # Installation on Cloud Computing platforms ## Table of Contents PHP installs on the cloud. To the PHP cloud! ## Microsoft Azure PHP installs on the » Azure cloud platform. See also the » Azure SDK for PHP. ## Amazon EC2 PHP installs on the » EC2 cloud platform. See also the » AWS SDK for PHP. # FastCGI Process Manager (FPM) ## Table of Contents FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites. These features include: • advanced process management with graceful stop/start; • ability to start workers with different uid/gid/chroot/environment, listening on different ports and using different php.ini (replaces safe_mode); • stdout and stderr logging; • emergency restart in case of accidental opcode cache destruction; • accelerated upload support; • "slowlog" - logging scripts (not just their names, but their PHP backtraces too, using ptrace and similar things to read remote process' execute_data) that are executed unusually slow; • fastcgi_finish_request() - special function to finish request and flush all data while continuing to do something time-consuming (video converting, stats processing etc.); • dynamic/static child spawning; • basic SAPI status info (similar to Apache mod_status); • php.ini-based config file. ## Installation ### Compiling from sources In order to enable FPM in your PHP build you need to add --enable-fpm to your configure line. There are several other FPM-specific configure options (all of them optional): • --with-fpm-user - set FPM user (default - nobody). • --with-fpm-group - set FPM group (default - nobody). ## Configuration FPM uses php.ini syntax for its configuration file - php-fpm.conf, and pool configuration files. ### List of global php-fpm.conf directives pid string Path to PID file. Default value: none. error_log string Path to error log file. Default value: #INSTALL_PREFIX#/log/php-fpm.log. log_level string Error log level. Possible values: alert, error, warning, notice, debug. Default value: notice. emergency_restart_threshold int If this number of child processes exit with SIGSEGV or SIGBUS within the time interval set by emergency_restart_interval then FPM will restart. A value of 0 means 'Off'. Default value: 0 (Off). emergency_restart_interval mixed Interval of time used by emergency_restart_interval to determine when a graceful restart will be initiated. This can be useful to work around accidental corruptions in an accelerator's shared memory. Available Units: s(econds), m(inutes), h(ours), or d(ays). Default Unit: seconds. Default value: 0 (Off). process_control_timeout mixed Time limit for child processes to wait for a reaction on signals from master. Available units: s(econds), m(inutes), h(ours), or d(ays) Default Unit: seconds. Default value: 0. daemonize boolean Send FPM to background. Set to 'no' to keep FPM in foreground for debugging. Default value: yes. ### List of pool directives With FPM you can run several pools of processes with different setting. These are settings that can be tweaked per pool. listen string The address on which to accept FastCGI requests. Valid syntaxes are: 'ip.add.re.ss:port', 'port', '/path/to/unix/socket'. This option is mandatory for each pool. listen.backlog int Set listen(2) backlog. A value of '-1' means unlimited. Default value: -1. listen.allowed_clients string List of ipv4 addresses of FastCGI clients which are allowed to connect. Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original PHP FastCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address must be separated by a comma. If this value is left blank, connections will be accepted from any ip address. Default value: any. listen.owner string Set permissions for unix socket, if one is used. In Linux, read/write permissions must be set in order to allow connections from a web server. Many BSD-derived systems allow connections regardless of permissions. Default values: user and group are set as the running user, mode is set to 0666. listen.group string See listen.owner. listen.mode string See listen.owner. user string Unix user of FPM processes. This option is mandatory. group string Unix group of FPM processes. If not set, the default user's group is used. pm string Choose how the process manager will control the number of child processes. Possible values: static, ondemand, dynamic. This option is mandatory. static - the number of child processes is fixed (pm.max_children). ondemand - the processes spawn on demand (when requested, as opposed to dynamic, where pm.start_servers are started when the service is started. dynamic - the number of child processes is set dynamically based on the following directives: pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers. pm.max_children int The number of child processes to be created when pm is set to static and the maximum number of child processes to be created when pm is set to dynamic. This option is mandatory. This option sets the limit on the number of simultaneous requests that will be served. Equivalent to the ApacheMaxClients directive with mpm_prefork and to the PHP_FCGI_CHILDREN environment variable in the original PHP FastCGI. pm.start_servers int The number of child processes created on startup. Used only when pm is set to dynamic. Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2. pm.min_spare_servers int The desired minimum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case. pm.max_spare_servers int The desired maximum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case. pm.max_requests int The number of requests each child process should execute before respawning. This can be useful to work around memory leaks in 3rd party libraries. For endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS. Default value: 0. pm.status_path string The URI to view the FPM status page. If this value is not set, no URI will be recognized as a status page. Default value: none. ping.path string The ping URI to call the monitoring page of FPM. If this value is not set, no URI will be recognized as a ping page. This could be used to test from outside that FPM is alive and responding. Please note that the value must start with a leading slash (/). ping.response string This directive may be used to customize the response to a ping request. The response is formatted as text/plain with a 200 response code. Default value: pong. request_terminate_timeout mixed The timeout for serving a single request after which the worker process will be killed. This option should be used when the 'max_execution_time' ini option does not stop script execution for some reason. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0. request_slowlog_timeout mixed The timeout for serving a single request after which a PHP backtrace will be dumped to the 'slowlog' file. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0. slowlog string The log file for slow requests. Default value: #INSTALL_PREFIX#/log/php-fpm.log.slow. rlimit_files int Set open file descriptor rlimit. Default value: system defined value. rlimit_core int Set max core size rlimit. Possible Values: 'unlimited' or an integer greater or equal to 0. Default value: system defined value. chroot string Chroot to this directory at the start. This value must be defined as an absolute path. When this value is not set, chroot is not used. chdir string Chdir to this directory at the start. This value must be an absolute path. Default value: current directory or / when chroot. catch_workers_output boolean Redirect worker stdout and stderr into main error log. If not set, stdout and stderr will be redirected to /dev/null according to FastCGI specs. Default value: no. It's possible to pass additional environment variables and update PHP settings of a certain pool. To do this, you need to add the following options to the pool configuration file. Example #1 Passing environment variables and PHP settings to a pool env[HOSTNAME] =$HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_flag[display_errors] = off
php_admin_value[memory_limit] = 32M
PHP settings passed with php_value or php_flag will overwrite their previous value. Please note that defining disable_functions or disable_classes will not overwrite previously defined php.ini values, but will append the new value instead.

As of 5.3.3, PHP settings are also possible to be set in webserver.

Example #2 set PHP settings in nginx.conf

set $php_value "pcre.backtrack_limit=424242"; set$php_value "$php_value \n pcre.recursion_limit=99999"; fastcgi_param PHP_VALUE$php_value;

fastcgi_param  PHP_ADMIN_VALUE "open_basedir=/var/www/htdocs";
Caution

Because these settings are passed to php-fpm as fastcgi headers, php-fpm should not be bound to a worldwide accessible address. Otherwise, anyone could alter the PHP configuration options. See also listen.allowed_clients.

# Installation of PECL extensions

## Introduction to PECL Installations

» 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 the 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 Git Instructions for details on the required tools, and required versions.

• The pecl install extname command downloads the extensions code automatically, so in this case there is no need for a separate download.
• 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.
• SVN Most PECL extensions also reside in SVN. A web-based view may be seen at » http://svn.php.net/viewvc/pecl/. To download straight from SVN, the following sequence of commands may be used:

$svn checkout http://svn.php.net/repository/pecl/extname/trunk extname • Windows downloads At this time the PHP project does not compile Windows binaries for PECL extensions. However, to compile PHP under Windows see the chapter titled building PHP for Windows. ## Installing a PHP extension on Windows On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way. To load an extension, you need to have it available as a ".dll" file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download). To compile an extension into PHP, please refer to building from source documentation. To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension. ### Where to find an extension? PHP extensions are usually called "php_*.dll" (where the star represents the name of the extension) and they are located under the "PHP\ext" ("PHP\extensions" in PHP 4) folder. PHP ships with the extensions most useful to the majority of developers. They are called "core" extensions. However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions. If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read http://pecl.php.net/package-new.php. ### Which extension to download? Many times, you will find several versions of each DLL: • Different version numbers (at least the first two numbers should match) • Different thread safety settings • Different processor architecture (x86, x64, ...) • Different debugging settings • etc. You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings: Example #1 phpinfo() call  <?phpphpinfo();?>  Or from the command line, run: drive:\\path\to\php\executable\php.exe -i  ### Loading an extension The most common way to load a PHP extension is to include it in your php.ini configuration file. Please note that many extensions are already present in your php.ini and that you only need to remove the semicolon to activate them. ;extension=php_extname.dll  extension=php_extname.dll  However, some web servers are confusing because they do not use the php.ini located alongside your PHP executable. To find out where your actual php.ini resides, look for its path in phpinfo(): Configuration File (php.ini) Path C:\WINDOWS  Loaded Configuration File C:\Program Files\PHP\5.2\php.ini  After activating an extension, save php.ini, restart the web server and check phpinfo() again. The new extension should now have its own section. ### Resolving problems If the extension does not appear in phpinfo(), you should check your logs to learn where the problem comes from. If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen. If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself. Common problems are the location of the DLL, the value of the " extension_dir" setting inside php.ini and compile-time setting mismatches. If the problem lies in a compile-time setting mismatch, you probably didn't download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help. ## Compiling shared PECL extensions with the pecl command PECL makes it easy to create shared PHP extensions. Using the » pecl command, do the following:$ pecl install extname

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

Note:

After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.

## Compiling shared PECL extensions with phpize

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

## php-config

php-config is a simple shell script for obtaining information about the installed PHP configuration.

When compiling extensions, if you have multiple PHP versions installed, you may specify for which installation you'd like to build by using the --with-php-config option during configuration, specifying the path of the respective php-config script.

The list of command line options provided by the php-config script can be queried anytime by running php-config with the -h switch:

Usage: /usr/local/bin/php-config [OPTION]
Options:
--prefix            [...]
--includes          [...]
--ldflags           [...]
--libs              [...]
--extension-dir     [...]
--include-dir       [...]
--php-binary        [...]
--php-sapis         [...]
--configure-options [...]
--version           [...]
--vernum            [...]


Command line options
Option Description
--prefix Directory prefix where PHP is installed, e.g. /usr/local
--includes List of -I options with all include files
--ldflags LD Flags which PHP was compiled with
--libs Extra libraries which PHP was compiled with
--extension-dir Directory where extensions are searched by default
--include-dir Directory prefix where header files are installed by default
--php-binary Full path to php CLI or CGI binary
--php-sapis Show all SAPI modules available
--configure-options Configure options to recreate configuration of current PHP installation
--version PHP version
--vernum PHP version as integer

## Compiling PECL extensions statically into PHP

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

# Problems?

Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.

## Other problems

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.

## Bug reports

If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at » http://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!

# Runtime Configuration

## The configuration file

The configuration file (php.ini) 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 versions, it happens on every invocation.

php.ini is searched for 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 location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] and [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in any of these keys, the first one found will be used as the location of the php.ini (Windows only).
• [HKEY_LOCAL_MACHINE\SOFTWARE\PHP], value of IniFilePath (Windows only).
• 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 the SAPI in use, so, for example, php-cli.ini or php-apache.ini), it is used instead of php.ini. The SAPI name can be determined with 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.

Using environment variables can be used in php.ini as shown below.

Example #1 php.ini Environment Variables

; PHP_MEMORY_LIMIT is taken from environment
memory_limit = ${PHP_MEMORY_LIMIT} The php.ini directives handled by extensions are documented on the respective pages of the extensions themselves. A list of the core directives is available in the appendix. Not all PHP directives are necessarily documented in this manual: for a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find » the latest php.ini from Git helpful too. Example #2 php.ini example ; any text on a line after an unquoted semicolon (;) is ignored [php] ; section markers (text within square brackets) are also ignored ; Boolean values can be set to either: ; true, on, yes ; or false, off, no, none register_globals = off track_errors = yes ; you can enclose strings in double-quotes include_path = ".:/usr/local/lib/php" ; backslashes are treated the same as any other character include_path = ".;c:\php\lib" 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".

## .user.ini files

Since PHP 5.3.0, PHP includes support for configuration INI files on a per-directory basis. These files are processed only by the CGI/FastCGI SAPI. This functionality obsoletes the PECL htscanner extension. If you are using Apache, use .htaccess files for the same effect.

In addition to the main php.ini file, PHP scans for INI files in each directory, starting with the directory of the requested PHP file, and working its way up to the current document root (as set in $_SERVER['DOCUMENT_ROOT']). In case the PHP file is outside the document root, only its directory is scanned. Only INI settings with the modes PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files. Two new INI directives, user_ini.filename and user_ini.cache_ttl control the use of user INI files. user_ini.filename sets the name of the file PHP looks for in each directory; if set to an empty string, PHP doesn't scan at all. The default is .user.ini. user_ini.cache_ttl controls how often user INI files are re-read. The default is 300 seconds (5 minutes). ## Where a configuration setting may be set These modes determine when and where a PHP directive may or may not be set, and each directive within the manual refers to one of these modes. For example, some settings may be set within a PHP script using ini_set(), whereas others may require php.ini or httpd.conf. For example, the output_buffering setting is PHP_INI_PERDIR therefore it may not be set using ini_set(). However, the display_errors directive is PHP_INI_ALL therefore it may be set anywhere, including with ini_set(). Definition of PHP_INI_* modes Mode Meaning PHP_INI_USER Entry can be set in user scripts (like with ini_set()) or in the Windows registry. Since PHP 5.3, entry can be set in .user.ini PHP_INI_PERDIR Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3) PHP_INI_SYSTEM Entry can be set in php.ini or httpd.conf PHP_INI_ALL Entry can be set anywhere ## How to change configuration settings ### Running PHP as an Apache module 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. 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. php_value name value Sets 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. php_flag name on|off Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. php_admin_value name value Sets 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 ini_set(). To clear a previously set value use none as the value. php_admin_flag name on|off Used 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 ini_set(). Example #1 Apache configuration example <IfModule mod_php5.c> php_value include_path ".:/usr/local/lib/php" php_admin_flag engine on </IfModule> <IfModule mod_php4.c> php_value include_path ".:/usr/local/lib/php" php_admin_flag engine on </IfModule> 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 ### Changing PHP configuration via the Windows registry 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. ### Other interfaces to PHP 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(). # Language Reference # Basic syntax ## Table of Contents ## PHP tags When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> 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. PHP also allows for short open tags <? and ?> (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.  <?phpecho "Hello world";// ... more codeecho "Last statement";// the script ends here with no PHP closing tag  ## Escaping from HTML Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents, for example to create templates.  <p>This is going to be ignored by PHP and displayed by the browser.</p><?php echo 'While this is going to be parsed.'; ?><p>This will also be ignored by PHP and displayed by the browser.</p>  This works as expected, because when the PHP interpreter hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation) until it hits another opening tag unless in the middle of a conditional statement in which case the interpreter will determine the outcome of the conditional before making a decision of what which to skip over. See the next example. Using structures with conditions Example #1 Advanced escaping using conditions  <?php if ($expression == true): ?>  This will show if the expression is true.<?php else: ?>  Otherwise this will show.<?php endif; ?> 
In this example PHP will skip the blocks where the condition is not met, even though they are outside of the PHP open/close tags, PHP skips them according to the condition since the PHP interpreter will jump over blocks contained within a condition what is not met.

For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print.

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 #2 PHP Opening and Closing Tags

 1.  <?php echo 'if you want to serve XHTML or XML documents, do it like this'; ?>2.  <script language="php">        echo 'some editors (like FrontPage) don\'t              like processing instructions';    </script>3.  <? echo 'this is the simplest, an SGML processing instruction'; ?>    <?= expression ?> This is a shortcut for "<? echo expression ?>"4.  <% echo 'You may optionally use ASP-style tags'; %>    <%= $variable; # This is a shortcut for "<% echo . . ." %>  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. ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive. 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. Note: In PHP 5.2 and earlier, the parser does not allow the <?php opening tag to be the only thing in a file. This is allowed as of PHP 5.3 provided there are one or more whitespace characters after the opening tag. Note: Starting with PHP 5.4, short echo tag <?= is always recognized and valid, regardless of the short_open_tag setting. ## Instruction separation 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. ## Comments 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 /* echo 'This is a test'; /* This comment will cause a problem */ */?>  # Types ## Table of Contents ## Introduction 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: And the pseudo-variable $....

Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons.

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

Note: To check the type and value of an expression, use the var_dump() function.

To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:

### Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

When converting to boolean, the following values are considered FALSE:

• the boolean FALSE itself
• the integer 0 (zero)
• the float 0.0 (zero)
• the empty string, and the string "0"
• 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

Every other value is considered TRUE (including any resource).

Warning

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

 <?phpvar_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)?> 

## Integers

An integer is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}.

### Syntax

Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).

Binary integer literals are available since PHP 5.4.0.

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

Example #1 Integer literals

 <?php$a = 1234; // decimal number$a = -123; // a negative number$a = 0123; // octal number (equivalent to 83 decimal)$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)$a = 0b11111111; // binary number (equivalent to 255 decimal)?>  Formally, the structure for integer literals is: decimal : [1-9][0-9]* | 0 hexadecimal : 0[xX][0-9a-fA-F]+ octal : 0[0-7]+ binary : 0b[01]+ integer : [+-]?decimal | [+-]?hexadecimal | [+-]?octal | [+-]?binary  The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5. Warning If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored. Example #2 Octal weirdness  <?phpvar_dump(01090); // 010 octal = 8 decimal?>  ### Integer overflow If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead. Example #3 Integer overflow on a 32-bit system  <?php$large_number = 2147483647;var_dump($large_number); // int(2147483647)$large_number = 2147483648;var_dump($large_number); // float(2147483648)$million = 1000000;$large_number = 50000 *$million;var_dump($large_number); // float(50000000000)?>  Example #4 Integer overflow on a 64-bit system  <?php$large_number = 9223372036854775807;var_dump($large_number); // int(9223372036854775807)$large_number = 9223372036854775808;var_dump($large_number); // float(9.2233720368548E+18)$million = 1000000;$large_number = 50000000000000 *$million;var_dump($large_number); // float(5.0E+19)?>  There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.  <?phpvar_dump(25/7); // float(3.5714285714286) var_dump((int) (25/7)); // int(3)var_dump(round(25/7)); // float(4) ?>  ### Converting to integer To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function. If a resource is converted to an integer, then the result will be the unique resource number assigned to the resource by PHP at runtime. See also Type Juggling. #### From booleans FALSE will yield 0 (zero), and TRUE will yield 1 (one). #### From floating point numbers 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 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens! Warning Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.  <?phpecho (int) ( (0.1+0.7) * 10 ); // echoes 7!?>  See also the warning about float precision. #### From strings #### From other types Caution The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice. ## Floating point numbers Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:  <?php$a = 1.234; $b = 1.2e3;$c = 7E-10;?> 

Formally:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})


The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

Warning

# Floating point precision

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small 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, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

For a "simple" explanation, see the » floating point guide that's also titled "Why don’t my numbers add up?"

### Converting to float

For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float.

### Comparing floats

As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations.

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

$a and$b are equal to 5 digits of precision.

 <?php$a = 1.23456789;$b = 1.23456780;$epsilon = 0.00001;if(abs($a-$b) <$epsilon) {    echo "true";}?> 

### NaN

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.

Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().

## Strings

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

Note: string can be as large as up to 2GB (2147483647 bytes maximum)

### Syntax

A string literal can be specified in four different ways:

#### Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ').

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

 <?phpecho 'this is a simple string';echo 'You can also have embedded newlines in strings this way as it isokay 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 newlineecho 'This will not expand: \n a newline';// Outputs: Variables do not $expand$eitherecho 'Variables do not $expand$either';?> 

#### Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

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)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ 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 As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

#### Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier 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 must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Example #1 Invalid example

 <?phpclass foo {    public $bar = <<<EOTbar EOT;}?>  Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings. Example #2 Heredoc string quoting example  <?php$str = <<<EODExample of stringspanning multiple linesusing heredoc syntax.EOD;/* More complex example, with variables. */class foo{    var $foo; var$bar;    function foo()    {        $this->foo = 'Foo';$this->bar = array('Bar1', 'Bar2', 'Bar3');    }}$foo = new foo();$name = 'MyName';echo <<<EOTMy name is "$name". I am printing some$foo->foo.Now, I am printing some {$foo->bar[1]}.This should print a capital 'A': \x41EOT;?>  The above example will output: My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A It is also possible to use the Heredoc syntax to pass data to function arguments: Example #3 Heredoc in arguments example  <?phpvar_dump(array(<<<EODfoobar!EOD));?>  As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax: Example #4 Using Heredoc to initialize static values  <?php// Static variablesfunction foo(){ static$bar = <<<LABELNothing in here...LABEL;}// Class properties/constantsclass foo{    const BAR = <<<FOOBARConstant exampleFOOBAR;    public $baz = <<<FOOBARProperty exampleFOOBAR;}?>  Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes: Example #5 Using double quotes in Heredoc  <?phpecho <<<"FOOBAR"Hello World!FOOBAR;?>  #### Nowdoc Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier. Example #6 Nowdoc string quoting example  <?php$str = <<<'EOD'Example of stringspanning multiple linesusing nowdoc syntax.EOD;/* More complex example, with variables. */class foo{    public $foo; public$bar;    function foo()    {        $this->foo = 'Foo';$this->bar = array('Bar1', 'Bar2', 'Bar3');    }}$foo = new foo();$name = 'MyName';echo <<<'EOT'My name is "$name". I am printing some$foo->foo.Now, I am printing some {$foo->bar[1]}.This should not print a capital 'A': \x41EOT;?>  The above example will output: My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

Note:

Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:

Example #7 Static data example

 <?phpclass foo {    public $bar = <<<'EOT'barEOT;}?>  Note: Nowdoc support was added in PHP 5.3.0. #### Variable parsing 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 embed a variable, an array value, or an object property in a string with a minimum of effort. The complex syntax can be recognised by the curly braces surrounding the expression. ##### Simple syntax 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 to explicitly specify the end of the name.

 <?php$juice = "apple";echo "He drank some$juice juice.".PHP_EOL;// Invalid. "s" is a valid character for a variable name, but the variable is $juice.echo "He drank some juice made of$juices.";?> 

The above example will output:

He drank some apple juice.
He drank some juice made of .


Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

Example #8 Simple syntax example

 <?php$juices = array("apple", "orange", "koolaid1" => "purple");echo "He drank some$juices[0] juice.".PHP_EOL;echo "He drank some $juices[1] juice.".PHP_EOL;echo "He drank some$juices[koolaid1] juice.".PHP_EOL;class people {    public $john = "John Smith"; public$jane = "Jane Smith";    public $robert = "Robert Paulsen"; public$smith = "Smith";}$people = new people();echo "$people->john drank some $juices[0] juice.".PHP_EOL;echo "$people->john then said hello to $people->jane.".PHP_EOL;echo "$people->john's wife greeted $people->robert.".PHP_EOL;echo "$people->robert greeted the two $people->smiths."; // Won't work?>  The above example will output: He drank some apple juice. He drank some orange juice. He drank some purple juice. John Smith drank some apple juice. John Smith then said hello to Jane Smith. John Smith's wife greeted Robert Paulsen. Robert Paulsen greeted the two .  For anything more complex, you should use the complex syntax. ##### Complex (curly) syntax This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions. Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the$ immediately follows the {. Use {\$to get a literal {$. Some examples to make it clear:

 <?php// Show all errorserror_reporting(E_ALL);$great = 'fantastic';// Won't work, outputs: This is { fantastic}echo "This is {$great}";// Works, outputs: This is fantasticecho "This is {$great}";echo "This is${great}";// Worksecho "This square is {$square->width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntaxecho "This works: {$arr['key']}";// Worksecho "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 only because PHP first looks for a// constant named foo; an error of level E_NOTICE (undefined constant) will be// thrown.echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays// when inside of stringsecho "This works: {$arr['foo'][3]}";// Works.echo "This works: " . $arr['foo'][3];echo "This works too: {$obj->values[3]->name}";echo "This is the value of the var named $name: {${$name}}";echo "This is the value of the var named by the return value of getName(): {${getName()}}";echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";// Won't work, outputs: This is the return value of getName(): {getName()}echo "This is the return value of getName(): {getName()}";?>  It is also possible to access class properties using variables within strings using this syntax.  <?phpclass foo { var$bar = 'I am bar.';}$foo = new foo();$bar = 'bar';$baz = array('foo', 'bar', 'baz', 'quux');echo "{$foo->$bar}\n";echo "{$foo->$baz[1]}\n";?>  The above example will output: I am bar. I am bar.  Note: Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

 <?php// Show all errors.error_reporting(E_ALL);class beers {    const softdrink = 'rootbeer';    public static $ale = 'ipa';}$rootbeer = 'A & W';$ipa = 'Alexander Keith\'s';// This works; outputs: I'd like an A & Wecho "I'd like an {${beers::softdrink}}\n";// This works too; outputs: I'd like an Alexander Keith'secho "I'd like an {${beers::$ale}}\n";?> 

#### String access and modification by character

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, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character. Note: Strings may also be accessed using braces, as in$str{42}, for the same purpose.

Warning

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NULL byte.

Warning

Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

Example #9 Some string examples

 <?php// Get the first character of a string$str = 'This is a test.';$first = $str[0];// Get the third character of a string$third = $str[2];// Get the last character of a string.$str = 'This is still a test.';$last =$str[strlen($str)-1]; // Modify the last character of a string$str = 'Look at the sea';$str[strlen($str)-1] = 'e';?> 

As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0.

Example #10 Differences between PHP 5.3 and PHP 5.4

 <?php$str = 'abc';var_dump($str['1']);var_dump(isset($str['1']));var_dump($str['1.0']);var_dump(isset($str['1.0']));var_dump($str['x']);var_dump(isset($str['x']));var_dump($str['1x']);var_dump(isset($str['1x']));?>  Output of the above example in PHP 5.3: string(1) "b" bool(true) string(1) "b" bool(true) string(1) "a" bool(true) string(1) "b" bool(true)  Output of the above example in PHP 5.4: string(1) "b" bool(true) Warning: Illegal string offset '1.0' in /tmp/t.php on line 7 string(1) "b" bool(false) Warning: Illegal string offset 'x' in /tmp/t.php on line 9 string(1) "a" bool(false) string(1) "b" bool(false)  Note: Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL. Note: PHP 5.5 added support for accessing characters within string literals using [] or {}. ### Useful functions and operators Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information. There are a number of useful functions for string manipulation. See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality. There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash). Finally, see also the character type functions. ### Converting to string A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function. A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values. An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6). Note: The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function. Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array. To view a single element, use a construction such as echo$arr['foo']. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". To print the values of object properties for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP at runtime. While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed (ie a Web request or CLI process) and won't be reused. To get a resource's type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

### String conversion to numbers

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

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

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

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

 <?phpecho "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";?>  Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters. ### Details of the String Type The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.) This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings. Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string "á" equivalent to "\xE1" (ISO-8859-1), "\xC3\xA1" (UTF-8, C form), "\x61\xCC\x81" (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicity declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic. Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions: • Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets. • Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities() and the majority of the functions in the mbstring extension. • Others use the current locale (see setlocale()), but operate byte-by-byte. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper("á") may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale. • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding. Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption. ## Arrays An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic. ### Syntax #### Specifying with array() An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments. array( key => value, key2 => value2, key3 => value3, ... ) The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end. As of PHP 5.4 you can also use the short array syntax, which replaces array() with []. Example #1 A simple array  <?php$array = array(    "foo" => "bar",    "bar" => "foo",);// as of PHP 5.4$array = [ "foo" => "bar", "bar" => "foo",];?>  The key can either be an integer or a string. The value can be of any type. Additionally the following key casts will occur: • Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer. • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8. • Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0. • Null will be cast to the empty string, i.e. the key null will actually be stored under "". • Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type. If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. Example #2 Type Casting and Overwriting example  <?php$array = array(    1    => "a",    "1"  => "b",    1.5  => "c",    true => "d",);var_dump($array);?>  The above example will output: array(1) { [1]=> string(1) "d" }  As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over. PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays. Example #3 Mixed integer and string keys  <?php$array = array(    "foo" => "bar",    "bar" => "foo",    100   => -100,    -100  => 100,);var_dump($array);?>  The above example will output: array(4) { ["foo"]=> string(3) "bar" ["bar"]=> string(3) "foo" [100]=> int(-100) [-100]=> int(100) }  The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key. Example #4 Indexed arrays without key  <?php$array = array("foo", "bar", "hello", "world");var_dump($array);?>  The above example will output: array(4) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(5) "hello" [3]=> string(5) "world" }  It is possible to specify the key only for some elements and leave it out for others: Example #5 Keys not on all elements  <?php$array = array(         "a",         "b",    6 => "c",         "d",);var_dump($array);?>  The above example will output: array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [6]=> string(1) "c" [7]=> string(1) "d" }  As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6. #### Accessing array elements with square bracket syntax Array elements can be accessed using the array[key] syntax. Example #6 Accessing array elements  <?php$array = array(    "foo" => "bar",    42    => 24,    "multi" => array(         "dimensional" => array(             "array" => "foo"         )    ));var_dump($array["foo"]);var_dump($array[42]);var_dump($array["multi"]["dimensional"]["array"]);?>  The above example will output: string(3) "bar" int(24) string(3) "foo"  Note: Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g.$array[42] and $array{42} will both do the same thing in the example above). As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable. As of PHP 5.5 it is possible to array dereference an array literal. Example #7 Array dereferencing  <?phpfunction getArray() { return array(1, 2, 3);}// on PHP 5.4$secondElement = getArray()[1];// previously$tmp = getArray();$secondElement = $tmp[1];// orlist(,$secondElement) = getArray();?> 

Note:

Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.

#### Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if$arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.

To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on 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 arrayunset($arr);    // This deletes the whole array?> 

Note:

As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero).

Note that the maximum integer key used for this need not currently exist in the array. It need only 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).$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
)


### Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Note:

The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

 <?php$a = array(1 => 'one', 2 => 'two', 3 => 'three');unset($a[2]);/* will produce an array that would have been defined as   $a = array(1 => 'one', 3 => 'three'); and NOT$a = array(1 => 'one', 2 =>'three');*/$b = array_values($a);// Now $b is array(0 => 'one', 1 =>'three')?>  The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array. ### Array do's and don'ts #### Why is$foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while$foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

 <?php$foo[bar] = 'enemy';echo$foo[bar];// etc?> 

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in the future define constants which, unfortunately for such 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. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

 <?phperror_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";}?> 

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
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
Good: 2


More examples to demonstrate this behaviour:

 <?php// Show all errorserror_reporting(E_ALL);$arr = array('fruit' => 'apple', 'veggie' => 'carrot');// Correctprint$arr['fruit'];  // appleprint $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// This defines a constant to demonstrate what's going on.  The value 'veggie'// is assigned to a constant named fruit.define('fruit', 'veggie');// Notice the difference nowprint $arr['fruit']; // appleprint$arr[fruit];    // carrot// The following is okay, as it's inside a string. Constants are not looked for// within strings, so no E_NOTICE occurs hereprint "Hello $arr[fruit]"; // Hello apple// With one exception: braces surrounding arrays within strings allows constants// to be interpretedprint "Hello {$arr[fruit]}";    // Hello carrotprint "Hello {$arr['fruit']}"; // Hello apple// This will not work, and will result 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 wellprint "Hello$arr['fruit']";print "Hello $_GET['foo']";// Concatenation is another optionprint "Hello " .$arr['fruit']; // Hello apple?> 

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

 <?phpecho $arr[somefunc($bar)];?> 

This is an example of using a function return value as the array index. PHP also knows about constants:

 <?php$error_descriptions[E_ERROR] = "A fatal error has occurred";$error_descriptions[E_WARNING] = "PHP issued a warning";$error_descriptions[E_NOTICE] = "This is just an informal notice";?>  Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:  <?php$error_descriptions[1] = "A fatal error has occurred";$error_descriptions[2] = "PHP issued a warning";$error_descriptions[8] = "This is just an informal notice";?> 

because E_ERROR equals 1, etc.

##### So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are 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. ### Converting to array For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue). If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; 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:  <?phpclass 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());?> 

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

### Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

### Examples

The array type in PHP is very versatile. Here are some examples:

 <?php// This:$a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 );$b = array('a', 'b', 'c');// . . .is completely equivalent with this:$a = array();$a['color'] = 'red';$a['taste'] = 'sweet';$a['shape'] = 'round';$a['name'] = 'apple';$a[]        = 4;        // key will be 0$b = array();$b[] = 'a';$b[] = 'b';$b[] = 'c';// After the above code is executed, $a will be the array// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', // 'name' => 'apple', 0 => 4), and$b will be the array // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').?> 

Example #8 Using array()

 <?php// Array as (property-)map$map = array( 'version' => 4, 'OS' => 'Linux', 'lang' => 'english', 'short_tags' => true ); // strictly numerical keys$array = array( 7,                8,                0,                156,                -10              );// this is the same as array(0 => 7, 1 => 8, ...)$switching = array( 10, // key = 0 5 => 6, 3 => 7, 'a' => 4, 11, // key = 6 (maximum of integer-indices was 5) '8' => 2, // key = 8 (integer!) '02' => 77, // key = '02' 0 => 12 // the value 10 will be overwritten by 12 ); // empty array$empty = array();         ?> 

Example #9 Collection

 <?php$colors = array('red', 'blue', 'green', 'yellow');foreach ($colors as $color) { echo "Do you like$color?\n";}?> 

The above example will output:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?


Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Example #10 Changing element in the loop

 <?php// PHP 5foreach ($colors as &$color) {    $color = strtoupper($color);}unset($color); /* ensure that following writes to$color will not modify the last array element */// Workaround for older versionsforeach ($colors as$key => $color) {$colors[$key] = strtoupper($color);}print_r($colors);?>  The above example will output: Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW )  This example creates a one-based array. Example #11 One-based index  <?php$firstquarter  = array(1 => 'January', 'February', 'March');print_r($firstquarter);?>  The above example will output: Array ( [1] => 'January' [2] => 'February' [3] => 'March' )  Example #12 Filling an array  <?php// fill an array with all items from a directory$handle = opendir('.');while (false !== ($file = readdir($handle))) {    $files[] =$file;}closedir($handle); ?>  Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array. Example #13 Sorting an array  <?phpsort($files);print_r($files);?>  Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays. Example #14 Recursive and multi-dimensional arrays  <?php$fruits = array ( "fruits"  => array ( "a" => "orange",                                       "b" => "banana",                                       "c" => "apple"                                     ),                  "numbers" => array ( 1,                                       2,                                       3,                                       4,                                       5,                                       6                                     ),                  "holes"   => array (      "first",                                       5 => "second",                                            "third"                                     )                );// Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second"echo$fruits["fruits"]["a"]; // prints "orange"unset($fruits["holes"][0]); // remove "first"// Create a new multi-dimensional array$juices["apple"]["green"] = "good"; ?> 

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

## Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var,$var becomes a string. If an integer value is then assigned to $var, it becomes an integer. An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both 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 and what the type of the expression itself is.  <?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.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, 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:

 <?php$a = 'car'; //$a is a string$a[0] = 'b'; //$a is still a stringecho $a; // bar?>  See the section titled String access by character for more information. ### Type Casting Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.  <?php$foo = 10;   // $foo is an integer$bar = (boolean) $foo; //$bar is a boolean?> 

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
• (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

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

 <?php$foo = (int)$bar;$foo = ( int )$bar;?> 

Casting literal strings and variables to binary strings:

 <?php$binary = (binary)$string;$binary = b"binary string";?>  Note: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.  <?php$foo = 10;            // $foo is an integer$str = "$foo"; //$str is a string$fst = (string)$foo; // $fst is also a string// This prints out that "they are the same"if ($fst === $str) { echo "they are the same";}?>  It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections: # Variables ## Table of Contents ## Basics 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 bytes from 127 through 255 (0x7f-0xff). Note:$this is a special variable that can't be assigned.

Tip

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.?>  By default, 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. PHP also 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 depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

 <?php// Unset AND unreferenced (no use context) variable; outputs NULLvar_dump($unset_var);// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)echo($unset_bool ? "true\n" : "false\n");// String usage; outputs 'string(3) "abc"'$unset_str .= 'abc';var_dump($unset_str);// Integer usage; outputs 'int(25)'$unset_int += 25; // 0 + 25 => 25var_dump($unset_int);// Float/double usage; outputs 'float(1.25)'$unset_float += 1.25;var_dump($unset_float);// Array usage; outputs array(1) {  [3]=>  string(3) "def" }$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")var_dump($unset_arr);// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }$unset_obj->foo = 'bar';var_dump($unset_obj);?> 

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.

## Predefined Variables

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 DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of$DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of$id, or $_ENV['HOME'] instead of$HOME.

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. Note: 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. ## Variable scope The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:  <?php$a = 1;include 'b.inc';?> 

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.

### The global keyword

First, an example use of global:

Example #1 Using global

 <?php$a = 1;$b = 2;function Sum(){    global $a,$b;    $b =$a + $b;} Sum();echo$b;?> 

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

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

 <?php$a = 1;$b = 2;function Sum(){    $GLOBALS['b'] =$GLOBALS['a'] + $GLOBALS['b'];} Sum();echo$b;?> 

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how$GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals: Example #3 Example demonstrating superglobals and scope  <?phpfunction test_global(){ // Most predefined variables aren't "super" and require // 'global' to be available to the functions local scope. global$HTTP_POST_VARS;        echo $HTTP_POST_VARS['name']; // Superglobals are available in any scope and do // not require 'global'. Superglobals are available // as of PHP 4.1.0, and HTTP_POST_VARS is now // deemed deprecated. echo$_POST['name'];}?> 

Note:

Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

### Using static variables

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:

Example #4 Example demonstrating need for static variables

 <?phpfunction test(){    $a = 0; echo$a;    $a++;}?>  This function is quite useless since every time it is called it sets$a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the$a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static: Example #5 Example use of static variables  <?phpfunction test(){ static$a = 0;    echo $a;$a++;}?> 

Now, $a is initialized only in first call of function and 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: Example #6 Static variables with recursive functions  <?phpfunction test(){ static$count = 0;    $count++; echo$count;    if ($count < 10) { test(); }$count--;}?> 

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.

Example #7 Declaring static variables

 <?phpfunction foo(){    static $int = 0; // correct static$int = 1+2;        // wrong  (as it is an expression)    static $int = sqrt(121); // wrong (as it is an expression too)$int++;    echo $int;}?>  Note: Static declarations are resolved in compile-time. ### References with global and static variables 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:  <?phpfunction 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);?>  The above example will output: NULL object(stdClass)(0) { } A similar behaviour applies to the static statement. References are not stored statically:  <?phpfunction &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();?>  The above example will 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. ## Variable variables Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:  <?php$a = 'hello';?> 

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

 <?php$$a = 'world';?>  At this point two variables have been defined and stored in the PHP symbol tree: a with contents "hello" and hello with contents "world". Therefore, this statement:  <?phpecho "a {a}";?>  produces the exact same output as:  <?phpecho "a hello";?>  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. Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as$foo->$bar, then the local scope will be examined for$bar and its value will be used as the name of the property of $foo. This is also true if$bar is an array access.

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

Example #1 Variable property example

 <?phpclass foo {    var $bar = 'I am bar.'; var$arr = array('I am A.', 'I am B.', 'I am C.');    var $r = 'I am r.';}$foo = new foo();$bar = 'bar';$baz = array('foo', 'bar', 'baz', 'quux');echo $foo->$bar . "\n";echo $foo->$baz[1] . "\n";$start = 'b';$end   = 'ar';echo $foo->{$start . $end} . "\n";$arr = 'arr';echo $foo->$arr[1] . "\n";echo $foo->{$arr}[1] . "\n";?> 

The above example will output:

I am bar.
I am bar.
I am bar.
I am r.
I am B.

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically. ## Variables From External Sources ### HTML Forms (GET and POST) 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: Example #1 A simple HTML form <form action="foo.php" method="post"> Name: <input type="text" name="username" /><br /> Email: <input type="text" name="email" /><br /> <input type="submit" name="submit" value="Submit me!" /> </form> Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are: Example #2 Accessing data from a simple POST HTML form  <?php // Available since PHP 4.1.0 echo$_POST['username'];   echo $_REQUEST['username']; import_request_variables('p', 'p_'); echo$p_username;// As of PHP 5.0.0, these long predefined variables can be// disabled with the register_long_arrays directive.   echo $HTTP_POST_VARS['username'];// Available if the PHP directive register_globals = on. As of // PHP 4.2.0 the default value of register_globals = off.// Using/relying on this method is not preferred. echo$username;?> 

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 $_POST and$_GET, became available in PHP 4.1.0

Note:

Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"]. As shown, before PHP 4.2.0 the default value for register_globals was 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!\"). It was deemed that this was needed for escaping for DB insertion circa a decade ago and is a legacy feature now that should be disabled. 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 #3 More complex form variables  <?phpif ($_POST) {    echo '<pre>';    echo htmlspecialchars(print_r($_POST, true)); echo '</pre>';}?><form action="" method="post"> Name: <input type="text" name="personal[name]" /><br /> Email: <input type="text" name="personal[email]" /><br /> Beer: <br /> <select multiple name="beer[]"> <option value="warthog">Warthog</option> <option value="guinness">Guinness</option> <option value="stuttgarter">Stuttgarter Schwabenbräu</option> </select><br /> <input type="submit" value="submit me!" /></form>  #### IMAGE SUBMIT variable names When submitting a form, it is possible to use an image instead of the standard submit button with a tag like: <input type="image" src="image.gif" name="sub" /> When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically. ### HTTP Cookies PHP transparently supports HTTP cookies as defined by » RFC 6265. 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.

Now, what the parser sees is a variable named $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. ### Determining variable types Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types. # Constants ## Table of Contents 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 See also the Userland Naming Guide. Example #1 Valid and invalid constant names  <?php// Valid constant namesdefine("FOO", "something");define("FOO2", "something else");define("FOO_BAR", "something more");// Invalid constant namesdefine("2FOO", "something");// This is valid, but should be avoided:// PHP may one day provide a magical constant// that will break your scriptdefine("__FOO__", "something"); ?>  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. ## Syntax You can define a constant by using the define()-function or by using the const keyword outside a class definition as of PHP 5.3.0. 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. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results. 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 $TRUE are 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. Example #1 Defining Constants  <?phpdefine("CONSTANT", "Hello world.");echo CONSTANT; // outputs "Hello world."echo Constant; // outputs "Constant" and issues a notice.?>  Example #2 Defining Constants using the const keyword  <?php// Works as of PHP 5.3.0const CONSTANT = 'Hello World';echo CONSTANT;?>  Note: As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops or if statements. See also Class Constants. ## Magic 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 eight 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: 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 with symlinks resolved whereas in older versions it contained relative path under some circumstances. __DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.) __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. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in. __TRAIT__ The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar). __METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive). __NAMESPACE__ The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0). # Expressions 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:

 <?phpfunction foo (){    return 5;}?> 

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

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports 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, 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:  <?php$first ? $second :$third?> 

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:

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

# Operators

An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression).

Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators + (plus) and - (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator).

A full list of PHP operators follows in the section Operator Precedence. The section also explains operator precedence and associativity, which govern exactly how expressions containing several different operators are evaluated.

## Operator Precedence

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.

When operators have equal precedence their associativity decides how the operators are grouped. For example "-" is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and evaluates to -4. "=" on the other hand is right-associative, so $a =$b = $c is grouped as$a = ($b =$c).

Operators of equal precedence that are non-associative cannot be used next to each other, for example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because the == operator has lesser precedence than the <= operator.

Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.

The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping.

Operator Precedence
non-associative clone new clone and new
left [ array()
right ++ -- ~ (int) (float) (string) (array) (object) (bool) @ types and increment/decrement
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

Example #1 Associativity

 <?php$a = 3 * 3 % 5; // (3 * 3) % 5 = 4// ternary operator associativity differs from C/C++$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2$a = 1;$b = 2;$a =$b += 3; // $a = ($b += 3) -> $a = 5,$b = 5?> 

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

Example #2 Undefined order of evaluation

 <?php$a = 1;echo$a + $a++; // may print either 2 or 3$i = 1;$array[$i] = $i++; // may set either index 1 or 2?>  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. ## Arithmetic Operators Remember basic arithmetic from school? These work just like those. 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 unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned. Operands of modulus are converted to integers (by stripping the decimal part) before processing. The result of the modulus operator % has the same sign as the dividend — that is, the result of$a % $b will have the same sign as$a. For example:

 <?phpecho (5 % 3)."\n";           // prints 2echo (5 % -3)."\n";          // prints 2echo (-5 % 3)."\n";          // prints -2echo (-5 % -3)."\n";         // prints -2?> 

## Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (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:  <?php$a = ($b = 4) + 5; //$a is equal to 9 now, and $b has been set to 4.?>  For arrays, assigning a value to a named key is performed using the "=>" operator. The precedence of this operator is the same as other assignment operators. 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. An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword. ### Assignment by Reference Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere. Example #1 Assigning by reference  <?php$a = 3;$b = &$a; // $b is a reference to$aprint "$a\n"; // prints 3print "$b\n"; // prints 3$a = 4; // change$aprint "$a\n"; // prints 4print "$b\n"; // prints 4 as well, since $b is a reference to$a, which has              // been changed?> 

As of PHP 5, the new operator returns a reference automatically, so assigning the result of new by reference results in an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions.

For example, this code will result in a warning:

 <?phpclass C {}/* The following line generates the following error message: * Deprecated: Assigning the return value of new by reference is deprecated in... */$o = &new C;?>  More information on references and their potential uses can be found in the References Explained section of the manual. ## Bitwise Operators Bitwise operators allow evaluation and manipulation of specific bits within an integer. Bitwise Operators Example Name Result $a & $b And Bits that are set in both$a and $b are set. $a | $b Or (inclusive or) Bits that are set in either$a or $b are set. $a ^ $b Xor (exclusive or) 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") Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved. Use parentheses to ensure the desired precedence. For example,$a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency. Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values. PHP's error_reporting ini setting uses bitwise values, providing a real-world demonstration of turning bits off. To show all errors, except for notices, the php.ini file instructions say to use: E_ALL & ~E_NOTICE  This works by starting with E_ALL: 00000000000000000111011111111111 Then taking the value of E_NOTICE... 00000000000000000000000000001000 ... and inverting it via ~: 11111111111111111111111111110111 Finally, it uses AND (&) to find the bits turned on in both values: 00000000000000000111011111110111  Another way to accomplish that is using XOR (^) to find bits that are on in only one value or the other: E_ALL ^ E_NOTICE  error_reporting can also be used to demonstrate turning bits on. The way to show just errors and recoverable errors is: E_ERROR | E_RECOVERABLE_ERROR  This process combines E_ERROR 00000000000000000000000000000001 and 00000000000000000001000000000000 using the OR (|) operator to get the bits turned on in either value: 00000000000000000001000000000001  Example #1 Bitwise AND, OR and XOR operations on integers  <?php/* * Ignore the top section, * it is just formatting to make output clearer. */$format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)'        . ' %3$s (%4$2d = %4$04b)' . "\n";echo <<<EOH --------- --------- -- --------- result value op test --------- --------- -- ---------EOH;/* * Here are the examples. */$values = array(0, 1, 2, 4, 8);$test = 1 + 4;echo "\n Bitwise AND \n";foreach ($values as $value) {$result = $value &$test;    printf($format,$result, $value, '&',$test);}echo "\n Bitwise Inclusive OR \n";foreach ($values as$value) {    $result =$value | $test; printf($format, $result,$value, '|', $test);}echo "\n Bitwise Exclusive OR (XOR) \n";foreach ($values as $value) {$result = $value ^$test;    printf($format,$result, $value, '^',$test);}?> 

The above example will output:

 ---------     ---------  -- ---------
result        value      op test
---------     ---------  -- ---------
Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)

Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)


Example #2 Bitwise XOR operations on strings

 <?phpecho 12 ^ 9; // Outputs '5'echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0                        // 'a' ^ 'e' = #4echo 2 ^ "3"; // Outputs 1              // 2 ^ ((int)"3") == 1echo "2" ^ 3; // Outputs 1              // ((int)"2") ^ 3 == 1?> 

Example #3 Bit shifting on integers

 <?php/* * Here are the examples. */echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";$val = 4;$places = 1;$res =$val >> $places;p($res, $val, '>>',$places, 'copy of sign bit shifted into left side');$val = 4;$places = 2;$res =$val >> $places;p($res, $val, '>>',$places);$val = 4;$places = 3;$res =$val >> $places;p($res, $val, '>>',$places, 'bits shift out right side');$val = 4;$places = 4;$res =$val >> $places;p($res, $val, '>>',$places, 'same result as above; can not shift beyond 0');echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";$val = -4;$places = 1;$res =$val >> $places;p($res, $val, '>>',$places, 'copy of sign bit shifted into left side');$val = -4;$places = 2;$res =$val >> $places;p($res, $val, '>>',$places, 'bits shift out right side');$val = -4;$places = 3;$res =$val >> $places;p($res, $val, '>>',$places, 'same result as above; can not shift beyond -1');echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";$val = 4;$places = 1;$res =$val << $places;p($res, $val, '<<',$places, 'zeros fill in right side');$val = 4;$places = (PHP_INT_SIZE * 8) - 4;$res =$val << $places;p($res, $val, '<<',$places);$val = 4;$places = (PHP_INT_SIZE * 8) - 3;$res =$val << $places;p($res, $val, '<<',$places, 'sign bits get shifted out');$val = 4;$places = (PHP_INT_SIZE * 8) - 2;$res =$val << $places;p($res, $val, '<<',$places, 'bits shift out left side');echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";$val = -4;$places = 1;$res =$val << $places;p($res, $val, '<<',$places, 'zeros fill in right side');$val = -4;$places = (PHP_INT_SIZE * 8) - 3;$res =$val << $places;p($res, $val, '<<',$places);$val = -4;$places = (PHP_INT_SIZE * 8) - 2;$res =$val << $places;p($res, $val, '<<',$places, 'bits shift out left side, including sign bit');/* * Ignore this bottom section, * it is just formatting to make output clearer. */function p($res,$val, $op,$places, $note = '') {$format = '%0' . (PHP_INT_SIZE * 8) . "b\n";    printf("Expression: %d = %d %s %d\n", $res,$val, $op,$places);    echo " Decimal:\n";    printf("  val=%d\n", $val); printf(" res=%d\n",$res);    echo " Binary:\n";    printf('  val=' . $format,$val);    printf('  res=' . $format,$res);    if ($note) { echo " NOTE:$note\n";    }    echo "\n";}?> 

Output of the above example on 32 bit machines:


--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
Decimal:
val=4
res=2
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000010
NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
Decimal:
val=4
res=1
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000001

Expression: 0 = 4 >> 3
Decimal:
val=4
res=0
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000000
NOTE: bits shift out right side

Expression: 0 = 4 >> 4
Decimal:
val=4
res=0
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000000
NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
Decimal:
val=-4
res=-2
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111110
NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
Decimal:
val=-4
res=-1
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111111
NOTE: bits shift out right side

Expression: -1 = -4 >> 3
Decimal:
val=-4
res=-1
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111111
NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
Decimal:
val=4
res=8
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000001000
NOTE: zeros fill in right side

Expression: 1073741824 = 4 << 28
Decimal:
val=4
res=1073741824
Binary:
val=00000000000000000000000000000100
res=01000000000000000000000000000000

Expression: -2147483648 = 4 << 29
Decimal:
val=4
res=-2147483648
Binary:
val=00000000000000000000000000000100
res=10000000000000000000000000000000
NOTE: sign bits get shifted out

Expression: 0 = 4 << 30
Decimal:
val=4
res=0
Binary:
val=00000000000000000000000000000100
res=00000000000000000000000000000000
NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
Decimal:
val=-4
res=-8
Binary:
val=11111111111111111111111111111100
res=11111111111111111111111111111000
NOTE: zeros fill in right side

Expression: -2147483648 = -4 << 29
Decimal:
val=-4
res=-2147483648
Binary:
val=11111111111111111111111111111100
res=10000000000000000000000000000000

Expression: 0 = -4 << 30
Decimal:
val=-4
res=0
Binary:
val=11111111111111111111111111111100
res=00000000000000000000000000000000
NOTE: bits shift out left side, including sign bit


Output of the above example on 64 bit machines:


--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
Decimal:
val=4
res=2
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000010
NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
Decimal:
val=4
res=1
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000001

Expression: 0 = 4 >> 3
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out right side

Expression: 0 = 4 >> 4
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
Decimal:
val=-4
res=-2
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111110
NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
Decimal:
val=-4
res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111111
NOTE: bits shift out right side

Expression: -1 = -4 >> 3
Decimal:
val=-4
res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111111
NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
Decimal:
val=4
res=8
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000001000
NOTE: zeros fill in right side

Expression: 4611686018427387904 = 4 << 60
Decimal:
val=4
res=4611686018427387904
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0100000000000000000000000000000000000000000000000000000000000000

Expression: -9223372036854775808 = 4 << 61
Decimal:
val=4
res=-9223372036854775808
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=1000000000000000000000000000000000000000000000000000000000000000
NOTE: sign bits get shifted out

Expression: 0 = 4 << 62
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
Decimal:
val=-4
res=-8
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111000
NOTE: zeros fill in right side

Expression: -9223372036854775808 = -4 << 61
Decimal:
val=-4
res=-9223372036854775808
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1000000000000000000000000000000000000000000000000000000000000000

Expression: 0 = -4 << 62
Decimal:
val=-4
res=0
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out left side, including sign bit


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. Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.

## Comparison Operators

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.

Comparison Operators
Example Name Result
$a ==$b Equal TRUE if $a is equal to$b after type juggling.
$a ===$b Identical TRUE if $a is equal to$b, and they are of the same type.
$a !=$b Not equal TRUE if $a is not equal to$b after type juggling.
$a <>$b Not equal TRUE if $a is not equal to$b after type juggling.
$a !==$b Not identical TRUE if $a is not equal to$b, or they are not of the same type.
$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 a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

 <?phpvar_dump(0 == "a"); // 0 == 0 -> truevar_dump("1" == "01"); // 1 == 1 -> truevar_dump("10" == "1e1"); // 10 == 10 -> truevar_dump(100 == "1e2"); // 100 == 100 -> trueswitch ("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).

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 both sides 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)
object anything object is always greater
array anything array is always greater

Example #1 Boolean/null comparison

 <?php// Bool and null are compared as bool alwaysvar_dump(1 == TRUE);  // TRUE - same as (bool)1 == TRUEvar_dump(0 == FALSE); // TRUE - same as (bool)0 == FALSEvar_dump(100 < TRUE); // FALSE - same as (bool)100 < TRUEvar_dump(-10 < FALSE);// FALSE - same as (bool)-10 < FALSEvar_dump(min(-100, -10, NULL, 10, 100)); // NULL - (bool)NULL < (bool)-100 is FALSE < TRUE?> 

Example #2 Transcription of standard array comparison

 <?php// Arrays are compared like this with standard comparison operatorsfunction standard_array_compare($op1,$op2){    if (count($op1) < count($op2)) {        return -1; // $op1 <$op2    } elseif (count($op1) > count($op2)) {        return 1; // $op1 >$op2    }    foreach ($op1 as$key => $val) { if (!array_key_exists($key, $op2)) { return null; // uncomparable } elseif ($val < $op2[$key]) {            return -1;        } elseif ($val >$op2[$key]) { return 1; } } return 0; //$op1 == $op2}?>  See also strcasecmp(), strcmp(), Array operators, and the manual section on Types. Warning # Comparison of floating point numbers Because of the way floats are represented internally, you should not test two floats for equality. See the documentation for float for more information. ### Ternary Operator Another conditional operator is the "?:" (or ternary) operator. Example #3 Assigning a default value  <?php// Example usage for: Ternary Operator$action = (empty($_POST['action'])) ? 'default' :$_POST['action'];// The above is identical to this if/else statementif (empty($_POST['action'])) {$action = 'default';} else {    $action =$_POST['action'];}?> 
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. 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: It 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 #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 aboveecho ((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.?>  ## Error Control Operators 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 you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @. 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.

## Execution Operators

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

 <?php$output = ls -al;echo "<pre>$output</pre>";?> 

Note:

The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.

Note:

Unlike some other languages, backticks cannot be used within double-quoted strings.

See also the manual section on Program Execution functions, popen() proc_open(), and Using PHP from the commandline.

## Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Note: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.

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:

 <?phpecho "<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 PHP and Perl $a = 'Z';$a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged. Example #1 Arithmetic Operations on Character Variables  <?phpecho '== Alphabets ==' . PHP_EOL;$s = 'W';for ($n=0;$n<6; $n++) { echo ++$s . PHP_EOL;}// Digit characters behave differentlyecho '== Digits ==' . PHP_EOL;$d = 'A8';for ($n=0; $n<6;$n++) {    echo ++$d . PHP_EOL;}$d = 'A08';for ($n=0;$n<6; $n++) { echo ++$d . PHP_EOL;}?> 

The above example will output:

== Characters ==
X
Y
Z
AA
AB
AC
== Digits ==
A9
B0
B1
B2
B3
B4
A09
A10
A11
A12
A13
A14


Incrementing or decrementing booleans has no effect.

## Logical Operators

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

Example #1 Logical operators illustrated

 <?php// --------------------// foo() will never get called as those operators are short-circuit$a = (false && foo());$b = (true  || foo());$c = (false and foo());$d = (true  or  foo());// --------------------// "||" has a greater precedence than "or"// The result of the expression (false || true) is assigned to $e// Acts like: ($e = (false || true))$e = false || true;// The constant false is assigned to$f and then true is ignored// Acts like: (($f = false) or true)$f = false or true;var_dump($e,$f);// --------------------// "&&" has a greater precedence than "and"// The result of the expression (true && false) is assigned to $g// Acts like: ($g = (true && false))$g = true && false;// The constant true is assigned to$h and then false is ignored// Acts like: (($h = true) and false)$h = true and false;var_dump($g,$h);?> 

The above example will output something similar to:

bool(true)
bool(false)
bool(false)
bool(true)


## String Operators

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. ## Array Operators 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 returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.  <?php$a = array("a" => "apple", "b" => "banana");$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");$c = $a +$b; // Union of $a and$becho "Union of \$a and \$b: \n";var_dump($c);$c = $b +$a; // Union of $b and$aecho "Union of \$b and \$a: \n";var_dump($c);?>  When executed, this script will print the following: 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. Example #1 Comparing arrays  <?php$a = array("apple", "banana");$b = array(1 => "banana", "0" => "apple");var_dump($a == $b); // bool(true)var_dump($a === $b); // bool(false)?>  See also the manual sections on the Array type and Array functions. ## Type Operators instanceof is used to determine whether a PHP variable is an instantiated object of a certain class: Example #1 Using instanceof with classes  <?phpclass MyClass{}class NotMyClass{}$a = new MyClass;var_dump($a instanceof MyClass);var_dump($a instanceof NotMyClass);?> 

The above example will output:

bool(true)
bool(false)


instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Example #2 Using instanceof with inherited classes

 <?phpclass ParentClass{}class MyClass extends ParentClass{}$a = new MyClass;var_dump($a instanceof MyClass);var_dump($a instanceof ParentClass);?>  The above example will output: bool(true) bool(true)  To check if an object is not an instanceof a class, the logical not operator can be used. Example #3 Using instanceof to check if object is not an instanceof a class  <?phpclass MyClass{}$a = new MyClass;var_dump(!($a instanceof stdClass));?>  The above example will output: bool(true)  Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface: Example #4 Using instanceof for class  <?phpinterface MyInterface{}class MyClass implements MyInterface{}$a = new MyClass;var_dump($a instanceof MyClass);var_dump($a instanceof MyInterface);?> 

The above example will output:

bool(true)
bool(true)


Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:

Example #5 Using instanceof with other variables

 <?phpinterface MyInterface{}class MyClass implements MyInterface{}$a = new MyClass;$b = new MyClass;$c = 'MyClass';$d = 'NotMyClass';var_dump($a instanceof$b); // $b is an object of class MyClassvar_dump($a instanceof $c); //$c is a string 'MyClass'var_dump($a instanceof$d); // $d is a string 'NotMyClass'?>  The above example will output: bool(true) bool(true) bool(false)  instanceof does not throw any error if the variable being tested is not an object, it simply returns FALSE. Constants, however, are not allowed. Example #6 Using instanceof to test other variables  <?php$a = 1;$b = NULL;$c = imagecreate(5, 5);var_dump($a instanceof stdClass); //$a is an integervar_dump($b instanceof stdClass); //$b is NULLvar_dump($c instanceof stdClass); //$c is a resourcevar_dump(FALSE instanceof stdClass);?> 

The above example will output:

bool(false)
bool(false)
bool(false)
PHP Fatal error:  instanceof expects an object instance, constant given


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:

Example #7 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0

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:  <?phpif ($a == 5):    echo "a equals 5";    echo "...";elseif ($a == 6): echo "a equals 6"; echo "!!!";else: echo "a is neither 5 nor 6";endif;?>  Note: Mixing syntaxes in the same control block is not supported. See also while, for, and if for further examples. ## while (PHP 4, PHP 5) 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: while (expr) statement  The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once. Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax: while (expr): statement ... endwhile;  The following examples are identical, and both print the numbers 1 through 10:  <?php/* example 1 */$i = 1;while ($i <= 10) { echo$i++;  /* the printed value would be                   $i before the increment (post-increment) */}/* example 2 */$i = 1;while ($i <= 10): echo$i;    $i++;endwhile;?>  ## do-while (PHP 4, PHP 5) 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 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:  <?php$i = 0;do {    echo $i;} while ($i > 0);?> 

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends. Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:  <?phpdo { 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'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.

## for

(PHP 4, PHP 5)

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

for (expr1; expr2; expr3)
statement


The first expression (expr1) is evaluated (executed) 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. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. 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 the numbers 1 through 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. for (expr1; expr2; expr3): statement ... endfor;  It's a common thing to many users to iterate through arrays like in the example below.  <?php/* * This is an array with some data we want to modify * when running through the for loop. */$people = array(    array('name' => 'Kalle', 'salt' => 856412),    array('name' => 'Pierre', 'salt' => 215863));for($i = 0;$i < count($people); ++$i) {    $people[$i]['salt'] = mt_rand(000000, 999999);}?> 

The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count():

 <?php$people = array( array('name' => 'Kalle', 'salt' => 856412), array('name' => 'Pierre', 'salt' => 215863));for($i = 0, $size = count($people); $i <$size; ++$i) {$people[$i]['salt'] = mt_rand(000000, 999999);}?>  ## foreach (PHP 4, PHP 5) The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, 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: 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 iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element). The second form will additionally assign the current element's key to the$key variable on each iteration.

It is possible to customize object iteration.

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.

As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.  <?php$arr = array(1, 2, 3, 4);foreach ($arr as &$value) {    $value =$value * 2;}// $arr is now array(2, 4, 6, 8)unset($value); // break the reference with the last element?> 

Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:  <?phpforeach (array(1, 2, 3, 4) as &$value) {    $value =$value * 2;}?> 

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). 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";}?>  The following are also functionally identical:  <?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 usage:  <?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 its manual access notation 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";}?>  ### Unpacking nested arrays with list() (PHP 5 >= 5.5.0) PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value. For example:  <?php$array = [    [1, 2],    [3, 4],];foreach ($array as list($a, $b)) { //$a contains the first element of the nested array,    // and $b contains the second element. echo "A:$a; B: $b\n";}?>  The above example will output: A: 1; B: 2 A: 3; B: 4  You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:  <?php$array = [    [1, 2],    [3, 4],];foreach ($array as list($a)) {    // Note that there is no $b here. echo "$a\n";}?> 

The above example will output:

1
3


A notice will be generated if there aren't enough array elements to fill the list():

 <?php$array = [ [1, 2], [3, 4],];foreach ($array as list($a,$b, $c)) { echo "A:$a; B: $b; C:$c\n";}?> 

The above example will output:


Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:


## break

(PHP 4, PHP 5)

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;    }}?> 

Changelog for break
Version Description
5.4.0 break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break$num;) as the numerical argument.

## continue

(PHP 4, PHP 5)

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. The default value is 1, thus skipping to the end of the current loop.

 <?phpwhile (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.  <?phpfor ($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 entire continue print "$i\n"; is evaluated as a single expression, and so print is called only when$i == 2 is true. (The return value of print is passed to continue as the numeric argument.)

Changelog for continue
Version Description
5.4.0 continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; continue$num;) as the numerical argument.

## switch

(PHP 4, PHP 5)

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.

Note:

Note that switch/case does loose comparision.

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:

Example #1 switch structure

 <?phpif ($i == 0) { echo "i equals 0";} elseif ($i == 1) {    echo "i equals 1";} elseif ($i == 2) { echo "i equals 2";}switch ($i) {    case 0:        echo "i equals 0";        break;    case 1:        echo "i equals 1";        break;    case 2:        echo "i equals 2";        break;}?> 

Example #2 switch structure allows usage of strings

 <?phpswitch ($i) { case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; break; case "cake": echo "i is cake"; break;}?>  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:  <?phpswitch ($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.  <?phpswitch ($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. For example:

 <?phpswitch ($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.  <?phpswitch ($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";endswitch;?> 

It's possible to use a semicolon instead of a colon after a case like:

## require

(PHP 4, PHP 5)

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

See the include documentation for how this works.

## include

(PHP 4, PHP 5)

The include statement includes and evaluates the specified file.

The documentation below also applies to require.

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.

If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

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 #1 Basic include example

 vars.php<?php$color = 'green';$fruit = 'apple';?>test.php<?phpecho "A $color$fruit"; // Ainclude 'vars.php';echo "A $color$fruit"; // A green apple?> 

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. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Example #2 Including within functions

 <?phpfunction foo(){    global $color; include 'vars.php'; echo "A$color $fruit";}/* vars.php is in the scope of foo() so **$fruit is NOT available outside of this  ** scope.  $color is because we declared it ** as global. */foo(); // A green appleecho "A$color $fruit"; // A green?>  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 include wrappers" are enabled in PHP, you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Supported Protocols and Wrappers 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 access of remote files via this function, even if allow_url_fopen is enabled. Example #3 include through HTTP  <?php/* This example assumes that www.example.com is configured to parse .php* files and not .txt files. Also, 'Works' here means that the variables*$foo and $bar are available within the included file. */// Won't work; file.txt wasn't handled by www.example.com as PHPinclude 'http://www.example.com/file.txt?foo=1&bar=2';// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the// local filesystem.include 'file.php?foo=1&bar=2';// Works.include 'http://www.example.com/file.php?foo=1&bar=2';$foo = 1;$bar = 2;include 'file.txt'; // Works.include 'file.php'; // Works.?>  Warning # 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: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. 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 for 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. Example #4 Comparing return value of include  <?php// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')if (include('vars.php') == 'OK') { echo 'OK';}// worksif ((include 'vars.php') == 'OK') { echo 'OK';}?>  Example #5 include and the return statement  return.php<?php$var = 'PHP';return $var;?>noreturn.php<?php$var = 'PHP';?>testreturns.php<?php$foo = include 'return.php';echo$foo; // prints 'PHP'$bar = include 'noreturn.php';echo$bar; // prints 1?> 

$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 #6 Using output buffering to include a PHP file into a string  <?php$string = get_include_contents('somefile.php');function get_include_contents($filename) { if (is_file($filename)) {        ob_start();        include $filename; return ob_get_clean(); } return false;}?>  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. ## require_once (PHP 4, PHP 5) The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again. See the include_once documentation for information about the _once behaviour, and how it differs from its non _once siblings. ## include_once (PHP 4, PHP 5) 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 may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc. See the include documentation for information about how this function works. Note: With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example: Example #1 include_once with a case insensitive OS in PHP 4  <?phpinclude_once "a.php"; // this will include a.phpinclude_once "A.php"; // this will include a.php again! (PHP 4 only)?>  This behaviour changed in PHP 5, so for example with Windows 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. ## goto (PHP 5 >= 5.3.0) Image courtesy of » xkcd The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break. Example #1 goto example  <?phpgoto a;echo 'Foo'; a:echo 'Bar';?>  The above example will output: Bar  Example #2 goto loop example  <?phpfor($i=0,$j=50;$i<100; $i++) { while($j--) {    if($j==17) goto end; } }echo "i =$i";end:echo 'j hit 17';?> 

The above example will output:

j hit 17


Example #3 This will not work

 <?phpgoto loop;for($i=0,$j=50; $i<100;$i++) {  while($j--) { loop: }}echo "$i = $i";?>  The above example will output: Fatal error: 'goto' into loop or switch statement is disallowed in script on line 2  Note: The goto operator is available as of PHP 5.3. # Functions ## Table of Contents ## User-defined functions A function may be defined using syntax such as the following: Example #1 Pseudo code to demonstrate function uses  <?phpfunction foo($arg_1, $arg_2, /* ..., */$arg_n){    echo "Example function.\n";    return $retval;}?>  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 See also the Userland Naming Guide. Functions need not be defined before they are referenced, except when a function is conditionally defined 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 #2 Conditional functions  <?php$makefoo = true;/* We can't call foo() from here    since it doesn't exist yet,   but we can call bar() */bar();if ($makefoo) { function foo() { echo "I don't exist until program execution reaches me.\n"; }}/* Now we can safely call foo() since$makefoo evaluated to true */if ($makefoo) foo();function bar() { echo "I exist immediately upon program start.\n";}?>  Example #3 Functions within functions  <?phpfunction foo() { function bar() { echo "I don't exist until foo() is called.\n"; }}/* We can't call bar() yet since it doesn't exist. */foo();/* Now we can call bar(), foo()'s processing has made it accessible. */bar();?>  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. Both variable number of arguments and default arguments are supported in functions. See also 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. Example #4 Recursive functions  <?phpfunction recursion($a){    if ($a < 20) { echo "$a\n";        recursion($a + 1); }}?>  ## Function arguments Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right. PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. Example #1 Passing arrays to functions  <?phpfunction takes_array($input){    echo "$input[0] +$input[1] = ", $input[0]+$input[1];}?> 

### Making arguments be passed by reference

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

Example #2 Passing function parameters by reference

 <?phpfunction add_some_extra(&$string){$string .= 'and something extra.';}$str = 'This is a string, ';add_some_extra($str);echo $str; // outputs 'This is a string, and something extra.'?>  ### Default argument values A function may define C++-style default values for scalar arguments as follows: Example #3 Use of default parameters in functions  <?phpfunction makecoffee($type = "cappuccino"){    return "Making a cup of $type.\n";}echo makecoffee();echo makecoffee(null);echo makecoffee("espresso");?>  The above example will output: Making a cup of cappuccino. Making a cup of . Making a cup of espresso.  PHP also allows the use of arrays and the special type NULL as default values, for example: Example #4 Using non-scalar types as default values  <?phpfunction makecoffee($types = array("cappuccino"), $coffeeMaker = NULL){$device = is_null($coffeeMaker) ? "hands" :$coffeeMaker;    return "Making a cup of ".join(", ", $types)." with$device.\n";}echo makecoffee();echo makecoffee(array("cappuccino", "lavazza"), "teapot");?> 

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:

Example #5 Incorrect usage of default function arguments

 <?phpfunction makeyogurt($type = "acidophilus",$flavour){    return "Making a bowl of $type$flavour.\n";} echo makeyogurt("raspberry");   // won't work as expected?> 

The above example will output:

Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .


Now, compare the above with this:

Example #6 Correct usage of default function arguments

 <?phpfunction makeyogurt($flavour,$type = "acidophilus"){    return "Making a bowl of $type$flavour.\n";} echo makeyogurt("raspberry");   // works as expected?> 

The above example will output:

Making a bowl of acidophilus raspberry.


Note: As of PHP 5, arguments that are passed by reference may have a default value.

### Variable-length argument lists

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

## Returning values

Values are returned by using the optional return statement. Any type may be returned, including arrays 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.

Note:

If the return is omitted the value NULL will be returned.

Example #1 Use of return

 <?phpfunction square($num){ return$num * $num;}echo square(4); // outputs '16'.?>  A function can not return multiple values, but similar results can be obtained by returning an array. Example #2 Returning an array to get multiple values  <?phpfunction small_numbers(){ return array (0, 1, 2);}list ($zero, $one,$two) = small_numbers();?> 

To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:

Example #3 Returning a reference from a function

 <?phpfunction &returns_reference(){    return $someref;}$newref =& returns_reference();?> 

## Variable functions

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. Utilize wrapper functions to make use of any of these constructs as variable functions.

Example #1 Variable function example

 <?phpfunction foo() {    echo "In foo()<br />\n";}function bar($arg = ''){ echo "In bar(); argument was '$arg'.<br />\n";}// This is a wrapper function around echofunction echoit($string){ echo$string;}$func = 'foo';$func();        // This calls foo()$func = 'bar';$func('test');  // This calls bar()$func = 'echoit';$func('test');  // This calls echoit()?> 

Object methods can also be called with the variable functions syntax.

Example #2 Variable method example

 <?phpclass Foo{    function Variable()    {        $name = 'Bar';$this->$name(); // This calls the Bar() method } function Bar() { echo "This is Bar"; }}$foo = new Foo();$funcname = "Variable";$foo->$funcname(); // This calls$foo->Variable()?> 

When calling static methods, the function call is stronger than the static property operator:

Example #3 Variable method example with static properties

 <?phpclass Foo{    static $variable = 'static property'; static function Variable() { echo 'Method Variable called'; }}echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.$variable = "Variable";Foo::$variable(); // This calls$foo->Variable() reading $variable in this scope.?>  ## Internal (built-in) functions PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are included in every version of PHP, such as the string and variable functions. A call to phpinfo() or get_loaded_extensions() will show which extensions are loaded into 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 set up 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(). ## Anonymous functions Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Example #1 Anonymous function example  <?phpecho preg_replace_callback('~-([a-z])~', function ($match) {    return strtoupper($match[1]);}, 'hello-world');// outputs helloWorld?>  Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon: Example #2 Anonymous function variable assignment example  <?php$greet = function($name){ printf("Hello %s\r\n",$name);};$greet('World');$greet('PHP');?> 

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

Example #3 Closures and scoping

 <?php// A basic shopping cart which contains a list of added products// and the quantity of each product. Includes a method which// calculates the total price of the items in the cart using a// closure as a callback.class Cart{    const PRICE_BUTTER  = 1.00;    const PRICE_MILK    = 3.00;    const PRICE_EGGS    = 6.95;    protected $products = array(); public function add($product, $quantity) {$this->products[$product] =$quantity;    }        public function getQuantity($product) { return isset($this->products[$product]) ?$this->products[$product] : FALSE; } public function getTotal($tax)    {        $total = 0.00;$callback =            function ($quantity,$product) use ($tax, &$total)            {                $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product));                $total += ($pricePerItem * $quantity) * ($tax + 1.0);            };                array_walk($this->products,$callback);        return round($total, 2); }}$my_cart = new Cart;// Add some items to the cart$my_cart->add('butter', 1);$my_cart->add('milk', 3);$my_cart->add('eggs', 6);// Print the total with a 5% sales tax.print$my_cart->getTotal(0.05) . "\n";// The result is 54.29?> 

Anonymous functions are implemented using the Closure class.

### Changelog

Version Description
5.4.0 $this can be used in anonymous functions. 5.3.0 Anonymous functions become available. ### Notes Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure. # Classes and Objects ## Table of Contents ## Introduction Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model. Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting. PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References Tip See also the Userland Naming Guide. ## The Basics ### class Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label which is not a PHP reserved word. A valid class 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]*$.

A class may contain its own constants, variables (called "properties"), and functions (called "methods").

Example #1 Simple Class definition

 <?phpclass SimpleClass{    // property declaration    public $var = 'a default value'; // method declaration public function displayVar() { echo$this->var;    }}?> 

The 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 possibly another object, if the method is called statically from the context of a secondary object).

Example #2 Some examples of the $this pseudo-variable  <?phpclass 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() { // Note: the next line will issue a warning if E_STRICT is enabled. A::foo(); }}$a = new A();$a->foo();// Note: the next line will issue a warning if E_STRICT is enabled.A::foo();$b = new B();$b->bar();// Note: the next line will issue a warning if E_STRICT is enabled.B::bar();?>  The above example will output: $this is defined (A)
$this is not defined.$this is defined (B)
$this is not defined.  ### new To create an instance of a class, the new keyword must be used. An object will always be created 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). If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this. Example #3 Creating an instance  <?php$instance = new SimpleClass();// This can also be done with a variable:$className = 'Foo';$instance = new $className(); // Foo()?>  In the class context, it is possible to create a new object by new self and new parent. 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 #4 Object Assignment  <?php$instance = new SimpleClass();$assigned =$instance;$reference =&$instance;$instance->var = '$assigned will have this value';$instance = null; //$instance and $reference become nullvar_dump($instance);var_dump($reference);var_dump($assigned);?> 

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value" }  PHP 5.3.0 introduced a couple of new ways to create instances of an object: Example #5 Creating new objects  <?phpclass Test{ static public function getNew() { return new static; }}class Child extends Test{}$obj1 = new Test();$obj2 = new$obj1;var_dump($obj1 !==$obj2);$obj3 = Test::getNew();var_dump($obj3 instanceof Test);$obj4 = Child::getNew();var_dump($obj4 instanceof Child);?> 

The above example will output:

bool(true)
bool(true)
bool(true)


### extends

A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.

The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.

When overriding methods, the parameter signature should remain the same or PHP will generate an E_STRICT level error. This does not apply to the constructor, which allows overriding with different parameters.

Example #6 Simple Class Inheritance

 <?phpclass ExtendClass extends SimpleClass{    // Redefine the parent method    function displayVar()    {        echo "Extending class\n";        parent::displayVar();    }}$extended = new ExtendClass();$extended->displayVar();?> 

The above example will output:

Extending class
a default value


### ::class

Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.

Example #7 Class name resolution

 <?phpnamespace NS {    class ClassName {    }        echo ClassName::class;}?> 

The above example will output:

NS\ClassName


## Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See Visibility for more information on the meanings of public, protected, and private.

Note:

In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.

If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property. See Static Keyword for more information on the difference between static and non-static properties.

The pseudo-variable $this is available inside any class method when that 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 possibly another object, if the method is called statically from the context of a secondary object).

Example #1 property declarations

 <?phpclass SimpleClass{   // invalid property declarations:   public $var1 = 'hello ' . 'world'; public$var2 = <<<EODhello worldEOD;   public $var3 = 1+2; public$var4 = self::myStaticMethod();   public $var5 =$myVar;   // valid property declarations:   public $var6 = myConstant; public$var7 = array(true, false);   // This is allowed only in PHP 5.3.0 and later.   public $var8 = <<<'EOD'hello worldEOD;}?>  Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions. Unlike heredocs, nowdocs can be used in any static data context, including property declarations. Example #2 Example of using a nowdoc to initialize a property  <?phpclass foo { // As of PHP 5.3.0 public$bar = <<<'EOT'barEOT;}?> 

Note:

Nowdoc support was added in PHP 5.3.0.

## Class Constants

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. The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call. It's also possible for interfaces to have constants. Look at the interface documentation for examples. As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static). Example #1 Defining and using a constant  <?phpclass MyClass{ const CONSTANT = 'constant value'; function showConstant() { echo self::CONSTANT . "\n"; }}echo MyClass::CONSTANT . "\n";$classname = "MyClass";echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0$class = new MyClass();$class->showConstant();echo$class::CONSTANT."\n"; // As of PHP 5.3.0?> 

Example #2 Static data example

 <?phpclass foo {    // As of PHP 5.3.0    const BAR = <<<'EOT'barEOT;}?> 

Unlike heredocs, nowdocs can be used in any static data context.

Note:

Nowdoc support was added in PHP 5.3.0.

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

Tip

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

Note:

Prior to 5.3.0, exceptions thrown in the __autoload function could not be caught in the catch block and would result in a fatal error. From 5.3.0+ exceptions thrown in the __autoload function can be caught in the catch block, with 1 provision. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.

Note:

Note:

If the class name is used e.g. in call_user_func() then it can contain some dangerous characters such as ../. It is recommended to not use the user-input in such functions or at least verify the input in __autoload().

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.

 <?phpfunction __autoload($class_name) { include$class_name . '.php';}$obj = new MyClass1();$obj2 = new MyClass2(); ?> 

This example attempts to load the interface ITest.

 <?phpfunction __autoload($name) { var_dump($name);}class Foo implements ITest {}/*string(5) "ITest"Fatal error: Interface 'ITest' not found in ...*/?> 

This example throws an exception and demonstrates the try/catch block.

 <?phpfunction __autoload($name) { echo "Want to load$name.\n";    throw new Exception("Unable to load $name.");}try {$obj = new NonLoadableClass();} catch (Exception $e) { echo$e->getMessage(), "\n";}?> 

The above example will output:

Want to load NonLoadableClass.


Example #4 Autoloading with exception handling for 5.3.0+ - Missing custom exception

This example throws an exception for a non-loadable, custom exception.

 <?phpfunction __autoload($name) { echo "Want to load$name.\n";    throw new MissingException("Unable to load $name.");}try {$obj = new NonLoadableClass();} catch (Exception $e) { echo$e->getMessage(), "\n";}?> 

The above example will output:

Want to load NonLoadableClass.



## Constructors and Destructors

### Constructor

void __construct ([ mixed $args [, $... ]] )

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. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Example #1 using new unified constructors

 <?phpclass BaseClass {   function __construct() {       print "In BaseClass constructor\n";   }}class SubClass extends BaseClass {   function __construct() {       parent::__construct();       print "In SubClass constructor\n";   }}class OtherSubClass extends BaseClass {    // inherits BaseClass's constructor}// In BaseClass constructor$obj = new BaseClass();// In BaseClass constructor// In SubClass constructor$obj = new SubClass();// In BaseClass constructor$obj = new OtherSubClass();?>  For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent 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. Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has. As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes. Example #2 Constructors in namespaced classes  <?phpnamespace Foo;class Bar { public function Bar() { // treated as constructor in PHP 5.3.0-5.3.2 // treated as regular method as of PHP 5.3.3 }}?>  ### Destructor void __destruct ( void ) 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 there are no other references to a particular object, or in any order during the shutdown sequence. Example #3 Destructor Example  <?phpclass MyDestructableClass { function __construct() { print "In constructor\n";$this->name = "MyDestructableClass";   }   function __destruct() {       print "Destroying " . $this->name . "\n"; }}$obj = new MyDestructableClass();?> 

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. Also like constructors, a child class may inherit the parent's destructor if it does not implement one itself.

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.

Note:

Destructors called during the script shutdown have H