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.
PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.
This manual consists primarily of a function reference, but also contains a language reference, explanations of some of PHP's major features, and other supplemental information.
You can download this manual in several formats at » http://www.php.net/download-docs.php. More information about how this manual is developed can be found in the 'About the manual' appendix. If you are interested in the history of PHP, visit the relevant appendix.
We highlight the currently most active people on 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.
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.
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.
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.
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.
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.
Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.
PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.
In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things.
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> <head> <title>PHP Test</title> </head> <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(); ?>
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)
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
A sample output of this script may be:
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
<?php
if (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
<?php
if (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.
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.
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:
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/
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:
For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and MacOS X; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.
In case of setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.
If you are also interested to use PHP for command line scripting (e.g. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.
With PHP you can also write desktop GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage windows and objects within them. For more information about PHP-GTK, please » visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.
From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.
PHP source code and binary distributions for Windows can be found at » http://www.php.net/downloads.php. We recommend you to choose a » mirror nearest to you for downloading the distributions.
This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.
As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.
There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.
Prerequisite knowledge and software for compiling:
When building directly from Git sources or after custom modifications you might also need:
The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.
When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.
You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.
Example #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.
13. Setup your php.ini file:
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.
If you instead choose php.ini-production, be certain to read the list
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.
LoadModule php5_module libexec/libphp5.so
15. And in the AddModule section of httpd.conf, somewhere under the
ClearModuleList, add this:
AddModule mod_php5.c
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.
AddType application/x-httpd-php .php .phtml
It's also common to setup the .phps extension to show highlighted PHP
source, this can be done with:
AddType application/x-httpd-php-source .phps
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.
Edit your httpd.conf or srm.conf file and add:
AddType application/x-httpd-php .php
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:
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.User nobody Group "#-1"
Note:
Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs . You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.
This section contains notes and hints specific to Apache 2.x installs of PHP on Unix systems.
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.
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
Likewise, obtain and unpack the PHP source:
gunzip php-NN.tar.gz tar -xf php-NN.tar
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
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
/usr/local/apache2/bin/apachectl stop
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.
Setup your php.ini
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.
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
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.
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:
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.
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.
It is recomended that you visit the Nginx Wiki » install page in order to obtain and install Nginx on your system.
Obtain and unpack the PHP source:
tar zxf php-x.x.x
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
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
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
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.
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
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.
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).
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).
Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.
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"
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 ))
)
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.
You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: » http://benoit.noss.free.fr/php/install-php4.html
To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.
Install the following packages from » http://www.sunfreeware.com/ or another download site:
export PATH.
gunzip php-x.x.x.tar.gz (if you have a .gz dist,
otherwise go to 4).
tar xvf php-x.x.x.tar
cd ../php-x.x.x
For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.
Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):
<Object name="default"> . . . .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] . . </Object>
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object>
Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object>
To use PHP Authentication on a single directory, add the following:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object>
Note:
The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!
Note:
Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Note:
But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
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.
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 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.
Some server supplied environment variables are not defined in the current » CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.
This section contains notes and hints specific to installing PHP on HP-UX systems.
There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.
Official pre-compiled packages are located here: » http://software.hp.com/
Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: » Building Apache and PHP on HP-UX 11.11
This section contains notes and hints specific to installing PHP on » OpenBSD 3.6.
Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.
The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.
Example #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.
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.
Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).
This section contains notes and hints specific to installing PHP on Solaris systems.
Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary.
For unpacking the PHP distribution you need
For compiling PHP you need
For building extra extensions or hacking the code of PHP you might also need
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.
This section contains notes and hints specific to installing PHP on » Debian GNU/Linux.
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.
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
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.
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.
There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.
The following resources offer easy to install packages and precompiled binaries for PHP on Mac OS:
PHP has come standard with Macs since OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).
Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate MAC OS X installation documentation for further details. The following instructions are geared towards a beginner with details provided for getting a default setup to work. All users are encouraged to compile, or install a new packaged version.
The standard installation type is using mod_php, and enabling the bundled mod_php on Mac OS X for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:
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.
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
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.
The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:
<?php phpinfo(); ?>
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.
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.
This section contains instructions for manually installing and configuring PHP on Microsoft Windows.
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.
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.
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.
This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).
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.
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.
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:
In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";
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";
Click the "Directory Security" tab;
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)
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:
In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";
Right-click on the "Web Sites" node in the tree view and select "Properties";
Click the "Documents" tab;
Click the "Add..." button and enter "index.php" for the "Default content page:".
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
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
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\"
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.
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:
In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";
In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;
Click OK and wait until the installation is complete.
To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:
In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";
If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";
If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;
Click "Next" and then "Install" and wait for the installation to complete.
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.
Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:
In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";
In the IIS Manager user interface select the server node in the "Connections" tree view;
In the "Features View" page open the "Handler Mappings" feature;
In the "Actions" pane click "Add Module Mapping...";
In the "Add Module Mapping" dialog enter the following:
Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;
Click OK on all the dialogs to save the configuration.
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.
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)
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
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']"
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
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
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.
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
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
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'); ?>.
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.
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>
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(); ?>
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 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" AddHandler fcgid-script .php FcgidWrapper "c:/php/php-cgi.exe" .php
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.
To install PHP as a CGI handler, do the following:
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %*
More details about setting up PHP as a CGI executable can be found here: » http://benoit.noss.free.fr/php/install-php.html
To install PHP with NSAPI, do the following:
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %*
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll" Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:
Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object>
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
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.
Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.
If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:
Init fn=php4_init ... server_lib="ns-httpdXX.dll"
You can check the status by using the phpinfo() function.
Note:
But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
This section contains notes and hints specific to 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
Now restart the Sambar server for the changes to take effect.
Note:
If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.
This section contains notes and hints specific to » Xitami on Windows.
Note:
You should read the manual installation steps first!
This list describes how to set up the PHP CGI binary to work with Xitami on Windows.
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.
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.
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
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.
| 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 |
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
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:
ordir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.dir | script -arg1 -arg2 -arg3Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788.Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer] "InheritConsoleHandles"=dword:00000001
PHP installs on the cloud. To the PHP cloud!
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.
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).
FPM uses php.ini syntax for its configuration file - php-fpm.conf, and pool configuration files.
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.
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[error_log] = /var/log/fpm-php.www.log php_admin_flag[log_errors] = on php_admin_value[memory_limit] = 32M
Settings defined with php_admin_value and php_admin_flag cannot be overriden with ini_set().
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";
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.
» 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.
There are several options for downloading PECL extensions, such as:
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.
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.
Many times, you will find several versions of each DLL:
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
<?php
phpinfo();
?>
Or from the command line, run:
drive:\\path\to\php\executable\php.exe -i
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.
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.
PECL makes it easy to create shared PHP extensions. Using the » pecl command, do the following:
This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini
By default, the pecl command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:
You may also install a specific version using this variant:
Note:
After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.
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 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 [...]
| 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 |
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:
From here, force PHP to rebuild the configure script, and then build PHP as normal:
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:
Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.
If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on » http://www.php.net/support.php. To subscribe to the PHP installation mailing list, send an empty mail to » php-install-subscribe@lists.php.net. The mailing list address is » php-install@lists.php.net.
If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what PHP version, what web server, if you are running PHP as CGI or a server module, safe mode, etc.), and preferably enough code to make others able to reproduce and test your problem.
If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at » http://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.
Read the » How to report a bug document before submitting any bug reports!
The configuration file (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):
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".
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).
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().
| 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 |
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_valueto 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>
PHP constants do not exist outside of PHP. For example, in
httpd.conf you can not use PHP constants
such as E_ALL or E_NOTICE
to set the error_reporting
directive as they will have no meaning and will evaluate to
0. Use the associated bitmask values instead.
These constants can be used in php.ini
When running PHP on Windows, the configuration values can be
modified on a per-directory basis using the Windows registry. The
configuration values are stored in the registry key
HKLM\SOFTWARE\PHP\Per Directory Values,
in the sub-keys corresponding to the path names. For example, configuration
values for the directory c:\inetpub\wwwroot would
be stored in the key HKLM\SOFTWARE\PHP\Per Directory
Values\c\inetpub\wwwroot. The settings for the
directory would be active for any script running from this
directory or any subdirectory of it. The values under the key
should have the name of the PHP configuration directive and the
string value. PHP constants in the values are not parsed.
However, only configuration values changeable in
PHP_INI_USER can be set
this way, PHP_INI_PERDIR values can not.
Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.
If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().
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>
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; ?>
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.
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.
<?php
echo 'This is a test';
?>
<?php echo 'This is a test' ?>
<?php echo 'We omitted the last closing tag';
Note:
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.
PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:
<?php
echo 'This is a test'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.
<h1>This is an <?php # echo 'simple';?> example</h1>
<p>The header above will say 'This is an example'.</p>
'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.
<?php
/*
echo 'This is a test'; /* This comment will cause a problem */
*/
?>
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:
<?php
$a_bool = TRUE; // a boolean
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an integer
echo gettype($a_bool); // prints out: boolean
echo gettype($a_str); // prints out: string
// If this is an integer, increment it by four
if (is_int($an_int)) {
$an_int += 4;
}
// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
echo "String: $a_bool";
}
?>
To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.
Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. The type comparison tables may also be useful, as they show examples of various type-related comparisons.
This is the simplest type. A boolean expresses a truth value. It
can be either TRUE or FALSE.
To specify a boolean literal, use the keywords TRUE or
FALSE. Both are case-insensitive.
<?php
$foo = True; // assign the value TRUE to $foo
?>
Typically, the result of an operator which returns a boolean value is passed on to a control structure.
<?php
// == is an operator which tests
// equality and returns a boolean
if ($action == "show_version") {
echo "The version is 1.23";
}
// this is not necessary...
if ($show_separators == TRUE) {
echo "<hr>\n";
}
// ...because this can be used with exactly the same meaning:
if ($show_separators) {
echo "<hr>\n";
}
?>
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.
See also Type Juggling.
When converting to boolean, the following values are considered
FALSE:
FALSE itself
Every other value is considered TRUE (including any
resource).
-1 is considered TRUE, like any other non-zero
(whether negative or positive) number!
<?php
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
?>
An integer is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}.
See also:
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.
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
<?php
var_dump(01090); // 010 octal = 8 decimal
?>
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.
<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>
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.
FALSE will yield 0 (zero), and TRUE will yield
1 (one).
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!
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.
<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>
See also the warning about float precision.
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 (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).
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?"
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.
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";
}
?>
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().
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)
A string literal can be specified in four different ways:
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.
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special 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.
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.
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
<?php
class foo {
public $bar = <<<EOT
bar
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 = <<<EOD
Example of string
spanning multiple lines
using 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 <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
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
<?php
var_dump(array(<<<EOD
foobar!
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 variables
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}
// Class properties/constants
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;
public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>
Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:
Example #5 Using double quotes in Heredoc
<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
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 string
spanning multiple lines
using 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': \x41
EOT;
?>
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': \x41Note:
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
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Note:
Nowdoc support was added in PHP 5.3.0.
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.
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.
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 errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but 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 strings
echo "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.
<?php
class 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 & W
echo "I'd like an {${beers::softdrink}}\n";
// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>
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.
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.
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 {}.
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.
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.
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:
<?php
echo "\$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.
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:
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.
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.
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:
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.
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
<?php
function getArray() {
return array(1, 2, 3);
}
// on PHP 5.4
$secondElement = getArray()[1];
// previously
$tmp = getArray();
$secondElement = $tmp[1];
// or
list(, $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 beNULL.
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 array
unset($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 )
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.
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.
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\nChecking $i: \n";
echo "Bad: " . $array['$i'] . "\n";
echo "Good: " . $array[$i] . "\n";
echo "Bad: {$array['$i']}\n";
echo "Good: {$array[$i]}\n";
}
?>The above example will output:
Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2
More examples to demonstrate this behaviour:
<?php
// Show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// 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 now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]"; // Hello apple
// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}"; // Hello carrot
print "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 well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "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:
<?php
echo $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.
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.
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:
<?php
class A {
private $A; // This will become '\0A\0A'
}
class B extends A {
private $A; // This will become '\0B\0A'
public $AA; // This will become 'AA'
}
var_dump((array) new B());
?>
The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.
It is possible to compare arrays with the array_diff() function and with array operators.
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 5
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
// Workaround for older versions
foreach ($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
<?php
sort($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.
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
To create a new object, use the new statement to instantiate a class:
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
For a full discussion, see the Classes and Objects chapter.
If an object is converted to an object, it is not
modified. If a value of any other type is converted to an
object, a new instance of the stdClass
built-in class is created. If the value was NULL, the new instance will be
empty. Arrays convert to an object with properties
named by keys, and corresponding values. For any other value, a member
variable named scalar will contain the value.
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // outputs 'ciao'
?>
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.
See also the get_resource_type() function.
As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.
Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.
The special NULL value represents a variable with no value. NULL is the
only possible value of type null.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
There is only one value of type null, and that is the
case-insensitive constant NULL.
<?php
$var = NULL;
?>
NULL
Casting a variable to null using (unset) $var
will not remove the variable or unset its value.
It will only return a NULL value.
Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.
Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.
A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.
Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.
Example #1 Callback function examples
<?php
// An example callback function
function my_callback_function() {
echo 'hello world!';
}
// An example callback method
class MyClass {
static function myCallbackMethod() {
echo 'Hello World!';
}
}
// Type 1: Simple callback
call_user_func('my_callback_function');
// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));
// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));
// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');
// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
public static function who() {
echo "A\n";
}
}
class B extends A {
public static function who() {
echo "B\n";
}
}
call_user_func(array('B', 'parent::who')); // A
?>
Example #2 Callback example using a Closure
<?php
// Our closure
$double = function($a) {
return $a * 2;
};
// This is our range of numbers
$numbers = range(1, 5);
// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);
print implode(' ', $new_numbers);
?>
The above example will output:
2 4 6 8 10
Note: In PHP 4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.
Note:
Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback.
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means exactly the same.
void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.
$... in function prototypes means
and so on. This variable name is used when a function can
take an endless number of arguments.
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 string
echo $a; // bar
?>See the section titled String access by character for more information.
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
The casts allowed are:
(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 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.
See also the Userland Naming Guide.
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 NULL
var_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 => 25
var_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.
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.
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.
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.
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
<?php
function 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.
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
<?php
function test()
{
$a = 0;
echo $a;
$a++;
}
?>
This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Example #5 Example use of static variables
<?php
function 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
<?php
function 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
<?php
function 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.
The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?php
function test_global_ref() {
global $obj;
$obj = &new stdclass;
}
function test_global_noref() {
global $obj;
$obj = new stdclass;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>
The above example will output:
A similar behaviour applies to the static statement. References are not stored statically:
<?php
function &get_instance_ref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign a reference to the static variable
$obj = &new stdclass;
}
$obj->property++;
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Assign the object to the static variable
$obj = new stdclass;
}
$obj->property++;
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>
The above example will output:
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
<?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:
<?php
echo "$a ${$a}";
?>
produces the exact same output as:
<?php
echo "$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
<?php
class 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:
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.
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
<?php
if ($_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>
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.
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.
Example #4 A setcookie() example
<?php
if (isset($_COOKIE['count'])) {
$count = $_COOKIE['count'] + 1;
} else {
$count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>
Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:
<?php
$varname.ext; /* invalid variable name */
?>
For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
See also the Userland Naming Guide.
Example #1 Valid and invalid constant names
<?php
// Valid constant names
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");
// Invalid constant names
define("2FOO", "something");
// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__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.
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
TRUEand $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:
Example #1 Defining Constants
<?php
define("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.0
const 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.
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:
| 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). |
See also get_class(), get_object_vars(), file_exists() and function_exists().
Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following function:
<?php
function foo ()
{
return 5;
}
?>
Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports 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:
<?php
function double($i)
{
return $i*2;
}
$b = $a = 5; /* assign the value five into the variable $a and $b */
$c = $a++; /* post-increment, assign original value of $a
(5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of
$b (6) to $d and $e */
/* at this point, both $d and $e are equal to 6 */
$f = double($d++); /* assign twice the value of $d before
the increment, 2*6 = 12 to $f */
$g = double(++$e); /* assign twice the value of $e after
the increment, 2*7 = 14 to $g */
$h = $g += 10; /* first, $g is incremented by 10 and ends with the
value of 24. the value of the assignment (24) is
then assigned into $h, and $h ends with the value
of 24 as well. */
?>
Some expressions can be considered as statements. In this case, a statement has the form of 'expr ;' that is, an expression followed by a semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not a statement by itself. '$b = $a = 5;' however is a valid statement.
One last thing worth mentioning is the truth value of expressions.
In many events, mainly in conditional execution and loops, you're
not interested in the specific value of the expression, but only
care about whether it means TRUE or FALSE.
The constants TRUE and FALSE (case-insensitive) are the two
possible boolean values. When necessary, an expression is
automatically converted to boolean. See the
section about
type-casting for details about how.
PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.
An operator is something that 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.
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.
| Associativity | Operators | Additional Information |
|---|---|---|
| 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.
Remember basic arithmetic from school? These work just like those.
| 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:
<?php
echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2
?>
See also the manual page on Math functions.
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the 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 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 $a
print "$a\n"; // prints 3
print "$b\n"; // prints 3
$a = 4; // change $a
print "$a\n"; // prints 4
print "$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:
<?php
class 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 allow evaluation and manipulation of specific bits within an integer.
| 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
<?php
echo 12 ^ 9; // Outputs '5'
echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8
echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4
echo 2 ^ "3"; // Outputs 1
// 2 ^ ((int)"3") == 1
echo "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
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.
See also pack(), unpack(), gmp_and(), gmp_or(), gmp_xor(), gmp_testbit(), gmp_clrbit()
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.
| 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.
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>
For various types, comparison is done according to the following table (in order).
| 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 always
var_dump(1 == TRUE); // TRUE - same as (bool)1 == TRUE
var_dump(0 == FALSE); // TRUE - same as (bool)0 == FALSE
var_dump(100 < TRUE); // FALSE - same as (bool)100 < TRUE
var_dump(-10 < FALSE);// FALSE - same as (bool)-10 < FALSE
var_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 operators
function 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.
Because of the way floats are represented internally, you should not test two floats for equality.
See the documentation for float for more information.
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 statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
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 above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
If 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.
Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.
PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().
<?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.
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
NULLvalues has no effect too, but incrementing them results in 1.
| Example | Name | Effect |
|---|---|---|
| ++$a | Pre-increment | Increments $a by one, then returns $a. |
| $a++ | Post-increment | Returns $a, then increments $a by one. |
| --$a | Pre-decrement | Decrements $a by one, then returns $a. |
| $a-- | Post-decrement | Returns $a, then decrements $a by one. |
Here's a simple example script:
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in 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
<?php
echo '== Alphabets ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
echo ++$s . PHP_EOL;
}
// Digit characters behave differently
echo '== 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.
| 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)
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.
| 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 $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}
Elements of arrays are equal for the comparison if they have the same key and value.
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.
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:
Example #1 Using instanceof with classes
<?php
class 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
<?php
class 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
<?php
class 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
<?php
interface 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
<?php
interface 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 MyClass
var_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 integer
var_dump($b instanceof stdClass); // $b is NULL
var_dump($c instanceof stdClass); // $c is a resource
var_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
<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>
The above example will output:
bool(false)
The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.
See also get_class() and is_a().
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.
(PHP 4, PHP 5)
The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:
if (expr) statement
As described in the section about
expressions, expression is evaluated to its
Boolean value. If expression evaluates to TRUE,
PHP will execute statement, and if it evaluates
to FALSE - it'll ignore it. More information about what values evaluate
to FALSE can be found in the 'Converting to boolean'
section.
The following example would display a is bigger than b if $a is bigger than $b:
<?php
if ($a > $b)
echo "a is bigger than b";
?>
Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:
<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>
If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.
(PHP 4, PHP 5)
Often you'd want to execute a statement if a certain condition is
met, and a different statement if the condition is not met. This
is what else is for. else
extends an if statement to execute a statement
in case the expression in the if statement
evaluates to FALSE. For example, the following
code would display a is greater than
b if $a is greater than
$b, and a is NOT greater
than b otherwise:
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
FALSE, and if there were any
elseif expressions - only if they evaluated to
FALSE as well (see elseif).
(PHP 4, PHP 5)
elseif, as its name suggests, is a combination
of if and else. Like
else, it extends an if
statement to execute a different statement in case the original
if expression evaluates to
FALSE. However, unlike
else, it will execute that alternative
expression only if the elseif conditional
expression evaluates to TRUE. For example, the
following code would display a is bigger than
b, a equal to b
or a is smaller than b:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
There may be several elseifs within the same
if statement. The first
elseif expression (if any) that evaluates to
TRUE would be executed. In PHP, you can also
write 'else if' (in two words) and the behavior would be identical
to the one of 'elseif' (in a single word). The syntactic meaning
is slightly different (if you're familiar with C, this is the same
behavior) but the bottom line is that both would result in exactly
the same behavior.
The elseif statement is only executed if the
preceding if expression and any preceding
elseif expressions evaluated to
FALSE, and the current
elseif expression evaluated to
TRUE.
Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.
<?php
/* Incorrect Method: */
if($a > $b):
echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
echo "The above line causes a parse error.";
endif;
/* Correct Method: */
if($a > $b):
echo $a." is greater than ".$b;
elseif($a == $b): // Note the combination of the words.
echo $a." equals ".$b;
else:
echo $a." is neither greater than or equal to ".$b;
endif;
?>
(PHP 4, PHP 5)
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
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:
<?php
if ($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.
(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;
?>
(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:
<?php
do {
if ($i < 5) {
echo "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "i is ok";
/* process i */
} while (0);
?>
Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.
(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);
}
?>
(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:
<?php
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
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";
}
?>
(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:
(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;
}
}
?>
| 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. |
(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.
<?php
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip odd members
continue;
}
do_something_odd($value);
}
$i = 0;
while ($i++ < 5) {
echo "Outer<br />\n";
while (1) {
echo "Middle<br />\n";
while (1) {
echo "Inner<br />\n";
continue 3;
}
echo "This never gets output.<br />\n";
}
echo "Neither does this.<br />\n";
}
?>
Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>
One can expect the result to be:
0 1 3 4
but this script will output:
2
because the 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.)
| 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. |
(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
<?php
if ($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
<?php
switch ($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:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).
In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.
The statement list for a case can also be empty, which simply passes control into the statement list for the next case.
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>
A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.
The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.
<?php
switch ($i):
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
endswitch;
?>
It's possible to use a semicolon instead of a colon after a case like:
<?php
switch($beer)
{
case 'tuborg';
case 'carlsberg';
case 'heineken';
echo 'Good choice';
break;
default;
echo 'Please make a new selection...';
break;
}
?>
(PHP 4, PHP 5)
The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:
declare (directive)
statement
The directive section allows the behavior of the declare block to be set. Currently only two directives are recognized: the ticks directive (See below for more information on the ticks directive) and the encoding directive (See below for more information on the encoding directive).
Note: The encoding directive was added in PHP 5.3.0
The statement part of the declare block will be executed - how it is executed and what side effects occur during execution may depend on the directive set in the directive block.
The declare construct can also be used in the global scope, affecting all code following it (however if the file with declare was included then it does not affect the parent file).
<?php
// these are the same:
// you can use this:
declare(ticks=1) {
// entire script here
}
// or you can use this:
declare(ticks=1);
// entire script here
?>
A tick is an event that occurs for every
N low-level tickable statements executed
by the parser within the declare block.
The value for N is specified
using ticks=N
within the declare blocks's
directive section.
Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.
The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.
Example #1 Tick usage example
<?php
declare(ticks=1);
// A function called on each tick event
function tick_handler()
{
echo "tick_handler() called\n";
}
register_tick_function('tick_handler');
$a = 1;
if ($a > 0) {
$a += 2;
print($a);
}
?>
Example #2 Ticks usage example
<?php
function tick_handler()
{
echo "tick_handler() called\n";
}
$a = 1;
tick_handler();
if ($a > 0) {
$a += 2;
tick_handler();
print($a);
tick_handler();
}
tick_handler();
?>
See also register_tick_function() and unregister_tick_function().
A script's encoding can be specified per-script using the encoding directive.
Example #3 Declaring an encoding for the script.
<?php
declare(encoding='ISO-8859-1');
// code here
?>
When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.
The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte.
Note that PHP does not expose whether --enable-zend-multibyte was used to compile PHP other than by phpinfo().
See also zend.script_encoding.
(PHP 4, PHP 5)
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.
If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call. If return is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.
For more information, see Returning values.
Note: Note that since return is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.
Note: If no parameter is supplied, then the parentheses must be omitted and
NULLwill be returned. Calling return with parentheses but with no arguments will result in a parse error.
Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).
(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.
(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
<?php
echo "A $color $fruit"; // A
include '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
<?php
function 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 apple
echo "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.
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 PHP
include '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.
?>
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';
}
// works
if ((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.
See also require, require_once, include_once, get_included_files(), readfile(), virtual(), and include_path.
(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.
(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
<?php
include_once "a.php"; // this will include a.php
include_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.
(PHP 5 >= 5.3.0)
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
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>
The above example will output:
Bar
Example #2 goto loop example
<?php
for($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
<?php
goto 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.
A function may be defined using syntax such as the following:
Example #1 Pseudo code to demonstrate function uses
<?php
function 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]*.
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
<?php
function 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
<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>
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
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
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
<?php
function 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.'
?>
A function may define C++-style default values for scalar arguments as follows:
Example #3 Use of default parameters in functions
<?php
function 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
<?php
function 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
<?php
function 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
<?php
function 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.
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.
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
NULLwill be returned.
Example #1 Use of return
<?php
function 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
<?php
function 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
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
For more information on references, please check out References Explained.
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.
Example #1 Variable function example
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function 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
<?php
class 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
<?php
class 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.
?>
See also is_callable(), call_user_func(), variable variables and function_exists().
PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise 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
NULLbut this is just a convention, and cannot be relied upon.
See also function_exists(), the function reference, get_extension_funcs(), and dl().
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
<?php
echo 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.
| Version | Description |
|---|---|
| 5.4.0 | $this can be used in anonymous functions. |
| 5.3.0 | Anonymous functions become available. |
Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.
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
See also the Userland Naming Guide.
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
<?php
class 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
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// 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.
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 null
var_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
<?php
class 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)
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
<?php
class 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
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
<?php
namespace NS {
class ClassName {
}
echo ClassName::class;
}
?>
The above example will output:
NS\ClassName
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_STRICTwarning, 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
<?php
class SimpleClass
{
// invalid property declarations:
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
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 world
EOD;
}
?>
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
<?php
class foo {
// As of PHP 5.3.0
public $bar = <<<'EOT'
bar
EOT;
}
?>
Note:
Nowdoc support was added in PHP 5.3.0.
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
<?php
class 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
<?php
class foo {
// As of PHP 5.3.0
const BAR = <<<'EOT'
bar
EOT;
}
?>
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.
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:
Autoloading is not available if using PHP in CLI interactive mode.
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().
Example #1 Autoload example
This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
<?php
function __autoload($class_name) {
include $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Example #2 Autoload other example
This example attempts to load the interface ITest.
<?php
function __autoload($name) {
var_dump($name);
}
class Foo implements ITest {
}
/*
string(5) "ITest"
Fatal error: Interface 'ITest' not found in ...
*/
?>
Example #3 Autoloading with exception handling for 5.3.0+
This example throws an exception and demonstrates the try/catch block.
<?php
function __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. Unable 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.
<?php
function __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. Want to load MissingException. Fatal error: Class 'MissingException' not found in testMissingException.php on line 4
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
<?php
class 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
<?php
namespace 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
}
}
?>
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
<?php
class 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 HTTP headers already sent. The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).
Note:
Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public.
Example #1 Property declaration
<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public, Protected2, Undefined
?>
Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an
E_STRICTwarning.
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
Example #2 Method Declaration
<?php
/**
* Define MyClass
*/
class MyClass
{
// Declare a public constructor
public function __construct() { }
// Declare a public method
public function MyPublic() { }
// Declare a protected method
protected function MyProtected() { }
// Declare a private method
private function MyPrivate() { }
// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// This is public
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublic\n";
}
private function testPrivate() {
echo "Bar::testPrivate\n";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}
private function testPrivate() {
echo "Foo::testPrivate\n";
}
}
$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>
Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.
Example #3 Accessing private members of the same object type
<?php
class Test
{
private $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
private function bar()
{
echo 'Accessed the private method.';
}
public function baz(Test $other)
{
// We can change the private property:
$other->foo = 'hello';
var_dump($other->foo);
// We can also call the private method:
$other->bar();
}
}
$test = new Test('test');
$test->baz(new Test('other'));
?>
The above example will output:
string(5) "hello" Accessed the private method.
Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.
For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.
Note:
Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.
Example #1 Inheritance Example
<?php
class foo
{
public function printItem($string)
{
echo 'Foo: ' . $string . PHP_EOL;
}
public function printPHP()
{
echo 'PHP is great.' . PHP_EOL;
}
}
class bar extends foo
{
public function printItem($string)
{
echo 'Bar: ' . $string . PHP_EOL;
}
}
$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP(); // Output: 'PHP is great'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP(); // Output: 'PHP is great'
?>
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
When referencing these items from outside the class definition, use the name of the class.
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).
Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!
Example #1 :: from outside the class definition
<?php
class MyClass {
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0
echo MyClass::CONST_VALUE;
?>
Three special keywords self, parent and static are used to access properties or methods from inside the class definition.
Example #2 :: from inside the class definition
<?php
class OtherClass extends MyClass
{
public static $my_static = 'static var';
public static function doubleColon() {
echo parent::CONST_VALUE . "\n";
echo self::$my_static . "\n";
}
}
$classname = 'OtherClass';
echo $classname::doubleColon(); // As of PHP 5.3.0
OtherClass::doubleColon();
?>
When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.
Example #3 Calling a parent's method
<?php
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()\n";
}
}
class OtherClass extends MyClass
{
// Override parent's definition
public function myFunc()
{
// But still call the parent function
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}
$class = new OtherClass();
$class->myFunc();
?>
See also some examples of static call trickery.
This page describes the use of the static keyword to define static methods and properties. static can also be used to define static variables and for late static bindings. Please refer to those pages for information on those meanings of static.
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
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 Static property example
<?php
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
class Bar extends Foo
{
public function fooStatic() {
return parent::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
Example #2 Static method example
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.
Example #1 Abstract class example
<?php
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
public function getValue() {
return "ConcreteClass2";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>
The above example will output:
ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2
Example #2 Abstract class example
<?php
abstract class AbstractClass
{
// Our abstract method only needs to define the required arguments
abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
// Our child class may define optional arguments not in the parent's signature
public function prefixName($name, $separator = ".") {
if ($name == "Pacman") {
$prefix = "Mr";
} elseif ($name == "Pacwoman") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>
The above example will output:
Mr. Pacman Mrs. Pacwoman
Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface.
To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
Note:
Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.
Note:
Interfaces can be extended like classes using the extends operator.
Note:
The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.
It's possible for interfaces to have constants. Interface constants works exactly like class constants except they cannot be overridden by a class/interface that inherits them.
Example #1 Interface example
<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
Example #2 Extendable Interfaces
<?php
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// This will work
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// This will not work and result in a fatal error
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?>
Example #3 Multiple interface inheritance
<?php
interface a
{
public function foo();
}
interface b
{
public function bar();
}
interface c extends a, b
{
public function baz();
}
class d implements c
{
public function foo()
{
}
public function bar()
{
}
public function baz()
{
}
}
?>
Example #4 Interfaces with constants
<?php
interface a
{
const b = 'Interface constant';
}
// Prints: Interface constant
echo a::b;
// This will however not work because it's not allowed to
// override constants.
class b implements a
{
const b = 'Class constant';
}
?>
An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.
As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.
Example #1 Trait example
<?php
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
?>
An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in return override inherited methods.
Example #2 Precedence Order Example
An inherited method from a base class is overridden by the method inserted into MyHelloWorld from the SayWorld Trait. The behavior is the same for methods defined in the MyHelloWorld class. The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.
<?php
class Base {
public function sayHello() {
echo 'Hello ';
}
}
trait SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}
class MyHelloWorld extends Base {
use SayWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
?>
The above example will output:
Hello World!
Example #3 Alternate Precedence Order Example
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
class TheWorldIsNotEnough {
use HelloWorld;
public function sayHello() {
echo 'Hello Universe!';
}
}
$o = new TheWorldIsNotEnough();
$o->sayHello();
?>
The above example will output:
Hello Universe!
Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.
Example #4 Multiple Traits Usage
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>
The above example will output:
Hello World!
If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved.
To resolve naming conflicts between Traits used in the same class, the insteadof operator needs to be used to chose exactly one of the conflicting methods.
Since this only allows one to exclude methods, the as operator can be used to allow the inclusion of one of the conflicting methods under another name.
Example #5 Conflict Resolution
In this example, Talker uses the traits A and B. Since A and B have conflicting methods, it defines to use the variant of smallTalk from trait B, and the variant of bigTalk from trait A.
The Aliased_Talker makes use of the as operator to be able to use B's bigTalk implementation under an additional alias talk.
<?php
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
class Aliased_Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
B::bigTalk as talk;
}
}
?>
Using the as syntax, one can also adjust the visibility of the method in the exhibiting class.
Example #6 Changing Method Visibility
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
// Change visibility of sayHello
class MyClass1 {
use HelloWorld { sayHello as protected; }
}
// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
use HelloWorld { sayHello as private myPrivateHello; }
}
?>
Just as classes can make use of traits, so can other traits. By using one or more traits in a trait definition, it can be composed partially or entirely of the members defined in those other traits.
Example #7 Traits Composed from Traits
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World!';
}
}
trait HelloWorld {
use Hello, World;
}
class MyHelloWorld {
use HelloWorld;
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>
The above example will output:
Hello World!
Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.
Example #8 Express Requirements by Abstract Methods
<?php
trait Hello {
public function sayHelloWorld() {
echo 'Hello'.$this->getWorld();
}
abstract public function getWorld();
}
class MyHelloWorld {
private $world;
use Hello;
public function getWorld() {
return $this->world;
}
public function setWorld($val) {
$this->world = $val;
}
}
?>
Traits can define both static members and static methods.
Example #9 Static Variables
<?php
trait Counter {
public function inc() {
static $c = 0;
$c = $c + 1;
echo "$c\n";
}
}
class C1 {
use Counter;
}
class C2 {
use Counter;
}
$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>
Example #10 Static Methods
<?php
trait StaticExample {
public static function doSomething() {
return 'Doing something';
}
}
class Example {
use StaticExample;
}
Example::doSomething();
?>
Traits can also define properties.
Example #11 Defining Properties
<?php
trait PropertiesTrait {
public $x = 1;
}
class PropertiesExample {
use PropertiesTrait;
}
$example = new PropertiesExample;
$example->x;
?>
If a trait defines a property then a class can not define a property with
the same name, otherwise an error is issued. It is an
E_STRICT if the class definition is compatible (same
visibility and initial value) or fatal error otherwise.
Example #12 Conflict Resolution
<?php
trait PropertiesTrait {
public $same = true;
public $different = false;
}
class PropertiesExample {
use PropertiesTrait;
public $same = true; // Strict Standards
public $different = true; // Fatal error
}
?>
Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.
The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.
All overloading methods must be defined as public.
Note:
None of the arguments of these magic methods can be passed by reference.
Note:
PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.
| Version | Description |
|---|---|
| 5.3.0 | Added __callStatic(). Added warning to enforce public visibility and non-static declaration. |
| 5.1.0 | Added __isset() and __unset(). Added support for __get() for overloading of private properties. |
| 5.0.0 | Added __get(). |
$name
)$name
)__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
__isset() is triggered by calling isset() or empty() on inaccessible properties.
__unset() is invoked when unset() is used on inaccessible properties.
The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to.
Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.
Note:
The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignments together like this:
$a = $obj->b = 8;
Example #1 Overloading properties via the __get(), __set(), __isset() and __unset() methods
<?php
class PropertyTest
{
/** Location for overloaded data. */
private $data = array();
/** Overloading not used on declared properties. */
public $declared = 1;
/** Overloading only used on this when accessed outside the class. */
private $hidden = 2;
public function __set($name, $value)
{
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}
public function __get($name)
{
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
/** As of PHP 5.1.0 */
public function __isset($name)
{
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
/** As of PHP 5.1.0 */
public function __unset($name)
{
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}
/** Not a magic method, just here for example. */
public function getHidden()
{
return $this->hidden;
}
}
echo "<pre>\n";
$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n\n";
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";
echo $obj->declared . "\n\n";
echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>
The above example will output:
Setting 'a' to '1' Getting 'a' 1 Is 'a' set? bool(true) Unsetting 'a' Is 'a' set? bool(false) 1 Let's experiment with the private property named 'hidden': Privates are visible inside the class, so __get() not used... 2 Privates not visible outside of class, so __get() is used... Getting 'hidden' Notice: Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29
__call() is triggered when invoking inaccessible methods in an object context.
__callStatic() is triggered when invoking inaccessible methods in a static context.
The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.
Example #2 Overloading methods via the __call() and __callStatic() methods
<?php
class MethodTest
{
public function __call($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments)
{
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}
$obj = new MethodTest;
$obj->runTest('in object context');
MethodTest::runTest('in static context'); // As of PHP 5.3.0
?>
The above example will output:
Calling object method 'runTest' in object context Calling static method 'runTest' in static context
PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.
Example #1 Simple Object Iteration
<?php
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
protected $protected = 'protected var';
private $private = 'private var';
function iterateVisible() {
echo "MyClass::iterateVisible:\n";
foreach($this as $key => $value) {
print "$key => $value\n";
}
}
}
$class = new MyClass();
foreach($class as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$class->iterateVisible();
?>
The above example will output:
var1 => value 1 var2 => value 2 var3 => value 3 MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected var private => private var
As the output shows, the foreach iterated through all of the visible properties that could be accessed.
To take it a step further, the Iterator interface may be implemented. This allows the object to dictate how it will be iterated and what values will be available on each iteration.
Example #2 Object Iteration implementing Iterator
<?php
class MyIterator implements Iterator
{
private $var = array();
public function __construct($array)
{
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind()
{
echo "rewinding\n";
reset($this->var);
}
public function current()
{
$var = current($this->var);
echo "current: $var\n";
return $var;
}
public function key()
{
$var = key($this->var);
echo "key: $var\n";
return $var;
}
public function next()
{
$var = next($this->var);
echo "next: $var\n";
return $var;
}
public function valid()
{
$key = key($this->var);
$var = ($key !== NULL && $key !== FALSE);
echo "valid: $var\n";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b\n";
}
?>
The above example will output:
rewinding valid: 1 current: 1 key: 0 0: 1 next: 2 valid: 1 current: 2 key: 1 1: 2 next: 3 valid: 1 current: 3 key: 2 2: 3 next: valid:
The IteratorAggregate interface can be used as an alternative to implementing all of the Iterator methods. IteratorAggregate only requires the implementation of a single method, IteratorAggregate::getIterator(), which should return an instance of a class implementing Iterator.
Example #3 Object Iteration implementing IteratorAggregate
<?php
class MyCollection implements IteratorAggregate
{
private $items = array();
private $count = 0;
// Required definition of interface IteratorAggregate
public function getIterator() {
return new MyIterator($this->items);
}
public function add($value) {
$this->items[$this->count++] = $value;
}
}
$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');
foreach ($coll as $key => $val) {
echo "key/value: [$key -> $val]\n\n";
}
?>
The above example will output:
rewinding current: value 1 valid: 1 current: value 1 key: 0 key/value: [0 -> value 1] next: value 2 current: value 2 valid: 1 current: value 2 key: 1 key/value: [1 -> value 2] next: value 3 current: value 3 valid: 1 current: value 3 key: 2 key/value: [2 -> value 3] next: current: valid:
Note:
For more examples of iterators, see the SPL Extension.
Note:
Users of PHP 5.5 and later may also want to investigate generators, which provide an alternative way of defining iterators.
The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
serialize() checks if your class has a function with
the magic name __sleep(). If so, that function is
executed prior to any serialization. It can clean up the object
and is supposed to return an array with the names of all variables
of that object that should be serialized.
If the method doesn't return anything then NULL is serialized and
E_NOTICE is issued.
Note:
It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an
E_NOTICElevel error. Instead you may use the Serializable interface.
The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Example #1 Sleep and wakeup
<?php
class Connection
{
protected $link;
private $dsn, $username, $password;
public function __construct($dsn, $username, $password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
$this->link = new PDO($this->dsn, $this->username, $this->password);
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
}?>
The __toString() method allows a class to decide
how it will react when it is treated like a string. For example,
what echo $obj; will print. This method must
return a string, as otherwise a fatal E_RECOVERABLE_ERROR
level error is emitted.
You cannot throw an exception from within a __toString() method. Doing so will result in a fatal error.
Example #2 Simple example
<?php
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function __toString()
{
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
The above example will output:
Hello
It is worth noting that before PHP 5.2.0 the __toString()
method was only called when it was directly combined with
echo or print.
Since PHP 5.2.0, it is called in any string context (e.g. in
printf() with %s modifier) but not
in other types contexts (e.g. with %d modifier).
Since PHP 5.2.0, converting objects without __toString()
method to string would cause E_RECOVERABLE_ERROR.
The __invoke() method is called when a script tries to call an object as a function.
Note:
This feature is available since PHP 5.3.0.
Example #3 Using __invoke()
<?php
class CallableClass
{
public function __invoke($x)
{
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>
The above example will output:
int(5) bool(true)
$properties
)This static method is called for classes exported by var_export() since PHP 5.1.0.
The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).
Example #4 Using __set_state() (since PHP 5.1.0)
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array) // As of PHP 5.1.0
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>
The above example will output:
object(A)#2 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Example #1 Final methods example
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>
Example #2 Final class example
<?php
final class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
// Here it doesn't matter if you specify the function as final or not
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>
Note: Properties cannot be declared final, only classes and methods may be declared as final.
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.
An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
$copy_of_object = clone $object;
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.
Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
Example #1 Cloning an object
<?php
class SubObject
{
static $instances = 0;
public $instance;
public function __construct() {
$this->instance = ++self::$instances;
}
public function __clone() {
$this->instance = ++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;
function __clone()
{
// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone $this->object1;
}
}
$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;
print("Original Object:\n");
print_r($obj);
print("Cloned Object:\n");
print_r($obj2);
?>
The above example will output:
Original Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 1
)
[object2] => SubObject Object
(
[instance] => 2
)
)
Cloned Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
)
[object2] => SubObject Object
(
[instance] => 2
)
)
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
An example will clarify these rules.
Example #1 Example of object comparison in PHP 5
<?php
function bool2str($bool)
{
if ($bool === false) {
return 'FALSE';
} else {
return 'TRUE';
}
}
function compareObjects(&$o1, &$o2)
{
echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}
class Flag
{
public $flag;
function Flag($flag = true) {
$this->flag = $flag;
}
}
class OtherFlag
{
public $flag;
function OtherFlag($flag = true) {
$this->flag = $flag;
}
}
$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();
echo "Two instances of the same class\n";
compareObjects($o, $p);
echo "\nTwo references to the same instance\n";
compareObjects($o, $q);
echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>
The above example will output:
Two instances of the same class o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : FALSE o1 !== o2 : TRUE Two references to the same instance o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE Instances of two different classes o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE
Note:
Extensions can define own rules for their objects comparison (==).
PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.
If class or interface is specified as type hint then all its children or implementations are allowed too.
Type hints can not be used with scalar types such as int or string. Resources and Traits are not allowed either.
Example #1 Type Hinting examples
<?php
// An example class
class MyClass
{
/**
* A test function
*
* First parameter must be an object of type OtherClass
*/
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
/**
* Another test function
*
* First parameter must be an array
*/
public function test_array(array $input_array) {
print_r($input_array);
}
/**
* First parameter must be iterator
*/
public function test_interface(Traversable $iterator) {
echo get_class($iterator);
}
/**
* First parameter must be callable
*/
public function test_callable(callable $callback, $data) {
call_user_func($callback, $data);
}
}
// Another example class
class OtherClass {
public $var = 'Hello World';
}
?>
Failing to satisfy the type hint results in a catchable fatal error.
<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;
// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');
// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);
// Fatal Error: Argument 1 must not be null
$myclass->test(null);
// Works: Prints Hello World
$myclass->test($otherclass);
// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');
// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
// Works: Prints ArrayObject
$myclass->test_interface(new ArrayObject(array()));
// Works: Prints int(1)
$myclass->test_callable('var_dump', 1);
?>
Type hinting also works with functions:
<?php
// An example class
class MyClass {
public $var = 'Hello World';
}
/**
* A test function
*
* First parameter must be an object of type MyClass
*/
function myFunction(MyClass $foo) {
echo $foo->var;
}
// Works
$myclass = new MyClass;
myFunction($myclass);
?>
Type hinting allowing NULL value:
<?php
/* Accepting NULL value */
function test(stdClass $obj = NULL) {
}
test(NULL);
test(new stdClass);
?>
As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.
More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.
This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.
Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined:
Example #1 self:: usage
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
The above example will output:
A
Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to reference B from test() in the previous example. It was decided not to introduce a new keyword but rather use static that was already reserved.
Example #2 static:: simple usage
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
The above example will output:
B
Note:
In non-static contexts, the called class will be the class of the object instance. Since $this-> will try to call private methods from the same scope, using static:: may give different results. Another difference is that static:: can only refer to static properties.
Example #3 static:: usage in a non-static context
<?php
class A {
private function foo() {
echo "success!\n";
}
public function test() {
$this->foo();
static::foo();
}
}
class B extends A {
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
class C extends A {
private function foo() {
/* original method is replaced; the scope of the new one is C */
}
}
$b = new B();
$b->test();
$c = new C();
$c->test(); //fails
?>
The above example will output:
success! success! success! Fatal error: Call to private method C::foo() from context 'A' in /tmp/test.php on line 9
Note:
Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.
Example #4 Forwarding and non-forwarding calls
<?php
class A {
public static function foo() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
class B extends A {
public static function test() {
A::foo();
parent::foo();
self::foo();
}
public static function who() {
echo __CLASS__."\n";
}
}
class C extends B {
public static function who() {
echo __CLASS__."\n";
}
}
C::test();
?>The above example will output:
A C C
One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
Example #1 References and Objects
<?php
class A {
public $foo = 1;
}
$a = new A;
$b = $a; // $a and $b are copies of the same identifier
// ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";
$c = new A;
$d = &$c; // $c and $d are references
// ($c,$d) = <id>
$d->foo = 2;
echo $c->foo."\n";
$e = new A;
function foo($obj) {
// ($obj) = ($e) = <id>
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
The above example will output:
2 2 2
serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class.
In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserialize this in another file, an object of class A, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of the spl_autoload_register() function.
<?php
// classa.inc:
class A {
public $one = 1;
public function show_one() {
echo $this->one;
}
}
// page1.php:
include("classa.inc");
$a = new A;
$s = serialize($a);
// store $s somewhere where page2.php can find it.
file_put_contents('store', $s);
// page2.php:
// this is needed for the unserialize to work properly.
include("classa.inc");
$s = file_get_contents('store');
$a = unserialize($s);
// now use the function show_one() of the $a object.
$a->show_one();
?>
If an application is using sessions and uses session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This means that these objects can show up on any of the application's pages once they become part of the session. However, the session_register() is removed since PHP 5.4.0.
It is strongly recommended that if an application serializes objects, for use later in the application, that the application includes the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object useless.
So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.
Beyond the above advice, note that you can also hook into the serialization and unserialization events on an object using the __sleep() and __wakeup() methods. Using __sleep() also allows you to only serialize a subset of the object's properties.
Changes to the PHP 5 OOP model are logged here. Descriptions and other notes regarding these features are documented within the OOP 5 documentation.
| Version | Description |
|---|---|
| 5.4.0 | Added: traits. |
| 5.4.0 | Changed: If an abstract class defines a signature for the constructor it will now be enforced. |
| 5.3.3 | Changed: 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. |
| 5.3.0 | Changed: Classes that implement interfaces with methods that have default values in the prototype are no longer required to match the interface's default value. |
| 5.3.0 | Changed: It's now possible to reference the class using a variable (e.g., echo $classname::constant;). The variable's value can not be a keyword (e.g., self, parent or static). |
| 5.3.0 |
Changed: An E_WARNING level error is issued if
the magic overloading
methods are declared static.
It also enforces the public visibility requirement.
|
| 5.3.0 | Changed: 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. Exceptions now thrown in the __autoload function can be caught in the catch block, with one provison. 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. |
| 5.3.0 | Added: The __callStatic method. |
| 5.3.0 | Added: heredoc and nowdoc support for class const and property definitions. Note: heredoc values must follow the same rules as double-quoted strings, (e.g., no variables within). |
| 5.3.0 | Added: Late Static Bindings. |
| 5.3.0 | Added: The __invoke() method. |
| 5.2.0 |
Changed: The __toString()
method was only called when it was directly combined with
echo or print.
But now, it is called in any string context (e.g. in
printf() with %s modifier) but not
in other types contexts (e.g. with %d modifier).
Since PHP 5.2.0, converting objects without a __toString
method to string emits a E_RECOVERABLE_ERROR level error.
|
| 5.1.3 |
Changed: In previous versions of PHP 5, the use of var
was considered deprecated and would issue an E_STRICT
level error. It's no longer deprecated, therefore does not emit the error.
|
| 5.1.0 | Changed: The __set_state() static method is now called for classes exported by var_export(). |
| 5.1.0 | Added: The __isset() and __unset() methods. |
(PHP 5 >= 5.3.0)
What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP:
Example #1 Namespace syntax example
<?php
namespace my\name; // see "Defining Namespaces" section
class MyClass {}
function myfunction() {}
const MYCONST = 1;
$a = new MyClass;
$c = new \my\name\MyClass; // see "Global Space" section
$a = strlen('hi'); // see "Using namespaces: fallback to global
// function/constant" section
$d = namespace\MYCONST; // see "namespace operator and __NAMESPACE__
// constant" section
$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // see "Namespaces and dynamic language features" section
?>
Note:
Namespace names PHP and php, and compound names starting with these names (like PHP\Classes) are reserved for internal language use and should not be used in the userspace code.
(PHP 5 >= 5.3.0)
Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants.
Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.
Example #1 Declaring a single namespace
<?php
namespace MyProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
Example #2 Declaring a single namespace
<html>
<?php
namespace MyProject; // fatal error - namespace must be the first statement in the script
?>
In addition, unlike any other PHP construct, the same namespace may be defined in multiple files, allowing splitting up of a namespace's contents across the filesystem.
(PHP 5 >= 5.3.0)
Much like directories and files, PHP namespaces also contain the ability to specify a hierarchy of namespace names. Thus, a namespace name can be defined with sub-levels:
Example #1 Declaring a single namespace with hierarchy
<?php
namespace MyProject\Sub\Level;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
(PHP 5 >= 5.3.0)
Multiple namespaces may also be declared in the same file. There are two allowed syntaxes.
Example #1 Declaring multiple namespaces, simple combination syntax
<?php
namespace MyProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
namespace AnotherProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.
Example #2 Declaring multiple namespaces, bracketed syntax
<?php
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace AnotherProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
?>
It is strongly discouraged as a coding practice to combine multiple namespaces into the same file. The primary use case is to combine multiple PHP scripts into the same file.
To combine global non-namespaced code with namespaced code, only bracketed syntax is supported. Global code should be encased in a namespace statement with no namespace name as in:
Example #3 Declaring multiple namespaces and unnamespaced code
<?php
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>
No PHP code may exist outside of the namespace brackets except for an opening declare statement.
Example #4 Declaring multiple namespaces and unnamespaced code
<?php
declare(encoding='UTF-8');
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>
(PHP 5 >= 5.3.0)
Before discussing the use of namespaces, it is important to understand how PHP knows which namespaced element your code is requesting. A simple analogy can be made between PHP namespaces and a filesystem. There are three ways to access a file in a file system:
Here is an example of the three kinds of syntax in actual code:
file1.php
<?php
namespace Foo\Bar\subnamespace;
const FOO = 1;
function foo() {}
class foo
{
static function staticmethod() {}
}
?>
file2.php
<?php
namespace Foo\Bar;
include 'file1.php';
const FOO = 2;
function foo() {}
class foo
{
static function staticmethod() {}
}
/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO; // resolves to constant Foo\Bar\FOO
/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
// method staticmethod
echo subnamespace\FOO; // resolves to constant Foo\Bar\subnamespace\FOO
/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO
?>
Note that to access any global class, function or constant, a fully qualified name can be used, such as \strlen() or \Exception or \INI_ALL.
Example #1 Accessing global classes, functions and constants from within a namespace
<?php
namespace Foo;
function strlen() {}
const INI_ALL = 3;
class Exception {}
$a = \strlen('hi'); // calls global function strlen
$b = \INI_ALL; // accesses global constant INI_ALL
$c = new \Exception('error'); // instantiates global class Exception
?>
(PHP 5 >= 5.3.0)
PHP's implementation of namespaces is influenced by its dynamic nature as a programming language. Thus, to convert code like the following example into namespaced code:
Example #1 Dynamically accessing elements
example1.php:
<?php
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "global";
$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
?>
Example #2 Dynamically accessing namespaced elements
<?php
namespace namespacename;
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "namespaced";
include 'example1.php';
$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a = '\namespacename\classname';
$obj = new $a; // prints namespacename\classname::__construct
$a = 'namespacename\classname';
$obj = new $a; // also prints namespacename\classname::__construct
$b = 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b = '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"; // prints namespaced
echo constant('namespacename\constname'), "\n"; // also prints namespaced
?>
Be sure to read the note about escaping namespace names in strings.
(PHP 5 >= 5.3.0)
PHP supports two ways of abstractly accessing elements within the current namespace,
the __NAMESPACE__ magic constant, and the namespace
keyword.
The value of __NAMESPACE__ is a string that contains the current
namespace name. In global, un-namespaced code, it contains an empty string.
Example #1 __NAMESPACE__ example, namespaced code
<?php
namespace MyProject;
echo '"', __NAMESPACE__, '"'; // outputs "MyProject"
?>
Example #2 __NAMESPACE__ example, global code
<?php
echo '"', __NAMESPACE__, '"'; // outputs ""
?>
__NAMESPACE__ constant is useful for dynamically constructing
names, for instance:
Example #3 using __NAMESPACE__ for dynamic name construction
<?php
namespace MyProject;
function get($classname)
{
$a = __NAMESPACE__ . '\\' . $classname;
return new $a;
}
?>
The namespace keyword can be used to explicitly request an element from the current namespace or a sub-namespace. It is the namespace equivalent of the self operator for classes.
Example #4 the namespace operator, inside a namespace
<?php
namespace MyProject;
use blah\blah as mine; // see "Using namespaces: importing/aliasing"
blah\mine(); // calls function MyProject\blah\mine()
namespace\blah\mine(); // calls function MyProject\blah\mine()
namespace\func(); // calls function MyProject\func()
namespace\sub\func(); // calls function MyProject\sub\func()
namespace\cname::method(); // calls static method "method" of class MyProject\cname
$a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname
$b = namespace\CONSTANT; // assigns value of constant MyProject\CONSTANT to $b
?>
Example #5 the namespace operator, in global code
<?php
namespace\func(); // calls function func()
namespace\sub\func(); // calls function sub\func()
namespace\cname::method(); // calls static method "method" of class cname
$a = new namespace\sub\cname(); // instantiates object of class sub\cname
$b = namespace\CONSTANT; // assigns value of constant CONSTANT to $b
?>
(PHP 5 >= 5.3.0)
The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.
PHP namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. Note that importing a function or constant is not supported.
In PHP, aliasing is accomplished with the use operator. Here is an example showing all 3 kinds of importing:
Example #1 importing/aliasing with the use operator
<?php
namespace foo;
use My\Full\Classname as Another;
// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;
// importing a global class
use ArrayObject;
$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
?>
PHP additionally supports a convenience shortcut to place multiple use statements on the same line
Example #2 importing/aliasing with the use operator, multiple use statements combined
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>
Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.
Example #3 Importing and dynamic names
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = new $a; // instantiates object of class Another
?>
In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.
Example #4 Importing and fully qualified names
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:
Example #5 Illegal importing rule
<?php
namespace Languages;
class Greenlandic
{
use Languages\Danish;
...
}
?>
Note:
Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.
(PHP 5 >= 5.3.0)
Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.
Example #1 Using global space specification
<?php
namespace A\B\C;
/* This function is A\B\C\fopen */
function fopen() {
/* ... */
$f = \fopen(...); // call global fopen
return $f;
}
?>
(PHP 5 >= 5.3.0)
Inside a namespace, when PHP encounters an unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, one must refer to them with their fully qualified Name as in:
Example #1 Accessing global classes inside a namespace
<?php
namespace A\B\C;
class Exception extends \Exception {}
$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception
$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>
For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.
Example #2 global functions/constants fallback inside a namespace
<?php
namespace A\B\C;
const E_ERROR = 45;
function strlen($str)
{
return \strlen($str) - 1;
}
echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL
echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
?>
(PHP 5 >= 5.3.0)
For the purposes of these resolution rules, here are some important definitions:
This is an identifier without a namespace separator, such as Foo
This is an identifier with a namespace separator, such as Foo\Bar
This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. The namespace \Foo is also a fully qualified name.
Names are resolved following these resolution rules:
Example #1 Name resolutions illustrated
<?php
namespace A;
use B\D, C\E as F;
// function calls
foo(); // first tries to call "foo" defined in namespace "A"
// then calls global function "foo"
\foo(); // calls function "foo" defined in global scope
my\foo(); // calls function "foo" defined in namespace "A\my"
F(); // first tries to call "F" defined in namespace "A"
// then calls global function "F"
// class references
new B(); // creates object of class "B" defined in namespace "A"
// if not found, it tries to autoload class "A\B"
new D(); // using import rules, creates object of class "D" defined in namespace "B"
// if not found, it tries to autoload class "B\D"
new F(); // using import rules, creates object of class "E" defined in namespace "C"
// if not found, it tries to autoload class "C\E"
new \B(); // creates object of class "B" defined in global scope
// if not found, it tries to autoload class "B"
new \D(); // creates object of class "D" defined in global scope
// if not found, it tries to autoload class "D"
new \F(); // creates object of class "F" defined in global scope
// if not found, it tries to autoload class "F"
// static methods/namespace functions from another namespace
B\foo(); // calls function "foo" from namespace "A\B"
B::foo(); // calls method "foo" of class "B" defined in namespace "A"
// if class "A\B" not found, it tries to autoload class "A\B"
D::foo(); // using import rules, calls method "foo" of class "D" defined in namespace "B"
// if class "B\D" not found, it tries to autoload class "B\D"
\B\foo(); // calls function "foo" from namespace "B"
\B::foo(); // calls method "foo" of class "B" from global scope
// if class "B" not found, it tries to autoload class "B"
// static methods/namespace functions of current namespace
A\B::foo(); // calls method "foo" of class "B" from namespace "A\A"
// if class "A\A\B" not found, it tries to autoload class "A\A\B"
\A\B::foo(); // calls method "foo" of class "B" from namespace "A"
// if class "A\B" not found, it tries to autoload class "A\B"
?>
(PHP 5 >= 5.3.0)
This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully.
First, the common questions.
There are a few implementation details of the namespace implementations that are helpful to understand.
No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:
Example #1 Accessing global classes outside a namespace
<?php
$a = new \stdClass;
?>
This is functionally equivalent to:
Example #2 Accessing global classes outside a namespace
<?php
$a = new stdClass;
?>
Example #3 Accessing internal classes in namespaces
<?php
namespace foo;
$a = new \stdClass;
function test(\ArrayObject $typehintexample = null) {}
$a = \DirectoryIterator::CURRENT_AS_FILEINFO;
// extending an internal or global class
class MyException extends \Exception {}
?>
Example #4 Accessing internal classes, functions or constants in namespaces
<?php
namespace foo;
class MyClass {}
// using a class from the current namespace as a type hint
function test(MyClass $typehintexample = null) {}
// another way to use a class from the current namespace as a type hint
function test(\foo\MyClass $typehintexample = null) {}
// extending a class from the current namespace
class Extended extends MyClass {}
// accessing a global function
$a = \globalfunc();
// accessing a global constant
$b = \INI_ALL;
?>
Names that begin with a \ always resolve to what they look like, so \my\name is in fact my\name, and \Exception is Exception.
Example #5 Fully Qualified names
<?php
namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL; // $a is set to the value of constant "INI_ALL"
?>
Names that contain a backslash but do not begin with a backslash like my\name can be resolved in 2 different ways.
If there is an import statement that aliases another name to my, then the import alias is applied to the my in my\name.
Otherwise, the current namespace name is prepended to my\name.
Example #6 Qualified names
<?php
namespace foo;
use blah\blah as foo;
$a = new my\name(); // instantiates "foo\my\name" class
foo\bar::name(); // calls static method "name" in class "blah\blah\bar"
my\bar(); // calls function "foo\my\bar"
$a = my\BAR; // sets $a to the value of constant "foo\my\BAR"
?>
Class names that do not contain a backslash like name can be resolved in 2 different ways.
If there is an import statement that aliases another name to name, then the import alias is applied.
Otherwise, the current namespace name is prepended to name.
Example #7 Unqualified class names
<?php
namespace foo;
use blah\blah as foo;
$a = new name(); // instantiates "foo\name" class
foo::name(); // calls static method "name" in class "blah\blah"
?>
Function or constant names that do not contain a backslash like name can be resolved in 2 different ways.
First, the current namespace name is prepended to name.
Finally, if the constant or function name does not exist in the current namespace, a global constant or function name is used if it exists.
Example #8 Unqualified function or constant names
<?php
namespace foo;
use blah\blah as foo;
const FOO = 1;
function my() {}
function foo() {}
function sort(&$a)
{
\sort($a); // calls the global function "sort"
$a = array_flip($a);
return $a;
}
my(); // calls "foo\my"
$a = strlen('hi'); // calls global function "strlen" because "foo\strlen" does not exist
$arr = array(1,3,2);
$b = sort($arr); // calls function "foo\sort"
$c = foo(); // calls function "foo\foo" - import is not applied
$a = FOO; // sets $a to value of constant "foo\FOO" - import is not applied
$b = INI_ALL; // sets $b to value of global constant "INI_ALL"
?>
The following script combinations are legal:
file1.php
<?php
namespace my\stuff;
class MyClass {}
?>
another.php
<?php
namespace another;
class thing {}
?>
file2.php
<?php
namespace my\stuff;
include 'file1.php';
include 'another.php';
use another\thing as MyClass;
$a = new MyClass; // instantiates class "thing" from namespace another
?>
There is no name conflict, even though the class MyClass exists within the my\stuff namespace, because the MyClass definition is in a separate file. However, the next example causes a fatal error on name conflict because MyClass is defined in the same file as the use statement.
<?php
namespace my\stuff;
use another\thing as MyClass;
class MyClass {} // fatal error: MyClass conflicts with import statement
$a = new MyClass;
?>
PHP does not allow nesting namespaces
<?php
namespace my\stuff {
namespace nested {
class foo {}
}
}
?>
<?php
namespace my\stuff\nested {
class foo {}
}
?>
The only elements that are affected by use statements are namespaces and class names. In order to shorten a long constant or function, import its containing namespace
<?php
namespace mine;
use ultra\long\ns\name;
$a = name\CONSTANT;
name\func();
?>
It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences:
Example #9 Dangers of using namespaced names inside a double-quoted string
<?php
$a = "dangerous\name"; // \n is a newline inside double quoted strings!
$obj = new $a;
$a = 'not\at\all\dangerous'; // no problems here.
$obj = new $a;
?>
Any undefined constant that is unqualified like FOO will produce a notice explaining that PHP assumed FOO was the value of the constant. Any constant, qualified or fully qualified, that contains a backslash will produce a fatal error if not found.
Example #10 Undefined constants
<?php
namespace bar;
$a = FOO; // produces notice - undefined constants "FOO" assumed "FOO";
$a = \FOO; // fatal error, undefined namespace constant FOO
$a = Bar\FOO; // fatal error, undefined namespace constant bar\Bar\FOO
$a = \Bar\FOO; // fatal error, undefined namespace constant Bar\FOO
?>
Any attempt to define a namespaced constant that is a special, built-in constant results in a fatal error
Example #11 Undefined constants
<?php
namespace bar;
const NULL = 0; // fatal error;
const true = 'stupid'; // also fatal error;
// etc.
?>
PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().
In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.
The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.
Note:
Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.
The Standard PHP Library (SPL) provides a good number of built-in exceptions.
Example #1 Throwing an Exception
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
?>
The above example will output:
0.2 Caught exception: Division by zero. Hello World
Example #2 Exception handling with a finally block
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
The above example will output:
0.2 First finally. Caught exception: Division by zero. Second finally. Hello World
Example #3 Nested Exception
<?php
class MyException extends Exception { }
class Test {
public function testing() {
try {
try {
throw new MyException('foo!');
} catch (MyException $e) {
// rethrow it
throw $e;
}
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
}
$foo = new Test;
$foo->testing();
?>
The above example will output:
string(4) "foo!"
A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class.
Example #1 The Built in Exception class
<?php
class Exception
{
protected $message = 'Unknown exception'; // exception message
private $string; // __toString cache
protected $code = 0; // user defined exception code
protected $file; // source filename of exception
protected $line; // source line of exception
private $trace; // backtrace
private $previous; // previous exception if nested exception
public function __construct($message = null, $code = 0, Exception $previous = null);
final private function __clone(); // Inhibits cloning of exceptions.
final public function getMessage(); // message of exception
final public function getCode(); // code of exception
final public function getFile(); // source filename
final public function getLine(); // source line
final public function getTrace(); // an array of the backtrace()
final public function getPrevious(); // previous exception
final public function getTraceAsString(); // formatted string of trace
// Overrideable
public function __toString(); // formatted string for display
}
?>
If a class extends the built-in Exception class and re-defines the constructor, it is highly recommended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overridden to provide a custom output when the object is presented as a string.
Note:
Exceptions cannot be cloned. Attempting to clone an Exception will result in a fatal
E_ERRORerror.
Example #2 Extending the Exception class (PHP 5.3.0+)
<?php
/**
* Define a custom exception class
*/
class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0, Exception $previous = null) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code, $previous);
}
// custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
/**
* Create a class to test the exception
*/
class TestException
{
public $var;
const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;
function __construct($avalue = self::THROW_NONE) {
switch ($avalue) {
case self::THROW_CUSTOM:
// throw custom exception
throw new MyException('1 is an invalid parameter', 5);
break;
case self::THROW_DEFAULT:
// throw default one.
throw new Exception('2 is not allowed as a parameter', 6);
break;
default:
// No exception, object will be created.
$this->var = $avalue;
break;
}
}
}
// Example 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // Will be caught
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Skipped
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o); // Null
echo "\n\n";
// Example 2
try {
$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) { // Doesn't match this type
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // Will be caught
echo "Caught Default Exception\n", $e;
}
// Continue execution
var_dump($o); // Null
echo "\n\n";
// Example 3
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) { // Will be caught
echo "Default Exception caught\n", $e;
}
// Continue execution
var_dump($o); // Null
echo "\n\n";
// Example 4
try {
$o = new TestException();
} catch (Exception $e) { // Skipped, no exception
echo "Default Exception caught\n", $e;
}
// Continue execution
var_dump($o); // TestException
echo "\n\n";
?>
Note:
Versions of PHP 5, prior to PHP 5.3.0 do not support nesting of exceptions. The following code fragment can be used as a replacement MyException class if you wish to run this example.
<?php
/**
* Define a custom exception class
*/
class MyException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code);
}
// custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
?>
(PHP 5 >= 5.5.0)
Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.
A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.
A simple example of this is to reimplement the range() function as a generator. The standard range() function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling range(0, 1000000) will result in well over 100 MB of memory being used.
As an alternative, we can implement an xrange() generator, which will only ever need enough memory to create an Iterator object and track the current state of the generator internally, which turns out to be less than 1 kilobyte.
Example #1 Implementing range() as a generator
<?php
function xrange($start, $limit, $step = 1) {
if ($start < $limit) {
if ($step <= 0) {
throw new LogicException('Step must be +ve');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be -ve');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}
/*
* Note that both range() and xrange() result in the same
* output below.
*/
echo 'Single digit odd numbers from range(): ';
foreach (range(1, 9, 2) as $number) {
echo "$number ";
}
echo "\n";
echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
echo "$number ";
}
?>
The above example will output:
Single digit odd numbers from range(): 1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9
A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.
When a generator function is called, it returns an object that can be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP will call the generator function each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.
Once there are no more values to be yielded, then the generator function can simply exit, and the calling code continues just as if an array has run out of values.
Note:
A generator cannot return a value: doing so will result in a compile error. An empty return statement is valid syntax within a generator and it will terminate the generator.
The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
Example #1 A simple example of yielding values
<?php
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
$generator = gen_one_to_three();
foreach ($generator as $value) {
echo "$value\n";
}
?>
The above example will output:
1 2 3
Note:
Internally, sequential integer keys will be paired with the yielded values, just as with a non-associative array.
If you use yield in an expression context (for example, on the right hand side of an assignment), you must surround the yield statement with parentheses. For example, this is valid:
$data = (yield $value);
But this is not, and will result in a parse error:
$data = yield $value;
This syntax may be used in conjunction with the Generator::send() method.
PHP also supports associative arrays, and generators are no different. In addition to yielding simple values, as shown above, you can also yield a key at the same time.
The syntax for yielding a key/value pair is very similar to that used to define an associative array, as shown below.
Example #2 Yielding a key/value pair
<?php
/*
* The input is semi-colon separated fields, with the first
* field being an ID to use as a key.
*/
$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;
function input_parser($input) {
foreach (explode("\n", $input) as $line) {
$fields = explode(';', $line);
$id = array_shift($fields);
yield $id => $fields;
}
}
foreach (input_parser($input) as $id => $fields) {
echo "$id:\n";
echo " $fields[0]\n";
echo " $fields[1]\n";
}
?>
The above example will output:
1:
PHP
Likes dollar signs
2:
Python
Likes whitespace
3:
Ruby
Likes blocks
As with the simple value yields shown earlier, yielding a key/value pair in an expression context requires the yield statement to be parenthesised:
$data = (yield $key => $value);
Yield can be called without an argument to yield a NULL value with an
automatic key.
Example #3 Yielding NULLs
<?php
function gen_three_nulls() {
foreach (range(1, 3) as $i) {
yield;
}
}
var_dump(iterator_to_array(gen_three_nulls()));
?>
The above example will output:
array(3) {
[0]=>
NULL
[1]=>
NULL
[2]=>
NULL
}
Generator functions are able to yield values by reference as well as by value. This is done in the same way as returning references from functions: by prepending an ampersand to the function name.
Example #4 Yielding values by reference
<?php
function &gen_reference() {
$value = 3;
while ($value > 0) {
yield $value;
}
}
/*
* Note that we can change $number within the loop, and
* because the generator is yielding references, $value
* within gen_reference() changes.
*/
foreach (gen_reference() as &$number) {
echo (--$number).'... ';
}
?>
The above example will output:
2... 1... 0...
The primary advantage of generators is their simplicity. Much less boilerplate code has to be written compared to implementing an Iterator class, and the code is generally much more readable. For example, the following function and class are equivalent:
<?php
function getLinesFromFile($fileName) {
if (!$fileHandle = fopen($fileName, 'r')) {
return;
}
while (false !== $line = fgets($fileHandle)) {
yield $line;
}
fclose($fileHandle);
}
// versus...
class LineIterator implements Iterator {
protected $fileHandle;
protected $line;
protected $i;
public function __construct($fileName) {
if (!$this->fileHandle = fopen($fileName, 'r')) {
throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
}
}
public function rewind() {
fseek($this->fileHandle, 0);
$this->line = fgets($this->fileHandle);
$this->i = 0;
}
public function valid() {
return false !== $this->line;
}
public function current() {
return $this->line;
}
public function key() {
return $this->i;
}
public function next() {
if (false !== $this->line) {
$this->line = fgets($this->fileHandle);
$this->i++;
}
}
public function __destruct() {
fclose($this->fileHandle);
}
}
?>
This flexibility does come at a cost, however: generators are forward-only iterators, and cannot be rewound once iteration has started. This also means that the same generator can't be iterated over multiple times: the generator will need to either be rebuilt by calling the generator function again, or cloned via the clone keyword.
References in PHP are a means to access the same variable content by different names. They are not like C pointers; for instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses, and so on. See What References Are Not for more information. Instead, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The closest analogy is with Unix filenames and files - variable names are directory entries, while variable content is the file itself. References can be likened to hardlinking in Unix filesystem.
There are three basic operations performed using references: assigning by reference, passing by reference, and returning by reference. This section will give an introduction to these operations, with links for further reading.
In the first of these, PHP references allow you to make two variables refer to the same content. Meaning, when you do:
<?php
$a =& $b;
?>
Note:
$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.
Note:
If you assign, pass, or return an undefined variable by reference, it will get created.
Example #1 Using references with undefined variables
<?php
function foo(&$var) { }
foo($a); // $a is "created" and assigned to null
$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)
$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>
The same syntax can be used with functions that return references, and with the new operator (since PHP 4.0.4 and before PHP 5.0.0):
<?php
$foo =& find_var($bar);
?>
E_DEPRECATED message in PHP 5.3 and
later, and an E_STRICT message in earlier versions.
(Technically, the difference is that, in PHP 5, object variables, much like
resources, are a mere pointer to the actual object data, so these object
references are not "references" in the same sense used before (aliases).
For more information, see Objects
and references.)
If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the $GLOBALS array.
Example #2 Referencing global variables inside functions
<?php
$var1 = "Example variable";
$var2 = "";
function global_references($use_globals)
{
global $var1, $var2;
if (!$use_globals) {
$var2 =& $var1; // visible only inside the function
} else {
$GLOBALS["var2"] =& $var1; // visible also in global context
}
}
global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
Note:
If you assign a value to a variable with references in a foreach statement, the references are modified too.
Example #3 References and foreach statement
<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
// do something
}
echo $ref; // 3 - last element of the iterated array
?>
While not being strictly an assignment by reference, expressions created with the language construct array() can also behave as such by prefixing & to the array element to add. Example:
<?php
$a = 1;
$b = array(2, 3);
$arr = array(&$a, &$b[0], &$b[1]);
$arr[0]++; $arr[1]++; $arr[2]++;
/* $a == 2, $b == array(3, 4); */
?>
Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. Example:
<?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b
/* Assignment of array variables */
$arr = array(1);
$a =& $arr[0]; //$a and $arr[0] are in the same reference set
$arr2 = $arr; //not an assignment-by-reference!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* The contents of $arr are changed even though it's not a reference! */
?>
The second thing references do is to pass variables by reference. This is done by making a local variable in a function and a variable in the calling scope referencing the same content. Example:
<?php
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
?>
The third thing references can do is return by reference.
As said before, references are not pointers. That means, the following construct won't do what you expect:
<?php
function foo(&$var)
{
$var =& $GLOBALS["baz"];
}
foo($bar);
?>
What happens is that $var in foo will be bound with $bar in the caller, but then re-bound with $GLOBALS["baz"]. There's no way to bind $bar in the calling scope to something else using the reference mechanism, since $bar is not available in the function foo (it is represented by $var, but $var has only variable contents and not name-to-value binding in the calling symbol table). You can use returning references to reference variables selected by the function.
You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:
<?php
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
// $a is 6 here
?>
Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.
The following things can be passed by reference:
References returned from functions, i.e.:
<?php
function foo(&$var)
{
$var++;
}
function &bar()
{
$a = 5;
return $a;
}
foo(bar());
?>
No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:
<?php
function foo(&$var)
{
$var++;
}
function bar() // Note the missing &
{
$a = 5;
return $a;
}
foo(bar()); // Produces fatal error since PHP 5.0.5
foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
?>
Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so. To return references, use this syntax:
<?php
class foo {
public $value = 42;
public function &getValue() {
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue; // prints the new value of $obj->value, i.e. 2.
?>
Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.
Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 4.4.0 in the PHP 4 branch, and PHP 5.1.0 in the PHP 5 branch, an
E_NOTICEerror is issued if the code tries to return a dynamic expression or a result of the new operator.
To use the returned reference, you must use reference assigment:
<?php
function &collector() {
static $collection = array();
return $collection;
}
$collection = &collector();
$collection[] = 'foo';
?>
<?php
function &collector() {
static $collection = array();
return $collection;
}
array_push(collector(), 'foo');
?>
Note: Note that array_push(&collector(), 'foo'); will not work, it results in a fatal error.
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:
<?php
$a = 1;
$b =& $a;
unset($a);
?>
Again, it might be useful to think about this as analogous to the Unix unlink call.
Many syntax constructs in PHP are implemented via referencing mechanisms, so everything mentioned herein about reference binding also applies to these constructs. Some constructs, like passing and returning by reference, are mentioned above. Other constructs that use references are:
When you declare a variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:
<?php
$var =& $GLOBALS["var"];
?>
This also means that unsetting $var won't unset the global variable.
In an object method, $this is always a reference to the caller object.
PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.
See also the FAQ titled "How does register_globals affect me?"
Superglobals — Superglobals are built-in variables that are always available in all scopes
Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.
These superglobal variables are:
| Version | Description |
|---|---|
| 4.1.0 | Superglobals were introduced to PHP. |
Note: Variable availability
By default, all of the superglobals are available but there are directives that affect this availability. For further information, refer to the documentation for variables_order.
Note: Dealing with register_globals
If the deprecated register_globals directive is set to on then the variables within will also be made available in the global scope of the script. For example, $_POST['foo'] would also exist as $foo.
For related information, see the FAQ titled "How does register_globals affect me?"
Note: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods.
(PHP 4, PHP 5)
$GLOBALS — References all variables available in global scope
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
Example #1 $GLOBALS example
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";
test();
?>
The above example will output something similar to:
$foo in global scope: Example content $foo in current scope: local variable
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
Note: Variable availability
Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.
(PHP 4 >= 4.1.0, PHP 5)
$_SERVER -- $HTTP_SERVER_VARS [deprecated] — Server and execution environment information
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.
$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)
You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.
Note:
PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.
Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.
Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().
The absolute pathname of the currently executing script.
Note:
If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
Note: Under the Apache 2, you must set UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On in order to get the physical (real) port, otherwise, this value can be spoofed and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.
Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.
| Version | Description |
|---|---|
| 4.1.0 | Introduced $_SERVER that deprecated $HTTP_SERVER_VARS. |
Example #1 $_SERVER example
<?php
echo $_SERVER['SERVER_NAME'];
?>
The above example will output something similar to:
www.example.com
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
(PHP 4 >= 4.1.0, PHP 5)
$_GET -- $HTTP_GET_VARS [deprecated] — HTTP GET variables
An associative array of variables passed to the current script via the URL parameters.
$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)
| Version | Description |
|---|---|
| 4.1.0 | Introduced $_GET that deprecated $HTTP_GET_VARS. |
Example #1 $_GET example
<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>
Assuming the user entered http://example.com/?name=Hannes
The above example will output something similar to:
Hello Hannes!
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
Note:
The GET variables are passed through urldecode().
(PHP 4 >= 4.1.0, PHP 5)
$_POST -- $HTTP_POST_VARS [deprecated] — HTTP POST variables
An associative array of variables passed to the current script via the HTTP POST method.
$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)
| Version | Description |
|---|---|
| 4.1.0 | Introduced $_POST that deprecated $HTTP_POST_VARS. |
Example #1 $_POST example
<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>
Assuming the user POSTed name=Hannes
The above example will output something similar to:
Hello Hannes!
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
(PHP 4 >= 4.1.0, PHP 5)
$_FILES -- $HTTP_POST_FILES [deprecated] — HTTP File Upload variables
An associative array of items uploaded to the current script via the HTTP POST method.
$HTTP_POST_FILES contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)
| Version | Description |
|---|---|
| 4.1.0 | Introduced $_FILES that deprecated $HTTP_POST_FILES. |
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
(PHP 4 >= 4.1.0, PHP 5)
$_REQUEST — HTTP Request variables
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
| Version | Description |
|---|---|
| 5.3.0 | Introduced request_order. This directive affects the contents of $_REQUEST. |
| 4.3.0 | $_FILES information was removed from $_REQUEST. |
| 4.1.0 | Introduced $_REQUEST. |
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
Note:
When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.
Note:
The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive.
(PHP 4 >= 4.1.0, PHP 5)
$_SESSION -- $HTTP_SESSION_VARS [deprecated] — Session variables
An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.
$HTTP_SESSION_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)
| Version | Description |
|---|---|
| 4.1.0 | Introduced $_SESSION that deprecated $HTTP_SESSION_VARS. |
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
(PHP 4 >= 4.1.0, PHP 5)
$_ENV -- $HTTP_ENV_VARS [deprecated] — Environment variables
An associative array of variables passed to the current script via the environment method.
These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.
Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.
$HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)
| Version | Description |
|---|---|
| 4.1.0 | Introduced $_ENV that deprecated $HTTP_ENV_VARS. |
Example #1 $_ENV example
<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>
Assuming "bjori" executes this script
The above example will output something similar to:
My username is bjori!
Note:
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.
(PHP 4, PHP 5)
$php_errormsg — The previous error message
$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).
If a user defined error handler (set_error_handler())
is set $php_errormsg is only set if the error handler
returns FALSE.
Example #1 $php_errormsg example
<?php
@strpos();
echo $php_errormsg;
?>
The above example will output something similar to:
Wrong parameter count for strpos()
(PHP 4, PHP 5)
$HTTP_RAW_POST_DATA — Raw POST data
$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data
(PHP 4 >= 4.0.4, PHP 5)
$http_response_header — HTTP response headers
The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.
Example #1 $http_response_header example
<?php
function get_contents() {
file_get_contents("http://example.com");
var_dump($http_response_header);
}
get_contents();
var_dump($http_response_header);
?>
The above example will output something similar to:
array(9) {
[0]=>
string(15) "HTTP/1.1 200 OK"
[1]=>
string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
[2]=>
string(29) "Server: Apache/2.2.3 (CentOS)"
[3]=>
string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
[4]=>
string(27) "ETag: "280100-1b6-80bfd280""
[5]=>
string(20) "Accept-Ranges: bytes"
[6]=>
string(19) "Content-Length: 438"
[7]=>
string(17) "Connection: close"
[8]=>
string(38) "Content-Type: text/html; charset=UTF-8"
}
NULL
(PHP 4, PHP 5)
$argc — The number of arguments passed to script
Contains the number of arguments passed to the current script when running from the command line.
Note: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is 1.
Note: This variable is not available when register_argc_argv is disabled.
Example #1 $argc example
<?php
var_dump($argc);
?>
When executing the example with: php script.php arg1 arg2 arg3
The above example will output something similar to:
int(4)
(PHP 4, PHP 5)
$argv — Array of arguments passed to script
Contains an array of all the arguments passed to the script when running from the command line.
Note: The first argument $argv[0] is always the name that was used to run the script.
Note: This variable is not available when register_argc_argv is disabled.
Example #1 $argv example
<?php
var_dump($argv);
?>
When executing the example with: php script.php arg1 arg2 arg3
The above example will output something similar to:
array(4) {
[0]=>
string(10) "script.php"
[1]=>
string(4) "arg1"
[2]=>
string(4) "arg2"
[3]=>
string(4) "arg3"
}
See also the SPL Exceptions
(PHP 5 >= 5.1.0)
Exception is the base class for all Exceptions.
The exception message
The exception code
The filename where the exception was created
The line where the exception was created
(PHP 5 >= 5.1.0)
Exception::__construct — Construct the exception
$message = ""
[, int $code = 0
[, Exception $previous = NULL
]]] )Constructs the Exception.
messageThe Exception message to throw.
codeThe Exception code.
previousThe previous exception used for the exception chaining.
| Version | Description |
|---|---|
| 5.3.0 |
The previous parameter was added.
|
Note:
The
messageis NOT binary safe.
(PHP 5 >= 5.1.0)
Exception::getMessage — Gets the Exception message
Returns the Exception message.
This function has no parameters.
Returns the Exception message as a string.
Example #1 Exception::getMessage() example
<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo $e->getMessage();
}
?>
The above example will output something similar to:
Some error message
(PHP 5 >= 5.3.0)
Exception::getPrevious — Returns previous Exception
Returns previous Exception (the third parameter of Exception::__construct()).
This function has no parameters.
Returns the previous Exception if available
or NULL otherwise.
Example #1 Exception::getPrevious() example
Looping over, and printing out, exception trace.
<?php
class MyCustomException extends Exception {}
function doStuff() {
try {
throw new InvalidArgumentException("You are doing it wrong!", 112);
} catch(Exception $e) {
throw new MyCustomException("Something happened", 911, $e);
}
}
try {
doStuff();
} catch(Exception $e) {
do {
printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
} while($e = $e->getPrevious());
}
?>
The above example will output something similar to:
/home/bjori/ex.php:8 Something happened (911) [MyCustomException] /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]
(PHP 5 >= 5.1.0)
Exception::getCode — Gets the Exception code
This function has no parameters.
Returns the exception code as integer in Exception but possibly as other type in Exception descendants (for example as string in PDOException).
Example #1 Exception::getCode() example
<?php
try {
throw new Exception("Some error message", 30);
} catch(Exception $e) {
echo "The exception code is: " . $e->getCode();
}
?>
The above example will output something similar to:
The exception code is: 30
(PHP 5 >= 5.1.0)
Exception::getFile — Gets the file in which the exception occurred
Get the name of the file the exception was created.
This function has no parameters.
Returns the filename in which the exception was created.
Example #1 Exception::getFile() example
<?php
try {
throw new Exception;
} catch(Exception $e) {
echo $e->getFile();
}
?>
The above example will output something similar to:
/home/bjori/tmp/ex.php
(PHP 5 >= 5.1.0)
Exception::getLine — Gets the line in which the exception occurred
Get line number where the exception was created.
This function has no parameters.
Returns the line number where the exception was created.
Example #1 Exception::getLine() example
<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo "The exception was created on line: " . $e->getLine();
}
?>
The above example will output something similar to:
The exception was created on line: 3
(PHP 5 >= 5.1.0)
Exception::getTrace — Gets the stack trace
Returns the Exception stack trace.
This function has no parameters.
Returns the Exception stack trace as an array.
Example #1 Exception::getTrace() example
<?php
function test() {
throw new Exception;
}
try {
test();
} catch(Exception $e) {
var_dump($e->getTrace());
}
?>
The above example will output something similar to:
array(1) {
[0]=>
array(4) {
["file"]=>
string(22) "/home/bjori/tmp/ex.php"
["line"]=>
int(7)
["function"]=>
string(4) "test"
["args"]=>
array(0) {
}
}
}
(PHP 5 >= 5.1.0)
Exception::getTraceAsString — Gets the stack trace as a string
Returns the Exception stack trace as a string.
This function has no parameters.
Returns the Exception stack trace as a string.
Example #1 Exception::getTraceAsString() example
<?php
function test() {
throw new Exception;
}
try {
test();
} catch(Exception $e) {
echo $e->getTraceAsString();
}
?>
The above example will output something similar to:
#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}
(PHP 5 >= 5.1.0)
Exception::__toString — String representation of the exception
Returns the string representation of the exception.
This function has no parameters.
Returns the string representation of the exception.
Example #1 Exception::__toString() example
<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo $e;
}
?>
The above example will output something similar to:
exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}
(PHP 5 >= 5.1.0)
Exception::__clone — Clone the exception
Tries to clone the Exception, which results in Fatal error.
This function has no parameters.
No value is returned.
Exceptions are not clonable.
(PHP 5 >= 5.1.0)
An Error Exception.
$message = ""
[, int $code = 0
[, int $severity = 1
[, string $filename = __FILE__
[, int $lineno = __LINE__
[, Exception $previous = NULL
]]]]]] )The severity of the exception
Example #1 Use set_error_handler() to change error messages into ErrorException.
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
?>
The above example will output something similar to:
Fatal error: Uncaught exception 'ErrorException' with message 'Wrong parameter count for strpos()' in /home/bjori/tmp/ex.php:8
Stack trace:
#0 [internal function]: exception_error_handler(2, 'Wrong parameter...', '/home/bjori/php...', 8, Array)
#1 /home/bjori/php/cleandocs/test.php(8): strpos()
#2 {main}
thrown in /home/bjori/tmp/ex.php on line 8
(PHP 5 >= 5.1.0)
ErrorException::__construct — Constructs the exception
$message = ""
[, int $code = 0
[, int $severity = 1
[, string $filename = __FILE__
[, int $lineno = __LINE__
[, Exception $previous = NULL
]]]]]] )Constructs the Exception.
messageThe Exception message to throw.
codeThe Exception code.
severityThe severity level of the exception.
filenameThe filename where the exception is thrown.
linenoThe line number where the exception is thrown.
previousThe previous exception used for the exception chaining.
| Version | Description |
|---|---|
| 5.3.0 |
The previous parameter was added.
|
(PHP 5 >= 5.1.0)
ErrorException::getSeverity — Gets the exception severity
Returns the severity of the exception.
This function has no parameters.
Returns the severity level of the exception.
Example #1 ErrorException::getSeverity() example
<?php
try {
throw new ErrorException("Exception message", 0, 75);
} catch(ErrorException $e) {
echo "This exception severity is: " . $e->getSeverity();
}
?>
The above example will output something similar to:
This exception severity is: 75
See also the SPL Interfaces and reserved classes.
(PHP 5 >= 5.0.0)
Interface to detect if a class is traversable using foreach.
Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.
Note:
Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.
Note:
This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead. When implementing an interface which extends Traversable, make sure to list IteratorAggregate or Iterator before its name in the implements clause.
This interface has no methods, its only purpose is to be the base interface for all traversable classes.
(PHP 5 >= 5.0.0)
Interface for external iterators or objects that can be iterated themselves internally.
PHP already provides a number of iterators for many day to day tasks. See SPL iterators for a list.
Example #1 Basic usage
This example demonstrates in which order methods are called when using foreach with an iterator.
<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
);
public function __construct() {
$this->position = 0;
}
function rewind() {
var_dump(__METHOD__);
$this->position = 0;
}
function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
function key() {
var_dump(__METHOD__);
return $this->position;
}
function next() {
var_dump(__METHOD__);
++$this->position;
}
function valid() {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
The above example will output something similar to:
string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(0) string(12) "firstelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(1) string(13) "secondelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(2) string(11) "lastelement" string(16) "myIterator::next" string(17) "myIterator::valid"
(PHP 5 >= 5.0.0)
Iterator::current — Return the current element
This function has no parameters.
Can return any type.
(PHP 5 >= 5.0.0)
Iterator::key — Return the key of the current element
Returns the key of the current element.
This function has no parameters.
Returns scalar on success, or NULL on failure.
Issues E_NOTICE on failure.
(PHP 5 >= 5.0.0)
Iterator::next — Move forward to next element
Moves the current position to the next element.
Note:
This method is called after each foreach loop.
This function has no parameters.
Any returned value is ignored.
(PHP 5 >= 5.0.0)
Iterator::rewind — Rewind the Iterator to the first element
Rewinds back to the first element of the Iterator.
Note:
This is the first method called when starting a foreach loop. It will not be executed after foreach loops.
This function has no parameters.
Any returned value is ignored.
(PHP 5 >= 5.0.0)
Iterator::valid — Checks if current position is valid
This method is called after Iterator::rewind() and Iterator::next() to check if the current position is valid.
This function has no parameters.
The return value will be casted to boolean and then evaluated.
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.0.0)
Interface to create an external Iterator.
Example #1 Basic usage
<?php
class myData implements IteratorAggregate {
public $property1 = "Public property one";
public $property2 = "Public property two";
public $property3 = "Public property three";
public function __construct() {
$this->property4 = "last property";
}
public function getIterator() {
return new ArrayIterator($this);
}
}
$obj = new myData;
foreach($obj as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
The above example will output something similar to:
string(9) "property1" string(19) "Public property one" string(9) "property2" string(19) "Public property two" string(9) "property3" string(21) "Public property three" string(9) "property4" string(13) "last property"
(PHP 5 >= 5.0.0)
IteratorAggregate::getIterator — Retrieve an external iterator
Returns an external iterator.
This function has no parameters.
An instance of an object implementing Iterator or Traversable
Throws an Exception on failure.
(PHP 5 >= 5.0.0)
Interface to provide accessing objects as arrays.
Example #1 Basic usage
<?php
class obj implements arrayaccess {
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new obj;
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>
The above example will output something similar to:
bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
[container:obj:private] => Array
(
[one] => 1
[three] => 3
[two] => A value
[0] => Append 1
[1] => Append 2
[2] => Append 3
)
)
(PHP 5 >= 5.0.0)
ArrayAccess::offsetExists — Whether a offset exists
Whether or not an offset exists.
This method is executed when using isset() or empty() on objects implementing ArrayAccess.
Note:
When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns
TRUE.
offsetAn offset to check for.
Returns TRUE on success or FALSE on failure.
Note:
The return value will be casted to boolean if non-boolean was returned.
Example #1 ArrayAccess::offsetExists() example
<?php
class obj implements arrayaccess {
public function offsetSet($offset, $value) {
var_dump(__METHOD__);
}
public function offsetExists($var) {
var_dump(__METHOD__);
if ($var == "foobar") {
return true;
}
return false;
}
public function offsetUnset($var) {
var_dump(__METHOD__);
}
public function offsetGet($var) {
var_dump(__METHOD__);
return "value";
}
}
$obj = new obj;
echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));
echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));
echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>
The above example will output something similar to:
Runs obj::offsetExists() string(17) "obj::offsetExists" bool(true) Runs obj::offsetExists() and obj::offsetGet() string(17) "obj::offsetExists" string(14) "obj::offsetGet" bool(false) Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get string(17) "obj::offsetExists" bool(true)
(PHP 5 >= 5.0.0)
ArrayAccess::offsetGet — Offset to retrieve
Returns the value at specified offset.
This method is executed when checking if offset is empty().
offsetThe offset to retrieve.
Note:
Starting with PHP 5.3.4, the prototype checks were relaxed and it's possible for implementations of this method to return by reference. This makes indirect modifications to the overloaded array dimensions of ArrayAccess objects possible.
A direct modification is one that replaces completely the value of the array dimension, as in $obj[6] = 7. An indirect modification, on the other hand, only changes part of the dimension, or attempts to assign the dimension by reference to another variable, as in $obj[6][7] = 7 or $var =& $obj[6]. Increments with ++ and decrements with -- are also implemented in a way that requires indirect modification.
While direct modification triggers a call to ArrayAccess::offsetSet(), indirect modification triggers a call to ArrayAccess::offsetGet(). In that case, the implementation of ArrayAccess::offsetGet() must be able to return by reference, otherwise an
E_NOTICEmessage is raised.
Can return all value types.
(PHP 5 >= 5.0.0)
ArrayAccess::offsetSet — Offset to set
Assigns a value to the specified offset.
offsetThe offset to assign the value to.
valueThe value to set.
No value is returned.
Note:
The
offsetparameter will be set toNULLif another value is not available, like in the following example.<?php
$arrayaccess[] = "first value";
$arrayaccess[] = "second value";
print_r($arrayaccess);
?>The above example will output:
Array ( [0] => first value [1] => second value )
Note:
This function is not called in assignments by reference and otherwise indirect changes to array dimensions overloaded with ArrayAccess (indirect in the sense they are made not by changing the dimension directly, but by changing a sub-dimension or sub-property or assigning the array dimension by reference to another variable). Instead, ArrayAccess::offsetGet() is called. The operation will only be successful if that method returns by reference, which is only possible since PHP 5.3.4.
(PHP 5 >= 5.0.0)
ArrayAccess::offsetUnset — Offset to unset
offsetThe offset to unset.
No value is returned.
(PHP 5 >= 5.1.0)
Interface for customized serializing.
Classes that implement this interface no longer support __sleep() and __wakeup(). The method serialize is called whenever an instance needs to be serialized. This does not invoke __destruct() or has any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize() method is called as a constructor instead of calling __construct(). If you need to execute the standard constructor you may do so in the method.
Example #1 Basic usage
<?php
class obj implements Serializable {
private $data;
public function __construct() {
$this->data = "My private data";
}
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
public function getData() {
return $this->data;
}
}
$obj = new obj;
$ser = serialize($obj);
var_dump($ser);
$newobj = unserialize($ser);
var_dump($newobj->getData());
?>
The above example will output something similar to:
string(38) "C:3:"obj":23:{s:15:"My private data";}"
string(15) "My private data"
(PHP 5 >= 5.1.0)
Serializable::serialize — String representation of object
Should return the string representation of the object.
Note:
This method acts as the destructor of the object. The __destruct() method will not be called after this method.
This function has no parameters.
Returns the string representation of the object or NULL
Throws Exception when returning other types than strings and
NULL.
(PHP 5 >= 5.1.0)
Serializable::unserialize — Constructs the object
$serialized
)Called during unserialization of the object.
Note:
This method acts as the constructor of the object. The __construct() method will not be called after this method.
serializedThe string representation of the object.
The return value from this method is ignored.
(PHP 5 >= 5.3.0)
Class used to represent anonymous functions.
Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon. Starting with PHP 5.4, this class has methods that allow further control of the anonymous function after it has been created.
Besides the methods listed here, this class also has an __invoke method. This is for consistency with other classes that implement calling magic, as this method is not used for calling the function.
(PHP 5 >= 5.3.0)
Closure::__construct — Constructor that disallows instantiation
This method exists only to disallow instantiation of the Closure class. Objects of this class are created in the fashion described on the anonymous functions page.
This function has no parameters.
This method has no return value; it simply emits an error
(of type E_RECOVERABLE_ERROR).
(PHP 5 >= 5.4.0)
Closure::bind — Duplicates a closure with a specific bound object and class scope
$closure
, object $newthis
[, mixed $newscope
= 'static'
] )This method is a static version of Closure::bindTo(). See the documentation of that method for more information.
closureThe anonymous functions to bind.
newthis
The object to which the given anonymous function should be bound, or
NULL for the closure to be unbound.
newscopeThe class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.
Returns a new Closure object or FALSE on failure
Example #1 Closure::bind() example
<?php
class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";
?>
The above example will output something similar to:
1 2
(PHP 5 >= 5.4.0)
Closure::bindTo — Duplicates the closure with a new bound object and class scope
Create and return a new anonymous function with the same body and bound variables as this one, but possibly with a different bound object and a new class scope.
The “bound object” determines the value $this will
have in the function body and the “class scope” represents a class
which determines which private and protected members the anonymous
function will be able to access. Namely, the members that will be
visible are the same as if the anonymous function were a method of
the class given as value of the newscope
parameter.
Static closures cannot have any bound object (the value of the parameter
newthis should be NULL), but this function can
nevertheless be used to change their class scope.
This function will ensure that for a non-static closure, having a bound
instance will imply being scoped and vice-versa. To this end,
non-static closures that are given a scope but a NULL instance are made
static and non-static non-scoped closures that are given a non-null
instance are scoped to an unspecified class.
Note:
If you only want to duplicate the anonymous functions, you can use cloning instead.
newthis
The object to which the given anonymous function should be bound, or
NULL for the closure to be unbound.
newscopeThe class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.
Returns the newly created Closure object
or FALSE on failure
Example #1 Closure::bindTo() example
<?php
class A {
function __construct($val) {
$this->val = $val;
}
function getClosure() {
//returns closure bound to this object and scope
return function() { return $this->val; };
}
}
$ob1 = new A(1);
$ob2 = new A(2);
$cl = $ob1->getClosure();
echo $cl(), "\n";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";
?>
The above example will output something similar to:
1 2
(PHP 5 >= 5.5.0)
Generator objects are returned from generators.
Generator objects cannot be instantiated via new.
(PHP 5 >= 5.5.0)
Generator::current — Get the yielded value
This function has no parameters.
Returns the yielded value.
(PHP 5 >= 5.5.0)
Generator::key — Get the yielded key
This function is currently not documented; only its argument list is available.
This function has no parameters.
Returns the yielded key.
(PHP 5 >= 5.5.0)
Generator::next — Resume execution of the generator
This function has no parameters.
No value is returned.
(PHP 5 >= 5.5.0)
Generator::rewind — Rewind the iterator
If iteration has already begun, this will throw an exception.
This function has no parameters.
No value is returned.
(PHP 5 >= 5.5.0)
Generator::send — Send a value to the generator
Sends the given value to the generator as the result of the current yield expression and resumes execution of the generator.
If the generator is not at a yield expression when this method is called, it will first be let to advance to the first yield expression before sending the value. As such it is not necessary to "prime" PHP generators with a Generator::next() call (like it is done in Python).
valueValue to send into the generator. This value will be the return value of the yield expression the generator is currently at.
Example #1 Using Generator::send() to inject values
<?php
function printer() {
while (true) {
$string = yield;
echo $string;
}
}
$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
?>
The above example will output:
Hello world! Bye world!
Returns the yielded value.
(PHP 5 >= 5.5.0)
Generator::throw — Throw an exception into the generator
Throws an exception into the generator and resumes execution of the generator. The behavior will be the same as if the current yield expression was replaced with a throw $exception statement.
If the generator is already closed when this method is invoked, the exception will be thrown in the caller's context instead.
exceptionException to throw into the generator.
Example #1 Throwing an exception into a generator
<?php
function gen() {
echo "Foo\n";
try {
yield;
} catch (Exception $e) {
echo "Exception: {$e->getMessage()}\n";
}
echo "Bar\n";
}
$gen = gen();
$gen->rewind();
$gen->throw(new Exception('Test'));
?>
The above example will output:
Foo Exception: Test Bar
Returns the yielded value.
(PHP 5 >= 5.5.0)
Generator::valid — Check if the iterator has been closed
This function has no parameters.
Returns FALSE if the iterator has been closed. Otherwise returns TRUE.
(PHP 5 >= 5.5.0)
Generator::__wakeup — Serialize callback
Throws an exception as generators can't be serialized.
This function has no parameters.
No value is returned.
PHP offers various context options and parameters which can be used with all filesystem and stream wrappers. The context is created with stream_context_create(). Options are set with stream_context_set_option() and parameters with stream_context_set_params().
Socket context options — Socket context option listing
Socket context options are available for all wrappers that work over sockets, like tcp, http and ftp.
| Version | Description |
|---|---|
| 5.3.3 | Added backlog. |
| 5.1.0 | Added bindto. |
Example #1 Basic bindto usage example
<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:0',
),
);
// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:7000',
),
);
// connect to the internet using the '2001:db8::1' IPv6 address
// and port '7000'
$opts = array(
'socket' => array(
'bindto' => '[2001:db8::1]:7000',
),
);
// connect to the internet using port '7000'
$opts = array(
'socket' => array(
'bindto' => '0:7000',
),
);
// create the context...
$context = stream_context_create($opts);
// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);
?>
HTTP context options — HTTP context option listing
Context options for http:// and https:// transports.
| Version | Description |
|---|---|
| 5.3.4 |
Added follow_location.
|
| 5.3.0 |
The protocol_version supports chunked transfer
decoding when set to 1.1.
|
| 5.2.10 |
Added ignore_errors.
|
| 5.2.10 |
The header can now be an numerically indexed array.
|
| 5.2.1 |
Added timeout.
|
| 5.1.0 | Added HTTPS proxying through HTTP proxies. |
| 5.1.0 |
Added max_redirects.
|
| 5.1.0 |
Added protocol_version.
|
Example #1 Fetch a page and send POST data
<?php
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
Example #2 Ignore redirects but fetch headers and content
<?php
$url = "http://www.example.org/header.php";
$opts = array('http' =>
array(
'method' => 'GET',
'max_redirects' => '0',
'ignore_errors' => '1'
)
);
$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);
// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));
// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>
Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.
Note: HTTP status line
When this stream wrapper follows a redirect, the wrapper_data returned by stream_get_meta_data() might not necessarily contain the HTTP status line that actually applies to the content data at index 0.The first request returned a 301 (permanent redirect), so the stream wrapper automatically followed the redirect to get a 200 response (index = 4).array ( 'wrapper_data' => array ( 0 => 'HTTP/1.0 301 Moved Permantenly', 1 => 'Cache-Control: no-cache', 2 => 'Connection: close', 3 => 'Location: http://example.com/foo.jpg', 4 => 'HTTP/1.1 200 OK', ...
FTP context options — FTP context option listing
Context options for ftp:// and ftps:// transports.
| Version | Description |
|---|---|
| 5.1.0 |
Added proxy.
|
| 5.0.0 |
Added overwrite and resume_pos.
|
Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.
SSL context options — SSL context option listing
Context options for ssl:// and tls:// transports.
| Version | Description |
|---|---|
| 5.4.13 |
Added disable_compression. Requires OpenSSL >= 1.0.0.
|
| 5.3.2 |
Added SNI_enabled and
SNI_server_name.
|
| 5.0.0 |
Added capture_peer_cert,
capture_peer_chain and
ciphers.
|
Note: Because ssl:// is the underlying transport for the https:// and ftps:// wrappers, any context options which apply to ssl:// also apply to https:// and ftps://.
Note: For SNI (Server Name Indication) to be available, then PHP must be compiled with OpenSSL 0.9.8j or greater. Use the
OPENSSL_TLSEXT_SERVER_NAMEto determine whether SNI is supported.
CURL context options — CURL context option listing
CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.
Example #1 Fetch a page and send POST data
<?php
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
Phar context options — Phar context option listing
Context options for phar:// wrapper.
Context parameters — Context parameter listing
These parameters can be set on a context using the stream_context_set_params() function.
PHP comes with many built-in wrappers for various URL-style protocols for use with the filesystem functions such as fopen(), copy(), file_exists() and filesize(). In addition to these wrappers, it is possible to register custom wrappers using the stream_wrapper_register() function.
Note: The URL syntax used to describe a wrapper only supports the scheme://... syntax. The scheme:/ and scheme: syntaxes are not supported.
file:// — Accessing local filesystem
Filesystem is the default wrapper used with PHP and represents the local filesystem. When a relative path is specified (a path which does not begin with /, \, \\, or a Windows drive letter) the path provided will be applied against the current working directory. In many cases this is the directory in which the script resides unless it has been changed. Using the CLI sapi, this defaults to the directory from which the script was called.
With some functions, such as fopen() and file_get_contents(), include_path may be optionally searched for relative paths as well.
| Version | Description |
|---|---|
| 5.0.0 | Added file://. |
http:// -- https:// — Accessing HTTP(s) URLs
Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your php.ini file or the stream context, it will also be included in the request.
The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable.
If it's important to know the URL of the resource where your document came from (after all redirects have been processed), you'll need to process the series of response headers returned by the stream.
The from directive will be used for the From: header if set and not overwritten by the Context options and parameters.
| Version | Description |
|---|---|
| 4.3.7 | Detect buggy IIS servers to avoid "SSL: Fatal Protocol Error" errors. |
| 4.3.0 | Added https://. |
| 4.0.5 | Added support for redirects. |
Example #1 Detecting which URL we ended up on after redirects
<?php
$url = 'http://www.example.com/redirecting_page.php';
$fp = fopen($url, 'r');
$meta_data = stream_get_meta_data($fp);
foreach ($meta_data['wrapper_data'] as $response) {
/* Were we redirected? */
if (strtolower(substr($response, 0, 10)) == 'location: ') {
/* update $url with where we were redirected to */
$url = substr($response, 10);
}
}
?>
Note: HTTPS is only supported when the openssl extension is enabled.
HTTP connections are read-only; writing data or copying files to an HTTP resource is not supported.
Sending POST and PUT requests, for example, can be done with the help of HTTP Contexts.
ftp:// -- ftps:// — Accessing FTP(s) URLs
Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.
You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing but have not specified the context option overwrite, the connection will fail. If you need to overwrite existing files over ftp, specify the overwrite option in the context and open the file for writing. Alternatively, you can use the FTP extension.
If you have set the from directive in php.ini, then this value will be sent as the anonymous FTP password.
| Version | Description |
|---|---|
| 4.3.0 | Added ftps://. |
Note:
FTPS is only supported when the openssl extension is enabled.
If the server does not support SSL, then the connection falls back to regular unencrypted ftp.
Note: Appending
As of PHP 5.0.0 files may be appended via the ftp:// URL wrapper. In prior versions, attempting to append to a file via ftp:// will result in failure.
php:// — Accessing various I/O streams
PHP provides a number of miscellaneous I/O streams that allow access to PHP's own input and output streams, the standard input, output and error file descriptors, in-memory and disk-backed temporary file streams, and filters that can manipulate other file resources as they are read from and written to.
php://stdin, php://stdout and
php://stderr allow direct access to the corresponding
input or output stream of the PHP process. The stream references a
duplicate file descriptor, so if you open php://stdin
and later close it, you close only your copy of the descriptor-the actual
stream referenced by STDIN is unaffected. Note that
PHP exhibited buggy behavior in this regard until PHP 5.2.1. It is
recommended that you simply use the constants STDIN,
STDOUT and STDERR instead of
manually opening streams using these wrappers.
php://stdin is read-only, whereas php://stdout and php://stderr are write-only.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
Note: A stream opened with php://input can only be read once; the stream does not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.
php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo.
php://fd allows direct access to the given file descriptor. For example, php://fd/3 refers to file descriptor 3.
php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.
The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.
php://filter is a kind of meta-wrapper designed to permit the application of filters to a stream at the time of opening. This is useful with all-in-one file functions such as readfile(), file(), and file_get_contents() where there is otherwise no opportunity to apply a filter to the stream prior the contents being read.
The php://filter target takes the following parameters as part of its path. Multiple filter chains can be specified on one path. Please refer to the examples for specifics on using these parameters.
| Name | Description |
|---|---|
| resource=<stream to be filtered> | This parameter is required. It specifies the stream that you would like to filter. |
| read=<filter list to apply to read chain> | This parameter is optional. One or more filter names can be provided here, separated by the pipe character (|). |
| write=<filter list to apply to write chain> | This parameter is optional. One or more filter names can be provided here, separated by the pipe character (|). |
| <filter list to apply to both chains> | Any filter lists which are not prefixed by read= or write= will be applied to both the read and write chains as appropriate. |
| Version | Description |
|---|---|
| 5.3.6 | php://fd was added. |
| 5.1.0 | php://memory and php://temp were added. |
| 5.0.0 | php://filter was added. |
Example #1 php://temp/maxmemory
This optional parameter allows setting the memory limit before php://temp starts using a temporary file.
<?php
// Set the limit to 5 MB.
$fiveMBs = 5 * 1024 * 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
fputs($fp, "hello\n");
// Read what we have written.
rewind($fp);
echo stream_get_contents($fp);
?>
Example #2 php://filter/resource=<stream to be filtered>
This parameter must be located at the end of your php://filter specification and should point to the stream which you want filtered.
<?php
/* This is equivalent to simply:
readfile("http://www.example.com");
since no filters are actually specified */
readfile("php://filter/resource=http://www.example.com");
?>
Example #3 php://filter/read=<filter list to apply to read chain>
This parameter takes one or more filternames separated by the pipe character |.
<?php
/* This will output the contents of
www.example.com entirely in uppercase */
readfile("php://filter/read=string.toupper/resource=http://www.example.com");
/* This will do the same as above
but will also ROT13 encode it */
readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.example.com");
?>
Example #4 php://filter/write=<filter list to apply to write chain>
This parameter takes one or more filternames separated by the pipe character |.
<?php
/* This will filter the string "Hello World"
through the rot13 filter, then write to
example.txt in the current directory */
file_put_contents("php://filter/write=string.rot13/resource=example.txt","Hello World");
?>
zlib:// -- bzip2:// -- zip:// — Compression Streams
zlib: PHP 4.0.4 - PHP 4.2.3 (systems with fopencookie only)
compress.zlib:// and compress.bzip2:// PHP 4.3.0 and up
zlib: works like gzopen(), except that the stream can be used with fread() and the other filesystem functions. This is deprecated as of PHP 4.3.0 due to ambiguities with filenames containing ':' characters; use compress.zlib:// instead.
compress.zlib:// and compress.bzip2:// are equivalent to gzopen() and bzopen() respectively, and operate even on systems that do not support fopencookie.
ZIP extension registers zip: wrapper.
data:// — Data (RFC 2397)
The data: (» RFC 2397) stream wrapper is available since PHP 5.2.0.
Example #1 Print data:// contents
<?php
// prints "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');
?>
Example #2 Fetch the media type
<?php
$fp = fopen('data://text/plain;base64,', 'r');
$meta = stream_get_meta_data($fp);
// prints "text/plain"
echo $meta['mediatype'];
?>
glob:// — Find pathnames matching pattern
The glob: stream wrapper is available since PHP 5.3.0.
Example #1 Basic usage
<?php
// Loop over all *.php files in ext/spl/examples/ directory
// and print the filename and its size
$it = new DirectoryIterator("glob://ext/spl/examples/*.php");
foreach($it as $f) {
printf("%s: %.1FK\n", $f->getFilename(), $f->getSize()/1024);
}
?>
tree.php: 1.0K findregex.php: 0.6K findfile.php: 0.7K dba_dump.php: 0.9K nocvsdir.php: 1.1K phar_from_dir.php: 1.0K ini_groups.php: 0.9K directorytree.php: 0.9K dba_array.php: 1.1K class_tree.php: 1.8K
phar:// — PHP Archive
The phar:// stream wrapper is available since PHP 5.3.0. See Phar stream wrapper for detailed description.
ssh2:// — Secure Shell 2
ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// PHP 4.3.0 and up (PECL)
Note: This wrapper is not enabled by default
In order to use the ssh2.*:// wrappers you must install the » SSH2 extension available from » PECL.
In addition to accepting traditional URI login details, the ssh2 wrappers will also reuse open connections by passing the connection resource in the host portion of the URL.
Example #1 Opening a stream from an active connection
<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
'/home/username/.ssh/id_rsa', 'secret');
$stream = fopen("ssh2.tunnel://$session/remote.example.com:1234", 'r');
?>
Example #2 This $session variable must be kept available!
In order to use the ssh2.*://$session wrappers you must keep the $session resouce variable. The code below will not have the desired effect:
<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
'/home/username/.ssh/id_rsa', 'secret');
$connection_string = "ssh2.sftp://$session/";
unset($session);
$stream = fopen($connection_string . "path/to/file", 'r');
?>
unset() closes the session, because $connection_string does not hold a reference to the $session variable, just a string cast derived from it. This also happens when the unset() is implicit because of leaving scope (like in a function).
rar:// — RAR
The wrapper takes the url encoded path to the RAR archive (relative or absolute), an optional asterik (*), an optional number sign (#) and an optional url encoded entry name, as stored in the archive. Specifying an entry name requires the number sign; a leading forward slash in the entry name is optional.
This wrapper can open both files and directories. When opening directories, the asterisk sign forces the directory entries names to be returned unencoded. If it's not specified, they will be returned url encoded – the reason for this is to allow the wrapper to be correctly used with built-in functionality like the RecursiveDirectoryIterator in the presence of file names that seem like url encoded data.
If the pound sign and the entry name part are not included, the root of the archive will be displayed. This differs from regular directories in that the resulting stream will not contain information such as the modification time, as the root directory is not stored in an individual entry in the archive. The usage of the wrapper with RecursiveDirectoryIterator requires the number sign to be included in the URL when accessing the root, so that the URLs of the children may be constructed correctly.
Note: This wrapper is not enabled by default
In order to use the rar:// wrapper, you must install the » rar extension available from » PECL.
rar:// Available since PECL rar 3.0.0
Example #1 Traversing a RAR archive
<?php
class MyRecDirIt extends RecursiveDirectoryIterator {
function current() {
return rawurldecode($this->getSubPathName()) .
(is_dir(parent::current())?" [DIR]":"");
}
}
$f = "rar://" . rawurlencode(dirname(__FILE__)) .
DIRECTORY_SEPARATOR . 'dirs_and_extra_headers.rar#';
$it = new RecursiveTreeIterator(new MyRecDirIt($f));
foreach ($it as $s) {
echo $s, "\n";
}
?>
The above example will output something similar to:
|-allow_everyone_ni [DIR]
|-file1.txt
|-file2_אּ.txt
|-with_streams.txt
\-אּ [DIR]
|-אּ\%2Fempty%2E [DIR]
| \-אּ\%2Fempty%2E\file7.txt
|-אּ\empty [DIR]
|-אּ\file3.txt
|-אּ\file4_אּ.txt
\-אּ\אּ_2 [DIR]
|-אּ\אּ_2\file5.txt
\-אּ\אּ_2\file6_אּ.txt
Example #2 Opening an encrypted file (header encryption)
<?php
$stream = fopen("rar://" .
rawurlencode(dirname(__FILE__)) . DIRECTORY_SEPARATOR .
'encrypted_headers.rar' . '#encfile1.txt', "r", false,
stream_context_create(
array(
'rar' =>
array(
'open_password' => 'samplepassword'
)
)
)
);
var_dump(stream_get_contents($stream));
/* creation and last access date is opt-in in WinRAR, hence most
* files don't have them */
var_dump(fstat($stream));
?>
The above example will output something similar to:
string(26) "Encrypted file 1 contents."
Array
(
[0] => 0
[1] => 0
[2] => 33206
[3] => 1
[4] => 0
[5] => 0
[6] => 0
[7] => 26
[8] => 0
[9] => 1259550052
[10] => 0
[11] => -1
[12] => -1
[dev] => 0
[ino] => 0
[mode] => 33206
[nlink] => 1
[uid] => 0
[gid] => 0
[rdev] => 0
[size] => 26
[atime] => 0
[mtime] => 1259550052
[ctime] => 0
[blksize] => -1
[blocks] => -1
)
ogg:// — Audio streams
Files opened for reading via the ogg:// wrapper
are treated as compressed audio encoded using the OGG/Vorbis codec.
Similarly, files opened for writing or appending via the
ogg:// wrapper are writen as compressed audio data.
stream_get_meta_data(), when used on an OGG/Vorbis
file opened for reading will return various details about the stream
including the vendor tag, any included
comments, the number of
channels, the sampling rate,
and the encoding rate range described by:
bitrate_lower, bitrate_upper,
bitrate_nominal, and bitrate_window.
ogg:// PHP 4.3.0 and up (PECL)
Note: This wrapper is not enabled by default
In order to use the ogg:// wrapper you must install the » OGG/Vorbis extension available from » PECL.
expect:// — Process Interaction Streams
Streams opened via the expect:// wrapper provide access to process'es stdio, stdout and stderr via PTY.
Note: This wrapper is not enabled by default
In order to use the expect:// wrapper you must install the » Expect extension available from » PECL.
expect:// PHP 4.3.0 and up (PECL)
PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.
As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.
The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.
This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.
A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.
The best security is often unobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.
A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.
When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.
The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.
Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory » CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:
If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.
Redirection can be configured in Apache by using AddHandler and Action directives (see below).
The configuration directive cgi.force_redirect prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule. PHP older than 4.2.0 used --enable-force-cgi-redirect compile time option for this.
Usually the redirection in the Apache configuration is done with the following directives:
Action php-script /cgi-bin/php AddHandler php-script .php
This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.
To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.
Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.
You can set the PHP script document root by the configuration
directive doc_root in the
configuration file, or
you can set the environment variable
PHP_DOCUMENT_ROOT. If it is set, the CGI
version of PHP will always construct the file name to open with this
doc_root and the path information in the
request, so you can be sure no script is executed outside this
directory (except for user_dir
below).
Another option usable here is user_dir. When user_dir is unset,
only thing controlling the opened file name is
doc_root. Opening a URL like http://my.host/~user/doc.php does not
result in opening a file under users home directory, but a file
called ~user/doc.php under
doc_root (yes, a directory name starting with a tilde
[~]).
If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.
user_dir expansion happens regardless of
the doc_root setting, so you can control
the document root and user directory access
separately.
A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:
#!/usr/local/bin/php
To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the PHP parser should be compiled with the --enable-discard-path configure option.
When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.
Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.
A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilities in some other way.
Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.
There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.
PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.
Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.
Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.
Example #1 Poor variable checking leads to....
<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir = "/home/$username";
unlink("$homedir/$userfile");
echo "The file has been deleted!";
?>
Example #2 ... A filesystem attack
<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = $_POST['user_submitted_name']; // "../etc"
$userfile = $_POST['user_submitted_filename']; // "passwd"
$homedir = "/home/$username"; // "/home/../etc"
unlink("$homedir/$userfile"); // "/home/../etc/passwd"
echo "The file has been deleted!";
?>
Example #3 More secure file name checking
<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile = basename($_POST['user_submitted_filename']);
$homedir = "/home/$username";
$filepath = "$homedir/$userfile";
if (file_exists($filepath) && unlink($filepath)) {
$logstring = "Deleted $filepath\n";
} else {
$logstring = "Failed to delete $filepath\n";
}
$fp = fopen("/home/logging/filedelete.log", "a");
fwrite($fp, $logstring);
fclose($fp);
echo htmlentities($logstring, ENT_QUOTES);
?>
Example #4 More secure file name checking
<?php
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile = $_POST['user_submitted_filename'];
$homedir = "/home/$username";
$filepath = "$homedir/$userfile";
if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
die("Bad username/filename");
}
//etc...
?>
Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.
As PHP uses the underlying C functions for filesystem related operations, it may handle null bytes in a quite unexpected way. As null bytes denote the end of a string in C, strings containing them won't be considered entirely but rather only until a null byte occurs. The following example shows a vulnerable code that demonstrates this problem:
Example #1 Script vulnerable to null bytes
<?php
$file = $_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
// file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
include '/home/wwwrun/'.$file.'.php';
// the file /etc/passwd will be included
}
?>
Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:
Example #2 Correctly validating the input
<?php
$file = $_GET['file'];
// Whitelisting possible values
switch ($file) {
case 'main':
case 'foo':
case 'bar':
include '/home/wwwrun/include/'.$file.'.php';
break;
default:
include '/home/wwwrun/include/main.php';
}
?>
Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.
As you can surmise, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.
Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.
The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.
Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.
You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.
You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.
You may want to establish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.
SSL/SSH protects data travelling from the client to the server: SSL/SSH does not protect persistent data stored in a database. SSL is an on-the-wire protocol.
Once an attacker gains access to your database directly (bypassing the webserver), stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.
The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.
In the case of truly hidden data, if its raw representation is not needed (i.e. will not be displayed), hashing may also be taken into consideration. The well-known example for hashing is storing the cryptographic hash of a password in a database, instead of the password itself. See also crypt().
Example #1 Using hashed password field
<?php
// storing password hash
// $random_chars retrieved e.g. using /dev/random
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
pg_escape_string($username),
pg_escape_string(crypt($password, '$2a$07$' . $random_chars . '$')));
$result = pg_query($connection, $query);
// querying if user submitted the right password
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));
if ($row && crypt($password, $row['pwd']) == $row['pwd']) {
echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}
?>
Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.
Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build an SQL query. The following examples are based on true stories, unfortunately.
Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.
Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)
<?php
$offset = $argv[0]; // beware, no input validation!
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);
?>
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
--
Note:
It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.
A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.
Example #2 Listing out articles ... and some passwords (any database server)
<?php
$query = "SELECT id, name, inserted, size FROM products
WHERE size = '$size'";
$result = odbc_exec($conn, $query);
?>
' union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable; --
SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.
Example #3 From resetting a password ... to gaining more privileges (any database server)
<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
<?php
// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";
// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";
?>
A frightening example how operating system level commands can be accessed on some database hosts.
Example #4 Attacking the database hosts operating system (MSSQL Server)
<?php
$query = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
?>
<?php
$query = "SELECT * FROM products
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD' --%'";
$result = mssql_query($query);
?>
Note:
Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.
While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publicly-available software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'.
These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.
If the application waits for numerical input, consider verifying data with ctype_digit(), or silently change its type using settype(), or use its numeric representation by sprintf().
Example #5 A more secure way to compose a query for paging
<?php
settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
$offset);
?>
Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.
With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.
A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:
Example #1 Attacking Variables with a custom HTML page
<form method="post" action="attacktarget?username=badfoo&password=badfoo"> <input type="hidden" name="username" value="badfoo" /> <input type="hidden" name="password" value="badfoo" /> </form>
The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occurred in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:
Example #2 Exploiting common debugging variables
<form method="post" action="attacktarget?errors=Y&showerrors=1&debug=1"> <input type="hidden" name="errors" value="Y" /> <input type="hidden" name="showerrors" value="1" /> <input type="hidden" name="debug" value="1" /> </form>
Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.
For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.
A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.
A filesystem or general PHP error can indicate what permissions the web server has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.
There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.
One way of catching this issue ahead of time is to make use of
PHP's own error_reporting(), to help you
secure your code and find variable usage that may be dangerous.
By testing your code, prior to deployment, with E_ALL,
you can quickly find areas where your variables may be open to poisoning
or modification in other ways. Once you are ready for deployment,
you should either disable error reporting completely by setting
error_reporting() to 0, or turn off the error
display using the php.ini option display_errors,
to insulate your code from probing. If you choose to do the latter,
you should also define the path to your log file using the
error_log ini directive, and turn
log_errors on.
Example #3 Finding dangerous variables with E_ALL
<?php
if ($username) { // Not initialized or checked before usage
$good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
readfile ("/highly/sensitive/data/index.html");
}
?>
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP » 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.
When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:
Example #1 Example misuse with register_globals = on
<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
$authorized = true;
}
// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
include "/highly/sensitive/data.php";
}
?>
When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.
Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).
Example #2 Example use of sessions with register_globals on or off
<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {
echo "Hello <b>{$_SESSION['username']}</b>";
} else {
echo "Hello <b>Guest</b><br />";
echo "Would you like to login?";
}
?>
It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from external sources.
Example #3 Detecting simple variable poisoning
<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {
// MAGIC_COOKIE comes from a cookie.
// Be sure to validate the cookie data!
} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {
mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
echo "Security violation, admin has been alerted.";
exit;
} else {
// MAGIC_COOKIE isn't set through this REQUEST
}
?>
Of course, simply turning off register_globals does not mean your code
is secure. For every piece of data that is submitted, it should also be
checked in other ways. Always validate your user data and initialize
your variables! To check for uninitialized variables you may turn up
error_reporting() to show
E_NOTICE level errors.
For information about emulating register_globals being On or Off, see this FAQ.
Note: Superglobals: availability note
Superglobal arrays such as $_GET, $_POST, and $_SERVER, etc. are available as of PHP 4.1.0. For more information, read the manual section on superglobals
The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.
Example #1 Dangerous Variable Usage
<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);
// Write logging of their access... or maybe an /etc/passwd entry?
fwrite ($fp, $evil_var);
// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);
?>
You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:
By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.
You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.
There are three magic quote directives:
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.
Example #1 Disabling magic quotes server side
An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.
; Magic quotes ; ; Magic quotes for incoming GET/POST/Cookie data. magic_quotes_gpc = Off ; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc. magic_quotes_runtime = Off ; Use Sybase-style magic quotes (escape ' with '' instead of \'). magic_quotes_sybase = Off
If access to the server configuration is unavailable, use of .htaccess is also an option. For example:
php_flag magic_quotes_gpc Off
In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.
Example #2 Disabling magic quotes at runtime
<?php
if (get_magic_quotes_gpc()) {
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)) {
foreach ($val as $k => $v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
?>
In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.
A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php to off in your php.ini file, you reduce the amount of information available to them.
Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:
Example #1 Hiding PHP as another language
# Make PHP code look like other code types AddType application/x-httpd-php .asp .py .pl
Example #2 Using unknown types for PHP extensions
# Make PHP code look like unknown types AddType application/x-httpd-php .bop .foo .133t
Example #3 Using HTML types for PHP extensions
# Make all PHP code look like HTML AddType application/x-httpd-php .htm .html
PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance security and repair any flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.
Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.
It is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported. See the header() function for more information.
Note: PHP Version Note
Superglobals, such as $_SERVER, became available in PHP » 4.1.0.
An example script fragment which would force client authentication on a page is as follows:
Example #1 Basic HTTP Authentication example
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
Example #2 Digest HTTP Authentication example
This example shows you how to implement a simple Digest HTTP authentication script. For more information read the » RFC 2617.
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response)
die('Wrong Credentials!');
// ok, valid username & password
echo 'You are logged in as: ' . $data['username'];
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
Note: Compatibility Note
Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above.
Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.
Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.
As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].
Note: Configuration Note
PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.
Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.
Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.
Example #3 HTTP Authentication example forcing a new name/password
<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Test Authentication System"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid login ID and password to access this resource\n";
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER']) ||
($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
authenticate();
} else {
echo "<p>Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "<br />";
echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']);
echo "<form action='' method='post'>\n";
echo "<input type='hidden' name='SeenBefore' value='1' />\n";
echo "<input type='hidden' name='OldAuth' value=\"" . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "\" />\n";
echo "<input type='submit' value='Re Authenticate' />\n";
echo "</form></p>\n";
}
?>
This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.
Also note that until PHP 4.3.3, HTTP Authentication did not work using Microsoft's IIS server with the CGI version of PHP due to a limitation of IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.
Another limitation is if you're using the IIS module (ISAPI) and PHP 4, you may not use the PHP_AUTH_* variables but instead, the variable HTTP_AUTHORIZATION is available. For example, consider the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
Note: IIS Note:
For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).
Note:
If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.
» XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.
The first key difference in XForms is how the form is sent to the client. » XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.
Example #1 A simple XForms search form
<h:html xmlns:h="http://www.w3.org/1999/xhtml"
xmlns="http://www.w3.org/2002/xforms">
<h:head>
<h:title>Search</h:title>
<model>
<submission action="http://example.com/search"
method="post" id="s"/>
</model>
</h:head>
<h:body>
<h:p>
<input ref="q"><label>Find</label></input>
<submit submission="s"><label>Go</label></submit>
</h:p>
</h:body>
</h:html>
The above form displays a text input box (named q),
and a submit button. When the submit button is clicked, the form will be
sent to the page referred to by action.
Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.
If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.
If you're not interested in formatting and just want your data to be loaded
into the traditional $_POST variable, you can instruct
the client browser to send it as application/x-www-form-urlencoded
by changing the method attribute to
urlencoded-post.
Example #2 Using an XForm to populate $_POST
<h:html xmlns:h="http://www.w3.org/1999/xhtml"
xmlns="http://www.w3.org/2002/xforms">
<h:head>
<h:title>Search</h:title>
<model>
<submission action="http://example.com/search"
method="urlencoded-post" id="s"/>
</model>
</h:head>
<h:body>
<h:p>
<input ref="q"><label>Find</label></input>
<submit submission="s"><label>Go</label></submit>
</h:p>
</h:body>
</h:html>
Note: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.
This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.
PHP is capable of receiving file uploads from any RFC-1867 compliant browser.
Note: Related Configurations Note
See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini
PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.
Example #1 File Upload Form
A file upload screen can be built by creating a special form which looks something like this:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
The __URL__ in the above example should be replaced, and point to a PHP file.
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.
Note:
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
The global $_FILES exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if using an earlier version). These arrays will contain all the uploaded file information.
The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.
The original name of the file on the client machine.
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
The size, in bytes, of the uploaded file.
The temporary filename of the file in which the uploaded file was stored on the server.
The error code associated with this file upload. This element was added in PHP 4.2.0
Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.
Example #2 Validating file uploads
See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.
If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.
The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.
Example #3 Uploading array of files
PHP supports HTML array feature even with files.
<form action="" method="post" enctype="multipart/form-data"> <p>Pictures: <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="submit" value="Send" /> </p> </form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
File upload progress bar can be implemented using Session Upload Progress.
Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error'].
UPLOAD_ERR_OKValue: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZEValue: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZEValue: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIALValue: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILEValue: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIRValue: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
UPLOAD_ERR_CANT_WRITEValue: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSIONValue: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.
Note:
These became PHP constants in PHP 4.3.0.
The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the php.ini file. The default is 2 megabytes.
If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough.
If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough.
Note: max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running.
max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded.
If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough.
Since PHP 5.2.12, the max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items.
Not validating which file you operate on may mean that users can access sensitive information in other directories.
Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature.
Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly.
A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]).
Multiple files can be uploaded using different name for input.
It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:
Example #1 Uploading multiple files
<form action="file-upload.php" method="post" enctype="multipart/form-data"> Send these files:<br /> <input name="userfile[]" type="file" /><br /> <input name="userfile[]" type="file" /><br /> <input type="submit" value="Send files" /> </form>
When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files.
For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth.
$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.
Since PHP 5.2.12, the max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit.
PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:
PUT /path/filename.html HTTP/1.1
This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <VirtualHost> block. A line like this would do the trick:
Script PUT /put.php
This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have.
With PHP you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy.
Example #1 Saving HTTP PUT files
<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");
/* Read the data 1 KB at a time
and write to the file */
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
?>
As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include, include_once, require and require_once statements (since PHP 5.2.0, allow_url_include must be enabled for these). See Supported Protocols and Wrappers for more information about the protocols supported by PHP.
Note:
In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option --enable-url-fopen-wrapper .
Note:
The Windows versions of PHP earlier than PHP 4.3 did not support remote file accessing for the following functions: include, include_once, require, require_once, and the imagecreatefromXXX functions in the GD and Image Functions extension.
For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.
Example #1 Getting the title of a remote page
<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
echo "<p>Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* This only works if the title and its tags are on one line */
if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>
You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.
To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)
Example #2 Storing data on a remote server
<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>
Note:
You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().
Internally in PHP a connection status is maintained. There are 3 possible states:
When a PHP script is running normally, the NORMAL state is active. If the remote client disconnects, the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.
You can decide whether or not you want a client disconnect to cause
your script to be aborted. Sometimes it is handy to always have your
scripts run to completion even if there is no remote browser receiving
the output. The default behaviour is however for your script to be
aborted when the remote client disconnects. This behaviour can be
set via the ignore_user_abort php.ini directive as well as through
the corresponding php_value ignore_user_abort Apache
httpd.conf directive or
with the ignore_user_abort() function. If you do
not tell PHP to ignore a user abort and the user aborts, your script
will terminate. The one exception is if you have registered a shutdown
function using register_shutdown_function(). With a
shutdown function, when the remote user hits his STOP button, the
next time your script tries to output something PHP will detect that
the connection has been aborted and the shutdown function is called.
This shutdown function will also get called at the end of your script
terminating normally, so to do something different in case of a client
disconnect you can use the connection_aborted()
function. This function will return TRUE if the connection was
aborted.
Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache httpd.conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called.
One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.
Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.
Why?
This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.
The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.
The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.
The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before.
If persistent connections don't have any added functionality, what are they good for?
The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.
Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.
There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is that when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere).
An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!
See also fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), oci_pconnect(), pfsockopen(), pg_pconnect(), and sybase_pconnect().
The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now.
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
| Version | Description |
|---|---|
| 5.4.0 |
Removed from PHP, and generates a fatal E_CORE_ERROR
level error when enabled.
|
| 5.3.0 |
Deprecated, and E_DEPRECATED errors were added.
|
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0. |
| safe_mode_gid | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0. Removed in PHP 5.4.0. |
| safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Available since PHP 4.1.0. Removed in PHP 5.4.0. |
| safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Removed in PHP 5.4.0. |
| safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Removed in PHP 5.4.0. |
| safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Removed in PHP 5.4.0. |
Here's a short explanation of the configuration directives.
safe_mode
boolean
Whether to enable PHP's safe mode. If PHP is compiled with --enable-safe-mode then defaults to On, otherwise Off.
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
safe_mode_gid
boolean
By default, Safe Mode does a UID compare check when
opening files. If you want to relax this to a GID compare,
then turn on safe_mode_gid.
Whether to use UID (FALSE) or
GID (TRUE) checking upon file
access.
safe_mode_include_dir
string
UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).
As of PHP 4.2.0, this directive can take a colon (semi-colon on Windows) separated path in a fashion similar to the include_path directive, rather than just a single directory. The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "safe_mode_include_dir = /dir/incl/" If the value of this directive is empty, no files with different UID/GID can be included in PHP 4.2.3 and as of PHP 4.3.3. In earlier versions, all files could be included.safe_mode_exec_dir
string
If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.
safe_mode_allowed_env_vars
string
Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).
Note:
If this directive is empty, PHP will let the user modify ANY environment variable!
safe_mode_protected_env_vars
string
This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.
See also: open_basedir, disable_functions, disable_classes, register_globals, display_errors, and log_errors.
When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:
-rw-rw-r-- 1 rasmus rasmus 33 Jul 1 19:20 script.php -rw-r--r-- 1 root root 1116 May 26 18:01 /etc/passwd
<?php
readfile('/etc/passwd');
?>
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2
However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.
If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory. For example (Apache httpd.conf example):
<Directory /docroot> php_admin_value open_basedir /docroot </Directory>
Warning: open_basedir restriction in effect. File is in wrong directory in /docroot/script.php on line 2
You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:
disable_functions = readfile,system
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2
These PHP restrictions are not valid in executed binaries, of course.
This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.
| Function | Limitations |
|---|---|
| dbmopen() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| dbase_open() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| filepro() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| filepro_rowcount() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| filepro_retrieve() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| ifx_* | sql_safe_mode restrictions, (!= safe mode) |
| ingres_* | sql_safe_mode restrictions, (!= safe mode) |
| mysql_* | sql_safe_mode restrictions, (!= safe mode) |
| pg_lo_import() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| posix_mkfifo() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| putenv() | Obeys the safe_mode_protected_env_vars and safe_mode_allowed_env_vars ini-directives. See also the documentation on putenv() |
| move_uploaded_file() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| chdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| dl() | This function is disabled when PHP is running in safe mode. |
| backtick operator | This function is disabled when PHP is running in safe mode. |
| shell_exec() (functional equivalent of backticks) | This function is disabled when PHP is running in safe mode. |
| exec() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| system() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| passthru() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| popen() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function. |
| fopen() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| mkdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| rmdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| rename() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| unlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| copy() | Checks whether the files or directories being operated
upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which
the script is operating has the same UID (owner) as the script that is being
executed. (on
source and
target) |
| chgrp() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| chown() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. |
| chmod() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits |
| touch() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. |
| symlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only the target is checked) |
| link() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only the target is checked) |
| apache_request_headers() | In safe mode, headers beginning with authorization (case-insensitive) will not be returned. |
| header() | In safe mode, the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication). |
| PHP_AUTH variables | In safe mode, the variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE are not available in $_SERVER. Regardless, you can still use REMOTE_USER for the USER. (note: only affected since PHP 4.3.0) |
| highlight_file(), show_source() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1) |
| parse_ini_file() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only affected since PHP 4.2.1) |
| set_time_limit() | Has no effect when PHP is running in safe mode. |
| max_execution_time | Has no effect when PHP is running in safe mode. |
| mail() | In safe mode, the fifth parameter is disabled. (note: only affected since PHP 4.2.3) |
| session_start() | The owner of a script must be the same as owner of a session.save_path directory if the default files session.save_handler is used. |
| All filesystem and stream functions. | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (see the safe_mode_include_dir php.ini option. |
PHP supports a CLI SAPI as of PHP 4.3.0. The main focus of this SAPI is for developing shell applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It is worth mentioning that CLI and CGI are different SAPIs although they do share many of the same behaviors.
The CLI SAPI is enabled by default using --enable-cli , but may be disabled using the --disable-cli option when running ./configure.
The name, location and existence of the CLI/CGI binaries will differ depending on how PHP is installed on your system. By default when executing make, both the CGI and CLI are built and placed as sapi/cgi/php-cgi and sapi/cli/php respectively, in your PHP source directory. You will note that both are named php. What happens during make install depends on your configure line. If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. So, for example, if --with-apxs is in your configure line then the CLI is copied to {PREFIX}/bin/php during make install. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify --disable-cgi in your configure line.
Note:
Because both --enable-cli and --enable-cgi are enabled by default, simply having --enable-cli in your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.
As of PHP 5, the CLI binary is distributed in the main folder as php.exe on Windows. The CGI version is distributed as php-cgi.exe. Additionally, a php-win.exe is distributed if PHP is configured using --enable-cli-win32 . This does the same as the CLI version, except that it doesn't output anything and thus provides no console.
Note: What SAPI do I have?
From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant
PHP_SAPI.
Note:
A Unix manual page is available by typing man php in the shell environment.
Remarkable differences of the CLI SAPI compared to other SAPIs:
Unlike the CGI SAPI, no headers are written to the output.
Though the CGI SAPI provides a way to suppress HTTP headers, there's no equivalent switch to enable them in the CLI SAPI.
CLI is started up in quiet mode by default, though the -q and --no-header switches are kept for compatibility so that it is possible to use older CGI scripts.
It does not change the working directory to that of the script. (-C and --no-chdir switches kept for compatibility)
Plain text error messages (no HTML formatting).
There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:
| Directive | CLI SAPI default value | Comment |
|---|---|---|
| html_errors | FALSE |
Defaults to FALSE, as it can be quite hard to read error messages
in the shell enviroment when they are cluttered up with uninterpreted
HTML tags.
|
| implicit_flush | TRUE |
In a shell environment, it is usually desirable for output, such as from print, echo and friends, to be displayed immediately, and not held in a buffer. Nonetheless, it is still possible to use output buffering to defer or manipulate standard output. |
| max_execution_time | 0 (unlimited) | PHP in a shell environment tends to be used for a much more diverse range of purposes than typical Web-based scripts, and as these can be very long-running, the maximum execution time is set to unlimited. |
| register_argc_argv | TRUE |
Setting this to The PHP variables $argc and $argv are automatically set to the appropriate values when using the CLI SAPI. These values can also be found in the $_SERVER array, for example: $_SERVER['argv']. |
| output_buffering | FALSE |
Although the php.ini setting is hardcoded to |
| max_input_time | FALSE |
The PHP CLI does not support GET, POST or file uploads. |
Note:
These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This limitation is because the values are applied after all configuration files have been parsed. However, their values can be changed during runtime (although this is not sensible for all of them, such as register_argc_argv).
Note:
It is recommended to set ignore_user_abort for command line scripts. See ignore_user_abort() for more information.
To ease working in the shell environment, a number of constants are defined for I/O streams .
The CLI SAPI does not change the current directory to the directory of the executed script.
Example #1 Example showing the difference to the CGI SAPI:
<?php
// Our simple test application named test.php
echo getcwd(), "\n";
?>
When using the CGI version, the output is:
$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directory
This clearly shows that PHP changes its current directory to the one of the executed script.
Using the CLI SAPI yields:
$ pwd /tmp $ php -f another_directory/test.php /tmp
This allows greater flexibility when writing shell tools in PHP.
Note:
The CGI SAPI supports this CLI SAPI behaviour by means of the -C switch when run from the command line.
The list of command line options provided by the PHP binary can be queried at any time by running PHP with the -h switch:
Usage: php [options] [-f] <file> [--] [args...]
php [options] -r <code> [--] [args...]
php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
php [options] -- [args...]
php [options] -a
-a Run interactively
-c <path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse and execute <file>.
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r <code> Run PHP <code> without using script tags <?..?>
-B <begin_code> Run PHP <begin_code> before processing input lines
-R <code> Run PHP <code> for every input line
-F <file> Parse and execute <file> for every input line
-E <end_code> Run PHP <end_code> after processing all input lines
-H Hide any passed arguments from external tools.
-S <addr>:<port> Run with built-in web server.
-t <docroot> Specify document root <docroot> for built-in web server.
-s Output HTML syntax highlighted source.
-v Version number
-w Output source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.
args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin
--ini Show configuration file names
--rf <name> Show information about function <name>.
--rc <name> Show information about class <name>.
--re <name> Show information about extension <name>.
--rz <name> Show information about Zend extension <name>.
--ri <name> Show configuration for extension <name>.
| Option | Long Option | Description |
|---|---|---|
| -a | --interactive |
Run PHP interactively. For more information, see the Interactive shell section. |
| -b | --bindpath |
Bind Path for external FASTCGI Server mode (CGI only). |
| -C | --no-chdir |
Do not chdir to the script's directory (CGI only). |
| -q | --no-header |
Quiet-mode. Suppress HTTP header output (CGI only). |
| -T | --timing |
Measure execution time of script repeated count times (CGI only). |
| -c | --php-ini |
Specifies either a directory in which to look for php.ini, or a custom INI file (which does not need to be named php.ini), e.g.: $ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.php If this option is not specified, php.ini is searched for in the default locations. |
| -n | --no-php-ini |
Ignore php.ini completely. |
| -d | --define |
Set a custom value for any of the configuration directives allowed in php.ini. The syntax is: -d configuration_directive[=value]
# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"
# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""
# The configuration directive will be set to anything passed after the '=' character
$ php -d max_execution_time=20
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$ php
-d max_execution_time=doesntmakesense
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"
|
| -e | --profile-info |
Activate the extended information mode, to be used by a debugger/profiler. |
| -f | --file |
Parse and execute the specified file. The -f is optional and may be omitted - providing just the filename to execute is sufficient.
|
| -h and -? | --help and --usage | Output a list of command line options with one line descriptions of what they do. |
| -i | --info | Calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use the command php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore very large. |
| -l | --syntax-check |
Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to -1. This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.
|
| -m | --modules |
Example #1 Printing built in (and loaded) PHP and Zend modules $ php -m [PHP Modules] xml tokenizer standard session posix pcre overload mysql mbstring ctype [Zend Modules] |
| -r | --run |
Allows execution of PHP included directly on the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parse error if present.
|
| -B | --process-begin |
PHP code to execute before processing stdin. Added in PHP 5. |
| -R | --process-code |
PHP code to execute for every input line. Added in PHP 5. There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number. |
| -F | --process-file |
PHP file to execute for every input line. Added in PHP 5. |
| -E | --process-end |
PHP code to execute after processing the input. Added in PHP 5. Example #4 Using the -B , -R and -E options to count the number of lines of a project. $ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";' Total Lines: 37328 |
| -S | --server |
Starts built-in web server. Available as of PHP 5.4.0. |
| -t | --docroot | Specifies document root for built-in web server. Available as of PHP 5.4.0. |
| -s | --syntax-highlight and --syntax-highlighting |
Display colour syntax highlighted source. This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of <code> [...] </code> HTML tags, no HTML headers.
|
| -v | --version |
Example #5 Using -v to get the SAPI name and the version of PHP and Zend $ php -v PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies |
| -w | --strip |
Display source with comments and whitespace stripped.
|
| -z | --zend-extension |
Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually /etc/ld.so.conf on Linux systems, for example). Passing a filename with an absolute path will not use the system's library search path. A relative filename including directory information will tell PHP to try loading the extension relative to the current directory. |
| --ini |
Show configuration file names and scanned directories. Available as of PHP 5.2.3. Example #6 --ini example $ php --ini Configuration File (php.ini) Path: /usr/dev/php/5.2/lib Loaded Configuration File: /usr/dev/php/5.2/lib/php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none) |
|
| --rf | --rfunction |
Show information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support.
Example #7 basic --rf usage $ php --rf var_dump
Function [ <internal> public function var_dump ] {
- Parameters [2] {
Parameter #0 [ <required> $var ]
Parameter #1 [ <optional> $... ]
}
}
|
| --rc | --rclass |
Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support.
Example #8 --rc example $ php --rc Directory
Class [ <internal:standard> class Directory ] {
- Constants [0] {
}
- Static properties [0] {
}
- Static methods [0] {
}
- Properties [0] {
}
- Methods [3] {
Method [ <internal> public method close ] {
}
Method [ <internal> public method rewind ] {
}
Method [ <internal> public method read ] {
}
}
}
|
| --re | --rextension |
Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support.
Example #9 --re example $ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {
- Functions {
Function [ <internal> function json_encode ] {
}
Function [ <internal> function json_decode ] {
}
}
}
|
| --rz | --rzendextension |
Show the configuration information for the given Zend extension (the same information that is returned by phpinfo()). Available as of PHP 5.4.0. |
| --ri | --rextinfo |
Show the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information is available using "main" as extension name.
Example #10 --ri example $ php --ri date date date/time support => enabled "Olson" Timezone Database Version => 2009.20 Timezone Database => internal Default timezone => Europe/Oslo Directive => Local Value => Master Value date.timezone => Europe/Oslo => Europe/Oslo date.default_latitude => 59.930972 => 59.930972 date.default_longitude => 10.776699 => 10.776699 date.sunset_zenith => 90.583333 => 90.583333 date.sunrise_zenith => 90.583333 => 90.583333 |
Note:
Options -rBRFEH, --ini and --r[fcezi] are available only in CLI.
There are three different ways of supplying the CLI SAPI with PHP code to be executed:
Tell PHP to execute a certain file.
$ php my_script.php $ php -f my_script.php
Both ways (whether using the -f switch or not) execute the file my_script.php. Note that there is no restriction on which files can be executed; in particular, the filename is not required have a .php extension.
Note:
If arguments need to be passed to the script when using -f , the first argument must be --.
Pass the PHP code to execute directly on the command line.
$ php -r 'print_r(get_defined_constants());'
Special care has to be taken with regard to shell variable substitution and usage of quotes.
Note:
Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.
Provide the PHP code to execute via standard input (stdin).
This gives the powerful ability to create PHP code dynamically and feed it to the binary, as shown in this (fictional) example:
$ some_application | some_filter | php | sort -u > final_output.txt
As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv. The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r , the value of $argv[0] will be just a dash (-). The same is true if the code is executed via a pipe from STDIN.
A second global variable, $argc, contains the number of elements in the $argv array (not the number of arguments passed to the script).
As long as the arguments to be passed to the script do not start with the - character, there's nothing special to watch out for. Passing an argument to the script which starts with a - will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every following argument is passed untouched to the script.
# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]
# This will pass the '-h' argument to the script and prevent PHP from showing its usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
}
However, on Unix systems there's another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script:
Example #1 Execute PHP script as shell script
#!/usr/bin/php
<?php
var_dump($argv);
?>
Assuming this file is named test in the current directory, it is now possible to do the following:
$ chmod +x test
$ ./test -h -- foo
array(4) {
[0]=>
string(6) "./test"
[1]=>
string(2) "-h"
[2]=>
string(2) "--"
[3]=>
string(3) "foo"
}
As can be seen, in this case no special care needs to be taken when passing parameters starting with -.
The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or "shebang") first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it's possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it's formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.
Example #2 Script intended to be run from command line (script.php)
#!/usr/bin/php
<?php
if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
This is a command line PHP script with one option.
Usage:
<?php echo $argv[0]; ?> <option>
<option> can be some word you would like
to print out. With the --help, -help, -h,
or -? options, you can get this help.
<?php
} else {
echo $argv[1];
}
?>
The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.
The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was --help , -help , -h or -? , the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.
To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:
Example #3 Batch file to run a command line PHP script (script.bat)
@echo OFF "C:\php\php.exe" script.php %*
Assuming the above program is named script.php, and the CLI php.exe is in C:\php\php.exe, this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.
See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.
On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.
The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.
| Constant | Description |
|---|---|
STDIN |
An already opened stream to stdin. This saves opening it with
<?php
<?php |
STDOUT |
An already opened stream to stdout. This saves opening it with
<?php |
STDERR |
An already opened stream to stderr. This saves opening it with
<?php |
Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:
php -r 'fwrite(STDERR, "stderr\n");'
Note:
These constants are not available if reading the PHP script from stdin.
As of PHP 5.1.0, the CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option.
Using the interactive shell you are able to type PHP code and have it executed directly.
Example #1 Executing code using the interactive shell
$ php -a
Interactive shell
php > echo 5+8;
13
php > function addTwo($n)
php > {
php { return $n + 2;
php { }
php > var_dump(addtwo(2));
int(4)
php >
The interactive shell also features tab completion for functions, constants, class names, variables, static method calls and class constants.
Example #2 Tab completion
Pressing the tab key twice when there are multiple possible completions will result in a list of these completions:
php > strp[TAB][TAB] strpbrk strpos strptime php > strp
When there is only one possible completion, pressing tab once will complete the rest on the same line:
php > strpt[TAB]ime(
Completion will also work for names that have been defined during the current interactive shell session:
php > $fooThisIsAReallyLongVariableName = 42; php > $foo[TAB]ThisIsAReallyLongVariableName
The interactive shell stores your history which can be accessed using the up and down keys. The history is saved in the ~/.php_history file.
As of PHP 5.4.0, the CLI SAPI provides
the php.ini settings cli.pager and
cli.prompt. The cli.pager
setting allows an external program (such as less) to
act as a pager for the output instead of being displayed directly on the
screen. The cli.prompt setting makes it possible to
change the php > prompt.
In PHP 5.4.0 it was also made possible to set php.ini settings in the interactive shell using a shorthand notation.
Example #3 Setting php.ini settings in the interactive shell
The cli.prompt setting:
php > #cli.prompt=hello world :> hello world :>
Using backticks it is possible to have PHP code executed in the prompt:
php > #cli.prompt=`echo date('H:i:s');` php >
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >
Setting the pager to less:
php > #cli.pager=less php > phpinfo(); (output displayed in less) php >
The cli.prompt setting supports a few escape
sequences:
| Sequence | Description |
|---|---|
| \e | Used for adding colors to the prompt. An example could be \e[032m\v \e[031m\b \e[34m\> \e[0m |
| \v | The PHP version. |
| \b | Indicates which block PHP is in. For instance /* to indicate being inside a multi-line comment. The outer scope is denoted by php. |
| \> | Indicates the prompt character. By default this is >, but changes when the shell is inside an unterminated block or string. Possible characters are: ' " { ( > |
Note:
Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions - e.g. functions have to be defined before called.
Note:
Autoloading is not available if using PHP in CLI interactive mode.
This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.
As of PHP 5.4.0, the CLI SAPI provides a built-in web server.
PHP applications will stall if a request is blocked.
URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, then a 404 response code is returned.
If a PHP file is given on the command line when the web server is
started it is treated as a "router" script. The script is run at
the start of each HTTP request. If this script returns FALSE,
then the requested resource is returned as-is. Otherwise the
script's output is returned to the browser.
Standard MIME types are returned for files with extensions: .3gp, .apk, .avi, .bmp, .css, .csv, .doc, .docx, .flac, .gif, .gz, .gzip, .htm, .html, .ics, .jpe, .jpeg, .jpg, .js, .kml, .kmz, .m4a, .mov, .mp3, .mp4, .mpeg, .mpg, .odp, .ods, .odt, .oga, .ogg, .ogv, .pdf, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx and .zip.
MIME type support for .htm and .svg extensions was added in PHP 5.4.4. The .ogg, .ogv, and .webm extensions were added in PHP 5.4.11. The .pdf extension is recognized from PHP 5.5.5. The .3gp, .apk, .avi, .bmp, .csv, .doc, .docx, .flac, .gz, .gzip, .ics, .kml, .kmz, .m4a, .mp3, .mp4, .mpg, .mpeg, .mov, .odp, .ods, .odt, .oga, .pdf, .pptx, .pps, .qt, .swf, .tar, .text, .tif, .wav, .wmv, .xls, .xlsx and .zip extensions were added in PHP 5.5.7.
Example #1 Starting the web server
$ cd ~/public_html $ php -S localhost:8000
The terminal will show:
PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011 Listening on localhost:8000 Document root is /home/me/public_html Press Ctrl-C to quit
After URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to:
PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011 Listening on localhost:8000 Document root is /home/me/public_html Press Ctrl-C to quit. [Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read [Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read [Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read [Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read [Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read
Example #2 Starting with a specific document root directory
$ cd ~/public_html $ php -S localhost:8000 -t foo/
The terminal will show:
PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011 Listening on localhost:8000 Document root is /home/me/public_html/foo Press Ctrl-C to quit
Example #3 Using a Router Script
In this example, requests for images will display them, but requests for HTML files will display "Welcome to PHP":
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false; // serve the requested resource as-is.
} else {
echo "<p>Welcome to PHP</p>";
}
?>
$ php -S localhost:8000 router.php
Example #4 Checking for CLI Web Server Use
To reuse a framework router script during development with the CLI web server and later also with a production web server:
<?php
// router.php
if (php_sapi_name() == 'cli-server') {
/* route static assets and return false */
}
/* go on with normal index.php operations */
?>
$ php -S localhost:8000 router.php
Example #5 Handling Unsupported File Types
If you need to serve a static resource whose MIME type is not handled by the CLI web server, use:
<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "el") {
header("Content-Type: text/x-script.elisp");
readfile($_SERVER["SCRIPT_FILENAME"]);
}
else {
return FALSE;
}
?>
$ php -S localhost:8000 router.php
Example #6 Accessing the CLI Web Server From Remote Machines
You can make the web server accessible on port 8000 to any interface with:
$ php -S 0.0.0.0:8000
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| cli_server.color | "0" | PHP_INI_ALL | Available since PHP 5.4.0. |
Here's a short explanation of the configuration directives.
cli_server.color
boolean
Enable the built-in development web server to use ANSI color coding in terminal output.
This section explains the merits of the new Garbage Collection (also known as GC) mechanism that is part of PHP 5.3.
A PHP variable is stored in a container called a "zval". A zval container contains, besides the variable's type and value, two additional bits of information. The first is called "is_ref" and is a boolean value indicating whether or not the variable is part of a "reference set". With this bit, PHP's engine knows how to differentiate between normal variables and references. Since PHP allows user-land references, as created by the & operator, a zval container also has an internal reference counting mechanism to optimize memory usage. This second piece of additional information, called "refcount", contains how many variable names (also called symbols) point to this one zval container. All symbols are stored in a symbol table, of which there is one per scope. There is a scope for the main script (i.e., the one requested through the browser), as well as one for every function or method.
A zval container is created when a new variable is created with a constant value, such as:
Example #1 Creating a new zval container
<?php
$a = "new string";
?>
In this case, the new symbol name, a, is created in the current scope,
and a new variable container is created with the type string and the value
new string. The "is_ref" bit is by default set to FALSE because no
user-land reference has been created. The "refcount" is set to 1 as
there is only one symbol that makes use of this variable container. Note
that if "refcount" is 1, "is_ref" is always FALSE. If you have » Xdebug installed, you can display this
information by calling xdebug_debug_zval().
Example #2 Displaying zval information
<?php
xdebug_debug_zval('a');
?>
The above example will output:
a: (refcount=1, is_ref=0)='new string'
Assigning this variable to another variable name will increase the refcount.
Example #3 Increasing refcount of a zval
<?php
$a = "new string";
$b = $a;
xdebug_debug_zval( 'a' );
?>
The above example will output:
a: (refcount=2, is_ref=0)='new string'
The refcount is 2 here, because the same variable container is linked with both a and b. PHP is smart enough not to copy the actual variable container when it is not necessary. Variable containers get destroyed when the "refcount" reaches zero. The "refcount" gets decreased by one when any symbol linked to the variable container leaves the scope (e.g. when the function ends) or when unset() is called on a symbol. The following example shows this:
Example #4 Decreasing zval refcount
<?php
$a = "new string";
$c = $b = $a;
xdebug_debug_zval( 'a' );
unset( $b, $c );
xdebug_debug_zval( 'a' );
?>
The above example will output:
a: (refcount=3, is_ref=0)='new string' a: (refcount=1, is_ref=0)='new string'
If we now call unset($a);, the variable container, including the type and value, will be removed from memory.
Things get a tad more complex with compound types such as arrays and objects. Instead of a scalar value, arrays and objects store their properties in a symbol table of their own. This means that the following example creates three zval containers:
Example #5 Creating a array zval
<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
xdebug_debug_zval( 'a' );
?>
The above example will output something similar to:
a: (refcount=1, is_ref=0)=array ( 'meaning' => (refcount=1, is_ref=0)='life', 'number' => (refcount=1, is_ref=0)=42 )
Or graphically
The three zval containers are: a, meaning, and number. Similar rules apply for increasing and decreasing "refcounts". Below, we add another element to the array, and set its value to the contents of an already existing element:
Example #6 Adding already existing element to an array
<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
xdebug_debug_zval( 'a' );
?>
The above example will output something similar to:
a: (refcount=1, is_ref=0)=array ( 'meaning' => (refcount=2, is_ref=0)='life', 'number' => (refcount=1, is_ref=0)=42, 'life' => (refcount=2, is_ref=0)='life' )
Or graphically
From the above Xdebug output, we see that both the old and new array elements now point to a zval container whose "refcount" is 2. Although Xdebug's output shows two zval containers with value 'life', they are the same one. The xdebug_debug_zval() function does not show this, but you could see it by also displaying the memory pointer.
Removing an element from the array is like removing a symbol from a scope. By doing so, the "refcount" of a container that an array element points to is decreased. Again, when the "refcount" reaches zero, the variable container is removed from memory. Again, an example to show this:
Example #7 Removing an element from an array
<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
unset( $a['meaning'], $a['number'] );
xdebug_debug_zval( 'a' );
?>
The above example will output something similar to:
a: (refcount=1, is_ref=0)=array ( 'life' => (refcount=1, is_ref=0)='life' )
Now, things get interesting if we add the array itself as an element of the array, which we do in the next example, in which we also sneak in a reference operator, since otherwise PHP would create a copy:
Example #8 Adding the array itself as an element of it self
<?php
$a = array( 'one' );
$a[] =& $a;
xdebug_debug_zval( 'a' );
?>
The above example will output something similar to:
a: (refcount=2, is_ref=1)=array ( 0 => (refcount=1, is_ref=0)='one', 1 => (refcount=2, is_ref=1)=... )
Or graphically
You can see that the array variable (a) as well as the second element (1) now point to a variable container that has a "refcount" of 2. The "..." in the display above shows that there is recursion involved, which, of course, in this case means that the "..." points back to the original array.
Just like before, unsetting a variable removes the symbol, and the reference count of the variable container it points to is decreased by one. So, if we unset variable $a after running the above code, the reference count of the variable container that $a and element "1" point to gets decreased by one, from "2" to "1". This can be represented as:
Example #9 Unsetting $a
(refcount=1, is_ref=1)=array ( 0 => (refcount=1, is_ref=0)='one', 1 => (refcount=1, is_ref=1)=... )
Or graphically
Although there is no longer a symbol in any scope pointing to this structure, it cannot be cleaned up because the array element "1" still points to this same array. Because there is no external symbol pointing to it, there is no way for a user to clean up this structure; thus you get a memory leak. Fortunately, PHP will clean up this data structure at the end of the request, but before then, this is taking up valuable space in memory. This situation happens often if you're implementing parsing algorithms or other things where you have a child point back at a "parent" element. The same situation can also happen with objects of course, where it actually is more likely to occur, as objects are always implicitly used by reference.
This might not be a problem if this only happens once or twice, but if there are thousands, or even millions, of these memory losses, this obviously starts being a problem. This is especially problematic in long running scripts, such as daemons where the request basically never ends, or in large sets of unit tests. The latter caused problems while running the unit tests for the Template component of the eZ Components library. In some cases, it would require over 2 GB of memory, which the test server didn't quite have.
Traditionally, reference counting memory mechanisms, such as that used previously by PHP, fail to address circular reference memory leaks. As of 5.3.0 PHP however implements the synchronous algorithm from the » Concurrent Cycle Collection in Reference Counted Systems paper which addresses that issue.
A full explanation of how the algorithm works would be slightly beyond the scope of this section, but the basics are explained here. First of all, we have to establish a few ground rules. If a refcount is increased, it's still in use and therefore, not garbage. If the refcount is decreased and hits zero, the zval can be freed. This means that garbage cycles can only be created when a refcount argument is decreased to a non-zero value. Secondly, in a garbage cycle, it is possible to discover which parts are garbage by checking whether it is possible to decrease their refcount by one, and then checking which of the zvals have a refcount of zero.
To avoid having to call the checking of garbage cycles with every possible decrease of a refcount, the algorithm instead puts all possible roots (zvals) in the "root buffer" (marking them "purple"). It also makes sure that each possible garbage root ends up in the buffer only once. Only when the root buffer is full does the collection mechanism start for all the different zvals inside. See step A in the figure above.
In step B, the algorithm runs a depth-first search on all possible roots to decrease by one the refcounts of each zval it finds, making sure not to decrease a refcount on the same zval twice (by marking them as "grey"). In step C, the algorithm again runs a depth-first search from each root node, to check the refcount of each zval again. If it finds that the refcount is zero, the zval is marked "white" (blue in the figure). If it's larger than zero, it reverts the decreasing of the refcount by one with a depth-first search from that point on, and they are marked "black" again. In the last step (D), the algorithm walks over the root buffer removing the zval roots from there, and meanwhile, checks which zvals have been marked "white" in the previous step. Every zval marked as "white" will be freed.
Now that you have a basic understanding of how the algorithm works, we will look back at how this integrates with PHP. By default, PHP's garbage collector is turned on. There is, however, a php.ini setting that allows you to change this: zend.enable_gc.
When the garbage collector is turned on, the cycle-finding algorithm as described above is executed whenever the root buffer runs full. The root buffer has a fixed size of 10,000 possible roots (although you can alter this by changing the GC_ROOT_BUFFER_MAX_ENTRIES constant in Zend/zend_gc.c in the PHP source code, and re-compiling PHP). When the garbage collector is turned off, the cycle-finding algorithm will never run. However, possible roots will always be recorded in the root buffer, no matter whether the garbage collection mechanism has been activated with this configuration setting.
If the root buffer becomes full with possible roots while the garbage collection mechanism is turned off, further possible roots will simply not be recorded. Those possible roots that are not recorded will never be analyzed by the algorithm. If they were part of a circular reference cycle, they would never be cleaned up and would create a memory leak.
The reason why possible roots are recorded even if the mechanism has been disabled is because it's faster to record possible roots than to have to check whether the mechanism is turned on every time a possible root could be found. The garbage collection and analysis mechanism itself, however, can take a considerable amount of time.
Besides changing the zend.enable_gc configuration setting, it is also possible to turn the garbage collecting mechanism on and off by calling gc_enable() or gc_disable() respectively. Calling those functions has the same effect as turning on or off the mechanism with the configuration setting. It is also possible to force the collection of cycles even if the possible root buffer is not full yet. For this, you can use the gc_collect_cycles() function. This function will return how many cycles were collected by the algorithm.
The rationale behind the ability to turn the mechanism on and off, and to initiate cycle collection yourself, is that some parts of your application could be highly time-sensitive. In those cases, you might not want the garbage collection mechanism to kick in. Of course, by turning off the garbage collection for certain parts of your application, you do risk creating memory leaks because some possible roots might not fit into the limited root buffer. Therefore, it is probably wise to call gc_collect_cycles() just before you call gc_disable() to free up the memory that could be lost through possible roots that are already recorded in the root buffer. This then leaves an empty buffer so that there is more space for storing possible roots while the cycle collecting mechanism is turned off.
We have already mentioned in the previous section that simply collecting the possible roots had a very tiny performance impact, but this is when you compare PHP 5.2 against PHP 5.3. Although the recording of possible roots compared to not recording them at all, like in PHP 5.2, is slower, other changes to the PHP runtime in PHP 5.3 prevented this particular performance loss from even showing.
There are two major areas in which performance is affected. The first area is reduced memory usage, and the second area is run-time delay when the garbage collection mechanism performs its memory cleanups. We will look at both of those issues.
First of all, the whole reason for implementing the garbage collection mechanism is to reduce memory usage by cleaning up circular-referenced variables as soon as the prerequisites are fulfilled. In PHP's implementation, this happens as soon as the root-buffer is full, or when the function gc_collect_cycles() is called. In the graph below, we display the memory usage of the script below, in both PHP 5.2 and PHP 5.3, excluding the base memory that PHP itself uses when starting up.
Example #1 Memory usage example
<?php
class Foo
{
public $var = '3.1415962654';
}
$baseMemory = memory_get_usage();
for ( $i = 0; $i <= 100000; $i++ )
{
$a = new Foo;
$a->self = $a;
if ( $i % 500 === 0 )
{
echo sprintf( '%8d: ', $i ), memory_get_usage() - $baseMemory, "\n";
}
}
?>
In this very academic example, we are creating an object in which a property is set to point back to the object itself. When the $a variable in the script is re-assigned in the next iteration of the loop, a memory leak would typically occur. In this case, two zval-containers are leaked (the object zval, and the property zval), but only one possible root is found: the variable that was unset. When the root-buffer is full after 10,000 iterations (with a total of 10,000 possible roots), the garbage collection mechanism kicks in and frees the memory associated with those possible roots. This can very clearly be seen in the jagged memory-usage graph for PHP 5.3. After each 10,000 iterations, the mechanism kicks in and frees the memory associated with the circular referenced variables. The mechanism itself does not have to do a whole lot of work in this example, because the structure that is leaked is extremely simple. From the diagram, you see that the maximum memory usage in PHP 5.3 is about 9 Mb, whereas in PHP 5.2 the memory usage keeps increasing.
The second area where the garbage collection mechanism influences performance is the time taken when the garbage collection mechanism kicks in to free the "leaked" memory. In order to see how much this is, we slightly modify the previous script to allow for a larger number of iterations and the removal of the intermediate memory usage figures. The second script is here:
Example #2 GC performance influences
<?php
class Foo
{
public $var = '3.1415962654';
}
for ( $i = 0; $i <= 1000000; $i++ )
{
$a = new Foo;
$a->self = $a;
}
echo memory_get_peak_usage(), "\n";
?>
We will run this script two times, once with the zend.enable_gc setting turned on, and once with it turned off:
Example #3 Running the above script
time php -dzend.enable_gc=0 -dmemory_limit=-1 -n example2.php # and time php -dzend.enable_gc=1 -dmemory_limit=-1 -n example2.php
On my machine, the first command seems to take consistently about 10.7 seconds, whereas the second command takes about 11.4 seconds. This is a slowdown of about 7%. However, the maximum amount of memory used by the script is reduced by 98% from 931Mb to 10Mb. This benchmark is not very scientific, or even representative of real-life applications, but it does demonstrate the memory usage benefits that this garbage collection mechanism provides. The good thing is that the slowdown is always the same 7%, for this particular script, while the memory saving capabilities save more and more memory as more circular references are found during script execution.
It is possible to coax a little bit more information about how the garbage collection mechanism is run from within PHP. But in order to do so, you will have to re-compile PHP to enable the benchmark and data-collecting code. You will have to set the CFLAGS environment variable to -DGC_BENCH=1 prior to running ./configure with your desired options. The following sequence should do the trick:
Example #4 Recompiling PHP to enable GC benchmarking
export CFLAGS=-DGC_BENCH=1 ./config.nice make clean make
When you run the above example code again with the newly built PHP binary, you will see the following being shown after PHP has finished execution:
Example #5 GC statistics
GC Statistics
-------------
Runs: 110
Collected: 2072204
Root buffer length: 0
Root buffer peak: 10000
Possible Remove from Marked
Root Buffered buffer grey
-------- -------- ----------- ------
ZVAL 7175487 1491291 1241690 3611871
ZOBJ 28506264 1527980 677581 1025731
The most informative statistics are displayed in the first block. You can see here that the garbage collection mechanism ran 110 times, and in total, more than 2 million memory allocations were freed during those 110 runs. As soon as the garbage collection mechanism has run at least one time, the "Root buffer peak" is always 10000.
In general the garbage collector in PHP will only cause a slowdown when the cycle collecting algorithm actually runs, whereas in normal (smaller) scripts there should be no performance hit at all.
However, in the cases where the cycle collection mechanism does run for normal scripts, the memory reduction it will provide allows more of those scripts to run concurrently on your server, since not so much memory is used in total.
The benefits are most apparent for longer-running scripts, such as lengthy test suites or daemon scripts. Also, for » PHP-GTK applications that generally tend to run longer than scripts for the Web, the new mechanism should make quite a bit of a difference regarding memory leaks creeping in over time.
DTrace is an always-available, low overhead, tracing framework available on a number of platforms including Solaris, Mac OS X, Oracle Linux and BSD. DTrace can trace operating system behavior and user program execution. It can display argument values and be used to infer performance statistics. Probes are monitored by user created scripts written in the DTrace D scripting language. This allows efficient analysis of data points.
PHP probes that are not being actively monitored by a user's DTrace D script do not contain instrumented code so there is no performance degradation during normal application execution. Probes that are being monitored incur an overhead low enough to generally allow DTrace monitoring on live production systems.
PHP incorporates "User-level Statically Defined Tracing" (USDT) probes that are triggered at runtime. For example, when a D script is monitoring PHP's function-entry probe, then, every time a PHP script function is called, this probe is fired and the associated D script action code is executed. This action code could, for example, print probe arguments such as the source file location of the PHP function. Or the action could aggregate data such as the number of times each function is called.
Only the PHP USDT probes are described here. Refer to external general and operating system-specific DTrace literature to see how DTrace can be used to trace arbitrary functions, and how it can be used to trace operating system behavior. Note not all DTrace features are available in all DTrace implementations.
DTrace static probes are included in PHP 5.4. Prior to this they were available via a » PECL extension, which is now obsolete.
The static DTrace probes in PHP can alternatively be used with the SystemTap facility on some Linux distributions.
PHP can be configured with DTrace static probes on platforms that support DTrace Dynamic Tracing.
Refer to external platform specific documentation for enabling operating system DTrace support. For example, on Oracle Linux boot a UEK3 kernel and do:
# modprobe fasttrap
# chmod 666 /dev/dtrace/helper
Instead of using chmod, you could instead use an ACL package rule to limit device access to a specific user.
Build PHP with the --enable-dtrace configuration parameter:
# ./configure --enable-dtrace ...
# make
# make install
This enables the static probes in core PHP. Any PHP extensions that provide their own probes should be built separately as shared extensions.
| Probe Name | Probe Description | Probe Arguments |
|---|---|---|
| request-startup | Fires when a request starts. | char *file, char *request_uri, char *request_method |
| request-shutdown | Fires when a request shutdown. | char *file, char *request_uri, char *request_method |
| compile-file-entry | Fires when the compilation of a script starts. | char *compile_file, char *compile_file_translated |
| compile-file-return | Fires when the compilation of a script finishes. | char *compile_file, char *compile_file_translated |
| execute-entry | Fires when an opcode array is to be executed. For example, it fires on function calls, includes, and generator resumes. | char *request_file, int lineno |
| execute-return | Fires after execution of an opcode array. | char *request_file, int lineno |
| function-entry | Fires when the PHP engine enters a PHP function or method call. | char *function_name, char *request_file, int lineno, char *classname, char *scope |
| function-return | Fires when the PHP engine returns from a PHP function or method call. | char *function_name, char *request_file, int lineno, char *classname, char *scope |
| exception-thrown | Fires when an exception is thrown. | char *classname |
| exception-caught | Fires when an exception is caught. | char *classname |
| error | Fires when an error occurs, regardless of the error_reporting level. | char *errormsg, char *request_file, int lineno |
PHP extensions may also have additional static probes.
To list available probes, start a PHP process and then run:
# dtrace -l
The output will be similar to:
ID PROVIDER MODULE FUNCTION NAME
[ . . . ]
4 php15271 php dtrace_compile_file compile-file-entry
5 php15271 php dtrace_compile_file compile-file-return
6 php15271 php zend_error error
7 php15271 php ZEND_CATCH_SPEC_CONST_CV_HANDLER exception-caught
8 php15271 php zend_throw_exception_internal exception-thrown
9 php15271 php dtrace_execute_ex execute-entry
10 php15271 php dtrace_execute_internal execute-entry
11 php15271 php dtrace_execute_ex execute-return
12 php15271 php dtrace_execute_internal execute-return
13 php15271 php dtrace_execute_ex function-entry
14 php15271 php dtrace_execute_ex function-return
15 php15271 php php_request_shutdown request-shutdown
16 php15271 php php_request_startup request-startup
The Provider column values consist of php and the process id of the currently running PHP process.
If the Apache web server is running, the module name might be, for example, libphp5.so, and there would be multiple blocks of listings, one per running Apache process.
The Function column refers to PHP's internal C implementation function names where each provider is located.
If a PHP process is not running, then no PHP probes will be shown.
This example shows the basics of the DTrace D scripting language.
Example #1 all_probes.d for tracing all PHP Static Probes with DTrace
#!/usr/sbin/dtrace -Zs
#pragma D option quiet
php*:::compile-file-entry
{
printf("PHP compile-file-entry\n");
printf(" compile_file %s\n", copyinstr(arg0));
printf(" compile_file_translated %s\n", copyinstr(arg1));
}
php*:::compile-file-return
{
printf("PHP compile-file-return\n");
printf(" compile_file %s\n", copyinstr(arg0));
printf(" compile_file_translated %s\n", copyinstr(arg1));
}
php*:::error
{
printf("PHP error\n");
printf(" errormsg %s\n", copyinstr(arg0));
printf(" request_file %s\n", copyinstr(arg1));
printf(" lineno %d\n", (int)arg2);
}
php*:::exception-caught
{
printf("PHP exception-caught\n");
printf(" classname %s\n", copyinstr(arg0));
}
php*:::exception-thrown
{
printf("PHP exception-thrown\n");
printf(" classname %s\n", copyinstr(arg0));
}
php*:::execute-entry
{
printf("PHP execute-entry\n");
printf(" request_file %s\n", copyinstr(arg0));
printf(" lineno %d\n", (int)arg1);
}
php*:::execute-return
{
printf("PHP execute-return\n");
printf(" request_file %s\n", copyinstr(arg0));
printf(" lineno %d\n", (int)arg1);
}
php*:::function-entry
{
printf("PHP function-entry\n");
printf(" function_name %s\n", copyinstr(arg0));
printf(" request_file %s\n", copyinstr(arg1));
printf(" lineno %d\n", (int)arg2);
printf(" classname %s\n", copyinstr(arg3));
printf(" scope %s\n", copyinstr(arg4));
}
php*:::function-return
{
printf("PHP function-return\n");
printf(" function_name %s\n", copyinstr(arg0));
printf(" request_file %s\n", copyinstr(arg1));
printf(" lineno %d\n", (int)arg2);
printf(" classname %s\n", copyinstr(arg3));
printf(" scope %s\n", copyinstr(arg4));
}
php*:::request-shutdown
{
printf("PHP request-shutdown\n");
printf(" file %s\n", copyinstr(arg0));
printf(" request_uri %s\n", copyinstr(arg1));
printf(" request_method %s\n", copyinstr(arg2));
}
php*:::request-startup
{
printf("PHP request-startup\n");
printf(" file %s\n", copyinstr(arg0));
printf(" request_uri %s\n", copyinstr(arg1));
printf(" request_method %s\n", copyinstr(arg2));
}
This script uses the -Z option to dtrace, allowing it to be run when there is no PHP process executing. If this option were omitted the script would immediately terminate because it knows none of the probes to be monitored are in existence.
The script traces all core PHP static probe points throughout the duration of a running PHP script. Run the D script:
# ./all_probes.d
Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires.
When monitoring is complete, the D script can be terminated with a ^C.
On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps will help reduce confusion, for example:
php*:::function-entry
{
printf("%lld: PHP function-entry ", walltimestamp);
[ . . .]
}
On some Linux distributions, the SystemTap tracing utility can be used to trace PHP's static DTrace probes. This is available with PHP 5.4.20 and PHP 5.5.
Install the SystemTap SDT development package:
# yum install systemtap-sdt-devel
Install PHP with the DTrace probes enabled:
# ./configure --enable-dtrace ... # make
The static probes in PHP can be listed using stap:
# stap -l 'process.provider("php").mark("*")' -c 'sapi/cli/php -i'
This outputs:
process("sapi/cli/php").provider("php").mark("compile__file__entry")
process("sapi/cli/php").provider("php").mark("compile__file__return")
process("sapi/cli/php").provider("php").mark("error")
process("sapi/cli/php").provider("php").mark("exception__caught")
process("sapi/cli/php").provider("php").mark("exception__thrown")
process("sapi/cli/php").provider("php").mark("execute__entry")
process("sapi/cli/php").provider("php").mark("execute__return")
process("sapi/cli/php").provider("php").mark("function__entry")
process("sapi/cli/php").provider("php").mark("function__return")
process("sapi/cli/php").provider("php").mark("request__shutdown")
process("sapi/cli/php").provider("php").mark("request__startup")
Example #1 all_probes.stp for tracing all PHP Static Probes with SystemTap
probe process("sapi/cli/php").provider("php").mark("compile__file__entry") {
printf("Probe compile__file__entry\n");
printf(" compile_file %s\n", user_string($arg1));
printf(" compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("compile__file__return") {
printf("Probe compile__file__return\n");
printf(" compile_file %s\n", user_string($arg1));
printf(" compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("error") {
printf("Probe error\n");
printf(" errormsg %s\n", user_string($arg1));
printf(" request_file %s\n", user_string($arg2));
printf(" lineno %d\n", $arg3);
}
probe process("sapi/cli/php").provider("php").mark("exception__caught") {
printf("Probe exception__caught\n");
printf(" classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("exception__thrown") {
printf("Probe exception__thrown\n");
printf(" classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("execute__entry") {
printf("Probe execute__entry\n");
printf(" request_file %s\n", user_string($arg1));
printf(" lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("execute__return") {
printf("Probe execute__return\n");
printf(" request_file %s\n", user_string($arg1));
printf(" lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("function__entry") {
printf("Probe function__entry\n");
printf(" function_name %s\n", user_string($arg1));
printf(" request_file %s\n", user_string($arg2));
printf(" lineno %d\n", $arg3);
printf(" classname %s\n", user_string($arg4));
printf(" scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("function__return") {
printf("Probe function__return: %s\n", user_string($arg1));
printf(" function_name %s\n", user_string($arg1));
printf(" request_file %s\n", user_string($arg2));
printf(" lineno %d\n", $arg3);
printf(" classname %s\n", user_string($arg4));
printf(" scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("request__shutdown") {
printf("Probe request__shutdown\n");
printf(" file %s\n", user_string($arg1));
printf(" request_uri %s\n", user_string($arg2));
printf(" request_method %s\n", user_string($arg3));
}
probe process("sapi/cli/php").provider("php").mark("request__startup") {
printf("Probe request__startup\n");
printf(" file %s\n", user_string($arg1));
printf(" request_uri %s\n", user_string($arg2));
printf(" request_method %s\n", user_string($arg3));
}
The above script will trace all core PHP static probe points throughout the duration of a running PHP script:
# stap -c 'sapi/cli/php test.php' all_probes.stp
See also Extension List/Categorization.
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.
No external libraries are needed to build this extension.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/apc.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
Note: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks the TMP, TEMP and USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.
Note: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .
The behaviour of these functions is affected by settings in php.ini.
Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.
There are two primary decisions to be made configuring APC. First, how much memory is going to be allocated to APC; and second, whether APC will check if a file has been modified on every request. The two ini directives that control these settings are apc.shm_size and apc.stat, respectively. Read the sections on these two directive carefully below.
Once the server is running, the apc.php script that is bundled with the extension should be copied somewhere into the docroot and viewed with a browser as it provides a detailed analysis of the internal workings of APC. If GD is enabled in PHP, it will even display some interesting graphs. The first thing to ensure, of course, is that it is actually caching files. If APC is working, the Cache full count number (on the left) will display the number of times the cache has reached maximum capacity and has had to forcefully clean any entries that haven't been accessed in the last apc.ttl seconds. This number is minimized in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for APC. Barring that, the apc.filters ought to be used to cache fewer scripts.
When APC is compiled with mmap support (Memory Mapping), it will use only one memory segment, unlike when APC is built with SHM (SysV Shared Memory) support that uses multiple memory segments. MMAP does not have a maximum limit like SHM does in /proc/sys/kernel/shmmax. In general MMAP support is recommeded because it will reclaim the memory faster when the webserver is restarted and all in all reduces memory allocation impact at startup.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12. |
| apc.shm_segments | "1" | PHP_INI_SYSTEM | |
| apc.shm_size | "32M" | PHP_INI_SYSTEM | |
| apc.shm_strings_buffer | "4M" | PHP_INI_SYSTEM | Available since APC 3.1.4. |
| apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13. |
| apc.num_files_hint | "1000" | PHP_INI_SYSTEM | |
| apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
| apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
| apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
| apc.gc_ttl | "3600" | PHP_INI_SYSTEM | |
| apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0. |
| apc.filters | NULL | PHP_INI_SYSTEM | |
| apc.mmap_file_mask | NULL | PHP_INI_SYSTEM | |
| apc.slam_defense | "1" | PHP_INI_SYSTEM | Available since APC 3.0.0. Prior to APC 3.1.4, the default value was "0" (disabled). |
| apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6. |
| apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7. |
| apc.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7. |
| apc.use_request_time | "1" | PHP_INI_ALL | Available since APC 3.1.3. |
| apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10. |
| apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11. |
| apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11. |
| apc.serializer | "default" | PHP_INI_SYSTEM | Available since APC 3.1.0. |
| apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12. |
| apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13. |
| apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM | |
| apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM | |
| apc.rfc1867_freq | "0" | PHP_INI_SYSTEM | |
| apc.rfc1867_ttl | "3600" | PHP_INI_SYSTEM | Available since APC 3.1.1. |
| apc.localcache | "0" | PHP_INI_SYSTEM | Available in APC 3.0.14 - 3.1.11. |
| apc.localcache.size | "512" | PHP_INI_SYSTEM | vailable in APC 3.0.14 - 3.1.11. |
| apc.coredump_unmap | "0" | PHP_INI_SYSTEM | Available since APC 3.0.16. |
| apc.stat_ctime | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13. |
| apc.preload_path | NULL | PHP_INI_SYSTEM | Available since APC 3.1.1. |
| apc.file_md5 | "0" | PHP_INI_SYSTEM | Available since APC 3.1.1. |
| apc.canonicalize | "1" | PHP_INI_SYSTEM | Available since APC 3.1.1. |
| apc.lazy_functions | 0 | PHP_INI_SYSTEM | Available since APC 3.1.3. |
| apc.lazy_classes | 0 | PHP_INI_SYSTEM | Available since APC 3.1.3. |
Here's a short explanation of the configuration directives.
apc.enabled
boolean
apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).
apc.shm_segments
integer
The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.
apc.shm_size
integer
The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.
apc.shm_strings_buffer
string
The size of memory to use as a shared buffer for strings used internally by APC. Size Should be suffixed by M for megabytes, G for gigabytes. Enabling this option will reduce the amount of memory used per PHP-FPM worker as strings will be stored once rather than for each worker.
apc.optimization
integer
The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.
apc.num_files_hint
integer
A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if unsure; this setting is mainly useful for sites that have many thousands of source files.
apc.user_entries_hint
integer
Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.
apc.ttl
integer
The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.
apc.user_ttl
integer
The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.
apc.gc_ttl
integer
The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.
apc.cache_by_default
boolean
On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.
apc.filters
string
A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.
apc.mmap_file_mask
string
If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.
apc.slam_defense
integer
On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.
Deprecated by apc.write_lock.
apc.file_update_protection
integer
When a file is modified on a live web server it really ought to be done in an atomic manner. That is, written to a temporary file and renamed (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds, which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If all of the webserver's files are atomically updated, via some method like rsync (which updates correctly), this protection can be disabled by setting this directive to 0. If the system is flooded with i/o and some update procedures are taking longer than 2 seconds, this setting should be increased to enable the protection on those slower update operations.
apc.enable_cli
integer
Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.
apc.max_file_size
integer
Prevent files larger than this value from getting cached. Defaults to 1M.
apc.stat
integer
Be careful changing this setting. This defaults to on, forcing APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version. If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.
For included/required files this option applies as well, but note that for relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.
apc.write_lock
boolean
On busy servers, when the web server is first started, or when many files have been modified at the same time, APC may try to compile and cache the same file multiple times. Write_lock guarantees that only one process will attempt to compile and cache an uncached script. The other processes attempting to use the script will run without using the opcode cache, rather than locking and waiting for the cache to prime.
apc.report_autofilter
boolean
Logs any scripts that were automatically excluded from being cached due to early/late binding issues.
apc.serializer
string
Used to configure APC to use a third party serializer.
apc.include_once_override
boolean
Optimize include_once and require_once calls and avoid the expensive system calls used.
This feature is EXPERIMENTAL. The behaviour of this directive, its name, and surrounding documentation may change without notice in a future release of APC. This feature should be used at your own risk.
apc.rfc1867
boolean
RFC1867 File Upload Progress hook handler is only available if APC was compiled against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.
Note that the hidden field specified by APC_UPLOAD_PROGRESS must come before the file field, otherwise the upload progress will not work correctly.
Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.
Note that the rate is only available once all file transfers are completed.
Example #1 An apc.rfc1867 example
<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>
The above example will output something similar to:
Array
(
[total] => 1142543
[current] => 1142543
[rate] => 1828068.8
[filename] => test
[name] => file
[temp_filename] => /tmp/php8F
[cancel_upload] => 0
[done] => 1
)
apc.rfc1867_prefix
string
Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.
apc.rfc1867_name
string
Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.
apc.rfc1867_freq
string
The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with "k", "m", or "g" for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.
apc.rfc1867_ttl
integer
TTL for rfc1867 entries.
apc.localcache
boolean
This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.
apc.localcache.size
integer
The size of the local process shadow-cache, should be set to a sufficiently large value, approximately half of apc.num_files_hint.
apc.coredump_unmap
boolean
Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.
This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.
Note:
Although some kernels may provide a facility to ignore various types of shared memory when generating a core dump file, these implementations may also ignore important shared memory segments such as the Apache scoreboard.
apc.stat_ctime
integer
Verification with ctime will avoid problems caused by programs such as svn or rsync by making sure inodes haven't changed since the last stat. APC will normally only check mtime.
apc.canonicalize
bool
If on, then relative paths are canonicalized in no-stat mode. If set, then files included via stream wrappers can not be cached as realpath() does not support stream wrappers.
apc.preload_path
string
Optionally, set a path to the directory that APC will load cache data at startup.
apc.use_request_time
bool
Use the SAPI request start time for TTL.
apc.file_md5
bool
Records a md5 hash of files.
apc.lazy_functions
integer
Enables lazy loading for functions.
apc.lazy_classes
integer
Enables lazy loading for classes.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
APC_BIN_VERIFY_CRC32
(integer)
APC_BIN_VERIFY_MD5
(integer)
APC_ITER_ALL
(integer)
APC_ITER_ATIME
(integer)
APC_ITER_CTIME
(integer)
APC_ITER_DEVICE
(integer)
APC_ITER_DTIME
(integer)
APC_ITER_FILENAME
(integer)
APC_ITER_INODE
(integer)
APC_ITER_KEY
(integer)
APC_ITER_MD5
(integer)
APC_ITER_MEM_SIZE
(integer)
APC_ITER_MTIME
(integer)
APC_ITER_NONE
(integer)
APC_ITER_NUM_HITS
(integer)
APC_ITER_REFCOUNT
(integer)
APC_ITER_TTL
(integer)
APC_ITER_TYPE
(integer)
APC_ITER_VALUE
(integer)
APC_LIST_ACTIVE
(integer)
APC_LIST_DELETED
(integer)
(PECL apc >= 3.0.13)
apc_add — Cache a new variable in the data store
Caches a variable in the data store, only if it's not already stored.
Note: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).
key
Store the variable using this name. keys are
cache-unique, so attempting to use apc_add() to
store data with a key that already exists will not overwrite the
existing data, and will instead return FALSE. (This is the only
difference between apc_add() and
apc_store().)
varThe variable to store
ttl
Time To Live; store var in the cache for
ttl seconds. After the
ttl has passed, the stored variable will be
expunged from the cache (on the next request). If no ttl
is supplied (or if the ttl is
0), the value will persist until it is removed from
the cache manually, or otherwise fails to exist in the cache (clear,
restart, etc.).
valuesNames in key, variables in value.
Returns TRUE if something has effectively been added into the cache, FALSE otherwise. Second syntax returns array with error keys.
Example #1 A apc_add() example
<?php
$bar = 'BAR';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
?>
The above example will output:
string(3) "BAR" string(3) "BAR"
(PECL apc >= 3.1.4)
apc_bin_dump — Get a binary dump of the given files and user variables
$files = NULL
[, array $user_vars = NULL
]] )
Returns a binary dump of the given files and user variables from the APC cache.
A NULL for files or user_vars signals a dump of every entry, whereas array() will dump
nothing.
Returns a binary dump of the given files and user variables from the APC cache,
FALSE if APC is not enabled, or NULL if an unknown error is encountered.
(PECL apc >= 3.1.4)
apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file
$files
, array $user_vars
, string $filename
[, int $flags = 0
[, resource $context = NULL
]] )Outputs a binary dump of the given files and user variables from the APC cache to the named file.
filesThe file names being dumped.
user_varsThe user variables being dumped.
filenameThe filename where the dump is being saved.
flags
Flags passed to the filename stream. See the
file_put_contents() documentation for details.
context
The context passed to the filename stream. See the
file_put_contents() documentation for details.
The number of bytes written to the file, otherwise
FALSE if APC is not enabled, filename is an invalid file name,
filename can't be opened, the file dump can't be completed
(e.g., the hard drive is out of disk space), or an unknown error was encountered.
(PECL apc >= 3.1.4)
apc_bin_load — Load a binary dump into the APC file/user cache
$data
[, int $flags = 0
] )Loads the given binary dump into the APC file/user cache.
dataThe binary dump being loaded, likely from apc_bin_dump().
flags
Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5,
or both.
Returns TRUE if the binary dump data was loaded
with success, otherwise FALSE is returned. FALSE is returned if APC
is not enabled, or if the data is not a valid APC
binary dump (e.g., unexpected size).
Example #1 apc_bin_load() example
<?php
$data = apc_bin_dump(NULL, NULL);
apc_bin_load($data, APC_BIN_VERIFY_MD5 | APC_BIN_VERIFY_CRC32);
?>
(PECL apc >= 3.1.4)
apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache
$filename
[, resource $context = NULL
[, int $flags = 0
]] )Loads a binary dump from a file into the APC file/user cache.
filenameThe file name containing the dump, likely from apc_bin_dumpfile().
contextThe files context.
flags
Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5,
or both.
Returns TRUE on success, otherwise FALSE Reasons it may return FALSE include
APC is not enabled, filename is an invalid file name or empty,
filename can't be opened, the file dump can't be completed, or
if the data is not a valid APC binary dump (e.g., unexpected
size).
(PECL apc >= 2.0.0)
apc_cache_info — Retrieves cached information from APC's data store
$cache_type = ""
[, bool $limited = false
]] )Retrieves cached information and meta-data from APC's data store.
cache_type
If cache_type is "user",
information about the user cache will be returned.
If cache_type is "filehits",
information about which files have been served from the bytecode cache
for the current request will be returned. This feature must be enabled at
compile time using --enable-filehits
.
If an invalid or no cache_type is specified, information about
the system cache (cached files) will be returned.
limited
If limited is TRUE, the
return value will exclude the individual list of cache entries. This
is useful when trying to optimize calls for statistics gathering.
Array of cached data (and meta-data) or FALSE on failure
Note: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.
| Version | Description |
|---|---|
| 3.0.11 |
The limited parameter was introduced.
|
| 3.0.16 |
The "filehits" option for the
cache_type parameter was introduced.
|
Example #1 A apc_cache_info() example
<?php
print_r(apc_cache_info());
?>
The above example will output something similar to:
Array
(
[num_slots] => 2000
[ttl] => 0
[num_hits] => 9
[num_misses] => 3
[start_time] => 1123958803
[cache_list] => Array
(
[0] => Array
(
[filename] => /path/to/apc_test.php
[device] => 29954
[inode] => 1130511
[type] => file
[num_hits] => 1
[mtime] => 1123960686
[creation_time] => 1123960696
[deletion_time] => 0
[access_time] => 1123962864
[ref_count] => 1
[mem_size] => 677
)
[1] => Array (...iterates for each cached file)
)
(PECL apc >= 3.1.1)
apc_cas — Updates an old value with a new value
$key
, int $old
, int $new
)
apc_cas() updates an already existing integer value if the
old parameter matches the currently stored value
with the value of the new parameter.
keyThe key of the value being updated.
oldThe old value (the value currently stored).
newThe new value to update to.
Returns TRUE on success or FALSE on failure.
Example #1 apc_cas() example
<?php
apc_store('foobar', 2);
echo '$foobar = 2', PHP_EOL;
echo '$foobar == 1 ? 2 : 1 = ', (apc_cas('foobar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar == 2 ? 1 : 2 = ', (apc_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar = ', apc_fetch('foobar'), PHP_EOL;
echo '$f__bar == 1 ? 2 : 1 = ', (apc_cas('f__bar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
apc_store('perfection', 'xyz');
echo '$perfection == 2 ? 1 : 2 = ', (apc_cas('perfection', 2, 1) ? 'ok' : 'epic fail'), PHP_EOL;
echo '$foobar = ', apc_fetch('foobar'), PHP_EOL;
?>
The above example will output something similar to:
$foobar = 2 $foobar == 1 ? 2 : 1 = fail $foobar == 2 ? 1 : 2 = ok $foobar = 1 $f__bar == 1 ? 2 : 1 = fail $perfection == 2 ? 1 : 2 = epic fail $foobar = 1
(PECL apc >= 2.0.0)
apc_clear_cache — Clears the APC cache
$cache_type = ""
] )Clears the user/system cache.
cache_type
If cache_type is "user", the
user cache will be cleared; otherwise, the system cache (cached files)
will be cleared.
Returns TRUE always
(PECL apc >= 3.0.13)
apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
Stores a file in the bytecode cache, bypassing all filters.
filenameFull or relative path to a PHP file that will be compiled and stored in the bytecode cache.
Returns TRUE on success or FALSE on failure.
(PECL apc >= 3.1.1)
apc_dec — Decrease a stored number
$key
[, int $step = 1
[, bool &$success
]] )Decreases a stored integer value.
keyThe key of the value being decreased.
stepThe step, or value to decrease.
successOptionally pass the success or fail boolean value to this referenced variable.
Returns the current value of key's value on success,
or FALSE on failure
Example #1 apc_dec() example
<?php
echo "Let's do something with success", PHP_EOL;
apc_store('anumber', 42);
echo apc_fetch('anumber'), PHP_EOL;
echo apc_dec('anumber'), PHP_EOL;
echo apc_dec('anumber', 10), PHP_EOL;
echo apc_dec('anumber', 10, $success), PHP_EOL;
var_dump($success);
echo "Now, let's fail", PHP_EOL, PHP_EOL;
apc_store('astring', 'foo');
$ret = apc_dec('astring', 1, $fail);
var_dump($ret);
var_dump($fail);
?>
The above example will output something similar to:
Let's do something with success 42 41 31 21 bool(true) Now, let's fail bool(false) bool(false)
(PECL apc >= 3.0.0)
apc_define_constants — Defines a set of constants for retrieval and mass-definition
$key
, array $constants
[, bool $case_sensitive = true
] )define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.
For a better-performing solution, try the » hidef extension from PECL.
Note: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the
constantsparameter, effectively clearing the stored value(s).
key
The key serves as the name of the constant set
being stored. This key is used to retrieve the
stored constants in apc_load_constants().
constantsAn associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.
case_sensitive
The default behaviour for constants is to be declared case-sensitive;
i.e. CONSTANT and Constant
represent different values. If this parameter evaluates to FALSE the
constants will be declared as case-insensitive symbols.
Returns TRUE on success or FALSE on failure.
Example #1 apc_define_constants() example
<?php
$constants = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>
The above example will output:
123
(PECL apc >= 3.1.1)
apc_delete_file — Deletes files from the opcode cache
keysThe files to be deleted. Accepts a string, array of strings, or an APCIterator object.
Returns TRUE on success or FALSE on failure.
Or if keys is an array, then
an empty array is returned on success, or an array of failed files
is returned.
Example #1 apc_delete_file() example
<?php
$filename = 'file.php';
if (apc_compile_file($filename)) {
if (apc_delete_file($filename)) {
echo "Successfully deleted file $filename from APC cache.", PHP_EOL;
}
}
if (apc_compile_file($filename)) {
if ($good = apc_delete_file(array($filename, 'donotexist.php'))) {
var_dump($good);
}
}
$bad = apc_delete_file('donotexist.php');
var_dump($bad);
?>
The above example will output something similar to:
Successfully deleted file file.php from APC cache.
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 13.
array(1) {
[0]=>
string(14) "donotexist.php"
}
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 18.
bool(false)
(PECL apc >= 3.0.0)
apc_delete — Removes a stored variable from the cache
Returns TRUE on success or FALSE on failure.
Example #1 A apc_delete() example
<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?>
(PECL apc >= 3.1.4)
apc_exists — Checks if APC key exists
Returns TRUE if the key exists, otherwise FALSE Or if an
array was passed to keys, then
an array is returned that contains all existing keys, or an empty
array if none exist.
Example #1 apc_exists() example
<?php
$fruit = 'apple';
$veggie = 'carrot';
apc_store('foo', $fruit);
apc_store('bar', $veggie);
if (apc_exists('foo')) {
echo "Foo exists: ";
echo apc_fetch('foo');
} else {
echo "Foo does not exist";
}
echo PHP_EOL;
if (apc_exists('baz')) {
echo "Baz exists.";
} else {
echo "Baz does not exist";
}
echo PHP_EOL;
$ret = apc_exists(array('foo', 'donotexist', 'bar'));
var_dump($ret);
?>
The above example will output something similar to:
Foo exists: apple
Baz does not exist
array(2) {
["foo"]=>
bool(true)
["bar"]=>
bool(true)
}
(PECL apc >= 3.0.0)
apc_fetch — Fetch a stored variable from the cache
Fetchs a stored variable from the cache.
key
The key used to store the value (with
apc_store()). If an array is passed then each
element is fetched and returned.
success
Set to TRUE in success and FALSE in failure.
The stored variable or array of variables on success; FALSE on failure
Example #1 A apc_fetch() example
<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>
The above example will output:
string(3) "BAR"
| Version | Description |
|---|---|
| 3.0.17 |
The success parameter was added.
|
(PECL apc >= 3.1.1)
apc_inc — Increase a stored number
$key
[, int $step = 1
[, bool &$success
]] )Increases a stored number.
keyThe key of the value being increased.
stepThe step, or value to increase.
successOptionally pass the success or fail boolean value to this referenced variable.
Returns the current value of key's value on success,
or FALSE on failure
Example #1 apc_inc() example
<?php
echo "Let's do something with success", PHP_EOL;
apc_store('anumber', 42);
echo apc_fetch('anumber'), PHP_EOL;
echo apc_inc('anumber'), PHP_EOL;
echo apc_inc('anumber', 10), PHP_EOL;
echo apc_inc('anumber', 10, $success), PHP_EOL;
var_dump($success);
echo "Now, let's fail", PHP_EOL, PHP_EOL;
apc_store('astring', 'foo');
$ret = apc_inc('astring', 1, $fail);
var_dump($ret);
var_dump($fail);
?>
The above example will output something similar to:
42 43 53 63 bool(true) Now, let's fail bool(false) bool(false)
(PECL apc >= 3.0.0)
apc_load_constants — Loads a set of constants from the cache
$key
[, bool $case_sensitive = true
] )Loads a set of constants from the cache.
keyThe name of the constant set (that was stored with apc_define_constants()) to be retrieved.
case_sensitive
The default behaviour for constants is to be declared case-sensitive;
i.e. CONSTANT and Constant
represent different values. If this parameter evaluates to FALSE the
constants will be declared as case-insensitive symbols.
Returns TRUE on success or FALSE on failure.
Example #1 apc_load_constants() example
<?php
$constants = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>
The above example will output:
123
(PECL apc >= 2.0.0)
apc_sma_info — Retrieves APC's Shared Memory Allocation information
$limited = false
] )Retrieves APC's Shared Memory Allocation information.
limited
When set to FALSE (default) apc_sma_info() will
return a detailed information about each segment.
Array of Shared Memory Allocation data; FALSE on failure.
Example #1 A apc_sma_info() example
<?php
print_r(apc_sma_info());
?>
The above example will output something similar to:
Array
(
[num_seg] => 1
[seg_size] => 31457280
[avail_mem] => 31448408
[block_lists] => Array
(
[0] => Array
(
[0] => Array
(
[size] => 31448408
[offset] => 8864
)
)
)
)
(PECL apc >= 3.0.0)
apc_store — Cache a variable in the data store
Cache a variable in the data store.
Note: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).
key
Store the variable using this name. keys are
cache-unique, so storing a second value with the same
key will overwrite the original value.
varThe variable to store
ttl
Time To Live; store var in the cache for
ttl seconds. After the
ttl has passed, the stored variable will be
expunged from the cache (on the next request). If no ttl
is supplied (or if the ttl is
0), the value will persist until it is removed from
the cache manually, or otherwise fails to exist in the cache (clear,
restart, etc.).
valuesNames in key, variables in value.
Returns TRUE on success or FALSE on failure.
Second syntax returns array with error keys.
Example #1 A apc_store() example
<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>
The above example will output:
string(3) "BAR"
(PECL apc >= 3.1.1)
The APCIterator class makes it easier to iterate over large APC caches. This is helpful as it allows iterating over large caches in steps, while grabbing a defined number of entries per lock instance, so it frees the cache locks for other activities rather than hold up the entire cache to grab 100 (the default) entries. Also, using regular expression matching is more efficient as it's been moved to the C level.
$cache
[, mixed $search = null
[, int $format = APC_ITER_ALL
[, int $chunk_size = 100
[, int $list = APC_LIST_ACTIVE
]]]] )(PECL apc >= 3.1.1)
APCIterator::__construct — Constructs an APCIterator iterator object
$cache
[, mixed $search = null
[, int $format = APC_ITER_ALL
[, int $chunk_size = 100
[, int $list = APC_LIST_ACTIVE
]]]] )Constructs an APCIterator object.
cacheThe cache type, which will be user or file.
search
A PCRE regular expression that
matches against APC key names, either as a string for
a single regular expression, or as an array of regular
expressions. Or, optionally pass in NULL to skip the search.
formatThe desired format, as configured with one or more of the APC_ITER_* constants.
chunk_sizeThe chunk size. Must be a value greater than 0. The default value is 100.
list
The type to list. Either pass in APC_LIST_ACTIVE
or APC_LIST_DELETED.
An APCIterator object on success,
or NULL on failure.
Example #1 A APCIterator::__construct() example
<?php
foreach (new APCIterator('user', '/^counter\./') as $counter) {
echo "$counter[key]: $counter[value]\n";
apc_dec($counter['key'], $counter['value']);
}
?>
(PECL apc >= 3.1.1)
APCIterator::current — Get current item
Gets the current item from the APCIterator stack.
This function has no parameters.
Returns the current item on success, or FALSE if no
more items or exist, or on failure.
(PECL apc >= 3.1.1)
APCIterator::getTotalCount — Get total count
Get the total count.
This function is currently not documented; only its argument list is available.
This function has no parameters.
The total count.
(PECL apc >= 3.1.1)
APCIterator::getTotalHits — Get total cache hits
Gets the total number of cache hits.
This function is currently not documented; only its argument list is available.
This function has no parameters.
The number of hits on success, or FALSE on failure.
(PECL apc >= 3.1.1)
APCIterator::getTotalSize — Get total cache size
Gets the total cache size.
This function is currently not documented; only its argument list is available.
This function has no parameters.
The total cache size.
(PECL apc >= 3.1.1)
APCIterator::key — Get iterator key
Gets the current iterator key.
This function has no parameters.
Returns the key on success, or FALSE upon failure.
(PECL apc >= 3.1.1)
APCIterator::next — Move pointer to next item
Moves the iterator pointer to the next element.
This function has no parameters.
Returns TRUE on success or FALSE on failure.
(PECL apc >= 3.1.1)
APCIterator::rewind — Rewinds iterator
Rewinds back the iterator to the first element.
This function has no parameters.
No value is returned.
(PECL apc >= 3.1.1)
APCIterator::valid — Checks if current position is valid
Checks if the current iterator position is valid.
This function has no parameters.
Returns TRUE if the current iterator position is valid, otherwise FALSE.
APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.
APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer).
No external libraries are needed to build this extension.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/apd.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
In your INI file, add the following lines:
zend_extension = /absolute/path/to/apd.so apd.dumpdir = /absolute/path/to/trace/directory apd.statement_tracing = 0
Depending on your PHP build, the zend_extension directive can be one of the following:
zend_extension (non ZTS, non debug build) zend_extension_ts ( ZTS, non debug build) zend_extension_debug (non ZTS, debug build) zend_extension_debug_ts ( ZTS, debug build)
To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apd.dumpdir | NULL | PHP_INI_ALL | |
| apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9. |
Here's a short explanation of the configuration directives.
apd.dumpdir
string
Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.
You can specify a different directory as an argument to apd_set_pprof_trace().
apd.statement_tracing
boolean
Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
| Constant | Value | Description |
|---|---|---|
FUNCTION_TRACE
(integer)
|
1 | |
ARGS_TRACE
(integer)
|
2 | |
ASSIGNMENT_TRACE
(integer)
|
4 | |
STATEMENT_TRACE
(integer)
|
8 | |
MEMORY_TRACE
(integer)
|
16 | |
TIMING_TRACE
(integer)
|
32 | |
SUMMARY_TRACE
(integer)
|
64 | |
ERROR_TRACE
(integer)
|
128 | |
PROF_TRACE
(integer)
|
256 | |
APD_VERSION
(string)
|
example: 1.0.2-dev |
As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:
<?php
apd_set_pprof_trace();
?>
You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.
Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.
If you're running the CGI version of PHP, you will need to add the '-e'
flag to enable extended information for apd to work properly. For
example:
php -e -f script.php
To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:
bash-2.05b$ pprofp -R /tmp/pprof.22141.0 Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace
The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.
To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to » apd@mail.communityconnect.com. Any help is very welcome.
(PECL apd >= 0.2)
apd_breakpoint — Stops the interpreter and waits on a CR from the socket
$debug_level
)This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended
to use MEMORY_TRACE. It is very slow and does not appear to be accurate.
ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
Returns TRUE on success or FALSE on failure.
Example #1 Typical session using tcplisten
bash#tcplisten localhost 7777
APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
( 0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test.
php:5
( 0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes
t.php:5 returned. Elapsed (0.074824)
( 0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned. Elapsed (
-2089521468.1073275368)
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC: apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);
(PECL apd 0.2-0.4)
apd_callstack — Returns the current call stack as an array
Returns the current call stack as an array
An array containing the current call stack.
Example #1 apd_callstack() example
<?php
print_r(apd_callstack());
?>
(PECL apd 0.2-0.4)
apd_clunk — Throw a warning and a callstack
$warning
[, string $delimiter = "<BR />"
] )Behaves like perl's Carp::cluck. Throw a warning and a callstack.
warningThe warning to throw.
delimiterThe delimiter. Default to <BR />.
No value is returned.
Example #1 apd_clunk() example
<?php
apd_clunk("Some Warning", "<br/>");
?>
(PECL apd >= 0.2)
apd_continue — Restarts the interpreter
$debug_level
)Usually sent via the socket to restart the interpreter.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended
to use MEMORY_TRACE. It is very slow and does not appear to be accurate.
ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
Returns TRUE on success or FALSE on failure.
Example #1 apd_continue() example
<?php
apd_continue(0);
?>
(PECL apd 0.2-0.4)
apd_croak — Throw an error, a callstack and then exit
$warning
[, string $delimiter = "<BR />"
] )Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.
warningThe warning to throw.
delimiterThe delimiter. Default to <BR />.
No value is returned.
Example #1 apd_croak() example
<?php
apd_croak("Some Warning","<P>");
?>
(Unknown)
apd_dump_function_table — Outputs the current function table
Outputs the current function table.
No value is returned.
Example #1 apd_dump_function_table() example
<?php
apd_dump_function_table();
?>
(PECL apd 0.2-0.4)
apd_dump_persistent_resources — Return all persistent resources as an array
Return all persistent resources as an array.
An array containing the current call stack.
Example #1 apd_dump_persistent_resources() example
<?php
print_r(apd_dump_persistent_resources());
?>
(PECL apd 0.2-0.4)
apd_dump_regular_resources — Return all current regular resources as an array
Return all current regular resources as an array.
An array containing the current regular resources.
Example #1 apd_dump_regular_resources() example
<?php
print_r(apd_dump_regular_resources());
?>
(PECL apd >= 0.2)
apd_echo — Echo to the debugging socket
$output
)Usually sent via the socket to request information about the running script.
outputThe debugged variable.
Returns TRUE on success or FALSE on failure.
Example #1 apd_echo() example
<?php
apd_echo($i);
?>
(PECL apd 0.2)
apd_get_active_symbols — Get an array of the current variables names in the local scope
Returns the names of all the variables defined in the active scope, (not their values).
A multidimensional array with all the variables.
Example #1 apd_get_active_symbols() example
<?php
apd_echo(apd_get_active_symbols());
?>
(PECL apd >= 0.2)
apd_set_pprof_trace — Starts the session debugging
$dump_directory = ini_get("apd.dumpdir")
[, string $fragment = "pprof"
]] )Starts debugging to pprof_{process_id} in the dump directory.
dump_directoryThe directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.
fragment
Returns path of the destination file.
Example #1 apd_set_pprof_trace() example
<?php
apd_set_pprof_trace();
?>
(PECL apd >= 0.2)
apd_set_session_trace_socket — Starts the remote session debugging
$tcp_server
, int $socket_type
, int $port
, int $debug_level
)
Connects to the specified tcp_server (eg. tcplisten)
and sends debugging data to the socket.
tcp_serverIP or Unix Domain socket (like a file) of the TCP server.
socket_type
Can be AF_UNIX for file based sockets or
APD_AF_INET for standard tcp/ip.
portYou can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended
to use MEMORY_TRACE. It is very slow and does not appear to be accurate.
ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
Returns TRUE on success or FALSE on failure.
Example #1 apd_set_session_trace_socket() example
<?php
apd_set_session_trace_socket("127.0.0.1",APD_AF_INET,7112,0);
?>
(PECL apd 0.2-0.4)
apd_set_session_trace — Starts the session debugging
$debug_level
[, string $dump_directory = ini_get("apd.dumpdir")
] )Starts debugging to apd_dump_{process_id} in the dump directory.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended
to use MEMORY_TRACE. It is very slow and does not appear to be accurate.
ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
dump_directoryThe directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.
No value is returned.
Example #1 apd_set_session_trace() example
<?php
apd_set_session_trace(99);
?>
(PECL apd 0.2-0.4)
apd_set_session — Changes or sets the current debugging level
$debug_level
)This can be used to increase or decrease debugging in a different area of your application.
debug_levelAn integer which is formed by adding together the XXX_TRACE constants.
It is not recommended
to use MEMORY_TRACE. It is very slow and does not appear to be accurate.
ASSIGNMENT_TRACE is not implemented yet.
To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
No value is returned.
Example #1 apd_set_session() example
<?php
apd_set_session(9);
?>
(PECL apd >= 0.2)
override_function — Overrides built-in functions
$function_name
, string $function_args
, string $function_code
)Overrides built-in functions by replacing them in the symbol table.
function_nameThe function to override.
function_argsThe function arguments, as a comma separated string.
Usually you will want to pass this parameter, as well as the
function_code parameter, as a single quote
delimited string. The reason for using single quoted strings, is to
protect the variable names from parsing, otherwise, if you use double
quotes there will be a need to escape the variable names, e.g.
\$your_var.
function_codeThe new code for the function.
Returns TRUE on success or FALSE on failure.
Example #1 override_function() example
<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>
(PECL apd >= 0.2)
rename_function — Renames orig_name to new_name in the global function table
$original_name
, string $new_name
)Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.
original_nameThe original function name.
new_name
The new name for the original_name function.
Returns TRUE on success or FALSE on failure.
Example #1 rename_function() example
<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>
This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.
Bcompiler was written for several reasons:
The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.
To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.
bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...
In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.
No external libraries are needed to build this extension.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/bcompiler.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
This extension has no constants defined.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at » alan_k@php.net. Any help is very welcome.
(PECL bcompiler >= 0.4)
bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
$filename
)Reads data from a bcompiler exe file and creates classes from the bytecodes.
filenameThe exe file path, as a string.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_load_exe() example
<?php
bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
(PECL bcompiler >= 0.4)
bcompiler_load — Reads and creates classes from a bz compressed file
$filename
)Reads data from a bzcompressed file and creates classes from the bytecodes.
filenameThe bzcompressed file path, as a string.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_load() example
<?php
bcompiler_load("/tmp/example");
print_r(get_defined_classes());
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Note:
Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.
(PECL bcompiler >= 0.4)
bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
$class
, string $callback
)Reads the bytecodes of a class and calls back to a user function.
classThe class name, as a string.
callback
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_parse_class() example
<?php
function readByteCodes($data) {
print_r($data);
}
bcompiler_parse_class("DB","readByteCodes");
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Note:
This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.
(PECL bcompiler >= 0.4)
bcompiler_read — Reads and creates classes from a filehandle
$filehandle
)Reads data from a open file handle and creates classes from the bytecodes.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_read() example
<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Note:
Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.
(PECL bcompiler >= 0.4)
bcompiler_write_class — Writes a defined class as bytecodes
$filehandle
, string $className
[, string $extends
] )Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.
filehandleA file handle as returned by fopen().
classNameThe class name, as a string.
extends
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_write_class() example
<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Note:
This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.
(PECL bcompiler >= 0.5)
bcompiler_write_constant — Writes a defined constant as bytecodes
$filehandle
, string $constantName
)Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.
filehandleA file handle as returned by fopen().
constantNameThe name of the defined constant, as a string.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_write_constant() example
<?php
define("MODULE_MAX", 30);
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
(PECL bcompiler >= 0.6)
bcompiler_write_file — Writes a php source file as bytecodes
$filehandle
, string $filename
)This function complies specified source file into bytecodes, and writes them to the open file handle.
filehandleA file handle as returned by fopen().
filenameThe source file path, as a string.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_write_file() example
<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
and
include "example.phb";
*/
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
(PECL bcompiler >= 0.5)
bcompiler_write_function — Writes a defined function as bytecodes
$filehandle
, string $functionName
)Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).
filehandleA file handle as returned by fopen().
functionNameThe function name, as a string.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_write_function() example
<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
(PECL bcompiler >= 0.5)
bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
$filehandle
, string $fileName
)Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.
filehandleA file handle as returned by fopen().
fileNameThe file to be compiled. You must always include or require the file you intend to compile.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_write_functions_from_file() example
<?php
require('module.php');
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
(PECL bcompiler >= 0.3)
bcompiler_write_header — Writes the bcompiler header
$filehandle
[, string $write_ver
] )Writes the header part of a bcompiler file.
filehandleA file handle as returned by fopen().
write_verCan be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.
Returns TRUE on success or FALSE on failure.
Example #1 bcompiler_write_header() example
<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);
?>
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
(PECL bcompiler >= 0.5)
bcompiler_write_included_filename — Writes an included file as bytecodes
$filehandle
, string $filename
)This function is currently not documented; only its argument list is available.
Returns TRUE on success or FALSE on failure.
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.
BLENC is a PHP source script protector that:
BLENC is an extension which hooks into the Zend Engine, allowing for transparent encryption and execution of PHP scripts using the blowfish algorithm. It is not designed for complete security (it is still possible to disassemble the script into op codes using a package such as XDebug), however it does keep people out of your code and make reverse engineering difficult.
In order to protect your PHP script you must encrypt each script with blenc_encrypt() function. After you can include the encoded script like the example below:
<?php
/* PHP script encoded with BLENC */
$my_source_encoded = 'my_source_encoded.phpe';
include($my_source_encoded);
?>
BLENC supports also expiration time for the module. So, if you want deploy your source code with a expiration time, you have to compile the extension modifying the header file related to encryption and expiration time. Please see configuration section for further informations.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/blenc
It's strongly recommended to install BLENC from sources without 'pecl' command. In this way you can:
Please read the content of blenc_protect.h in sources of BLENC to know how set these hardcoded options.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| blenc.key_file | /usr/local/etc/blenckeys | PHP_INI_ALL |
Here's a short explanation of the configuration directives.
blenc.key_file
string
It's the location where BLENC can find the file containing a list of available decryption keys. This file must be readable by webserver.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
BLENC_EXT_VERSION
(string)
(PECL blenc >= 5)
blenc_encrypt — Encrypt a PHP script with BLENC.
$plaintext
, string $encodedfile
[, string $encryption_key
] )Encrypt the plaintext content and write it into encodedfile
plaintext
A source code to encrypt. Does not need to contain opening/closing PHP tags
encodedfile
The filename where BLENC will save the encoded source.
encryption_key
The key that BLENC will use to encrypt plaintext content. If not given BLENC will create a valid key.
BLENC will return the redistributable key that must be saved into key_file: the path of key_file is specified at runtime with the option blenc.key_file
Example #1 blenc_encrypt() example
<?php
/* read the PHP source code */
$source_code = file_get_contents("my_source_to_protect.php");
/* create the encrypted version */
$redistributable_key = blenc_encrypt($source_code, "my_source_encoded.php");
/* read which is the key_file */
$key_file = ini_get('blenc.key_file');
/* save the redistributable key */
file_put_contents($key_file, $redistributable_key, FILE_APPEND);
?>
These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.
With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.
The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.
No external libraries are needed to build this extension.
There is no installation needed to use these functions; they are part of the PHP core.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| error_reporting | NULL | PHP_INI_ALL | |
| display_errors | "1" | PHP_INI_ALL | |
| display_startup_errors | "0" | PHP_INI_ALL | |
| log_errors | "0" | PHP_INI_ALL | |
| log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_errors | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_source | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0. |
| track_errors | "0" | PHP_INI_ALL | |
| html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. |
| xmlrpc_errors | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0. |
| xmlrpc_error_number | "0" | PHP_INI_ALL | Available since PHP 4.1.0. |
| docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0. |
| docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2. |
| error_prepend_string | NULL | PHP_INI_ALL | |
| error_append_string | NULL | PHP_INI_ALL | |
| error_log | NULL | PHP_INI_ALL |
Here's a short explanation of the configuration directives.
error_reporting
integer
Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.
PHP 5.3 or later, the default value
is E_ALL &
~E_NOTICE &
~E_STRICT &
~E_DEPRECATED. This setting does not
show E_NOTICE, E_STRICT
and E_DEPRECATED level errors. You may want
to show them during development.
Prior to PHP 5.3.0, the default value
is E_ALL &
~E_NOTICE &
~E_STRICT.
In PHP 4 the default value is E_ALL
& ~E_NOTICE.
Note:
Enabling
E_NOTICEduring development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.
Note:
In PHP 5 a new error level
E_STRICTis available. Prior to PHP 5.4.0E_STRICTwas not included withinE_ALL, so you would have to explicitly enable this kind of error level in PHP < 5.4.0. EnablingE_STRICTduring development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issueE_STRICTerrors such as assigning objects by reference upon instantiation.
Note: PHP Constants outside of PHP
Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for
E_ALL) will likely change. So in place ofE_ALLconsider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not justE_ALL).
display_errors
string
This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.
Value "stderr" sends the errors to stderr instead of stdout. The value is available as of PHP 5.2.4. In earlier versions, this directive was of type boolean.
Note:
This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).
Note:
Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
display_startup_errors
boolean
Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.
log_errors
boolean
Tells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.
Note:
You're strongly advised to use error logging in place of error displaying on production web sites.
log_errors_max_len
integer
Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.
When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.ignore_repeated_errors
boolean
Do not log repeated messages. Repeated errors must occur in the same file on the same line unless ignore_repeated_source is set true.
ignore_repeated_source
boolean
Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.
report_memleaks
boolean
If this parameter is set to On (the default), this parameter will show a
report of memory leaks detected by the Zend memory manager. This report
will be send to stderr on Posix platforms. On Windows, it will be send
to the debugger using OutputDebugString(), and can be viewed with tools
like » DbgView.
This parameter only has effect in a debug build, and if
error_reporting includes E_WARNING in the allowed
list.
track_errors
boolean
If enabled, the last error message will always be present in the variable $php_errormsg.
html_errors
boolean
Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.
xmlrpc_errors
boolean
Turns off normal error reporting and formats errors as XML-RPC error message.
xmlrpc_error_number
integer
Used as the value of the XML-RPC faultCode element.
docref_root
string
The new error format contains a reference to a page describing the error or
function causing the error. In case of manual pages you can download the
manual in your language and set this ini directive to the URL of your local
copy. If your local copy of the manual can be reached by "/manual/"
you can simply use docref_root=/manual/. Additional you have
to set docref_ext to match the fileextensions of your copy
docref_ext=.html. It is possible to use external
references. For example you can use
docref_root=http://manual/en/ or
docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon
&url=http%3A%2F%2Fwww.php.net%2F"
Most of the time you want the docref_root value to end with a slash "/". But see the second example above which does not have nor need it.
Note:
This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).
docref_ext
string
See docref_root.
Note:
The value of docref_ext must begin with a dot ".".
error_prepend_string
string
String to output before an error message.
error_append_string
string
String to output after an error message.
error_log
string
Name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog(). If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI. See also error_log().
This extension has no resource types defined.
The constants below are always available as part of the PHP core.
Note: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.
| Value | Constant | Description | Note |
|---|---|---|---|
| 1 |
E_ERROR
(integer)
|
Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. | |
| 2 |
E_WARNING
(integer)
|
Run-time warnings (non-fatal errors). Execution of the script is not halted. | |
| 4 |
E_PARSE
(integer)
|
Compile-time parse errors. Parse errors should only be generated by the parser. | |
| 8 |
E_NOTICE
(integer)
|
Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. | |
| 16 |
E_CORE_ERROR
(integer)
|
Fatal errors that occur during PHP's initial startup. This is like an
E_ERROR, except it is generated by the core of PHP.
|
|
| 32 |
E_CORE_WARNING
(integer)
|
Warnings (non-fatal errors) that occur during PHP's initial startup.
This is like an E_WARNING, except it is generated
by the core of PHP.
|
|
| 64 |
E_COMPILE_ERROR
(integer)
|
Fatal compile-time errors. This is like an E_ERROR,
except it is generated by the Zend Scripting Engine.
|
|
| 128 |
E_COMPILE_WARNING
(integer)
|
Compile-time warnings (non-fatal errors). This is like an
E_WARNING, except it is generated by the Zend
Scripting Engine.
|
|
| 256 |
E_USER_ERROR
(integer)
|
User-generated error message. This is like an
E_ERROR, except it is generated in PHP code by
using the PHP function trigger_error().
|
|
| 512 |
E_USER_WARNING
(integer)
|
User-generated warning message. This is like an
E_WARNING, except it is generated in PHP code by
using the PHP function trigger_error().
|
|
| 1024 |
E_USER_NOTICE
(integer)
|
User-generated notice message. This is like an
E_NOTICE, except it is generated in PHP code by
using the PHP function trigger_error().
|
|
| 2048 |
E_STRICT
(integer)
|
Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | Since PHP 5 but not included in E_ALL until PHP 5.4.0 |
| 4096 |
E_RECOVERABLE_ERROR
(integer)
|
Catchable fatal error. It indicates that a probably dangerous error
occurred, but did not leave the Engine in an unstable state. If the error
is not caught by a user defined handle (see also
set_error_handler()), the application aborts as it
was an E_ERROR.
|
Since PHP 5.2.0 |
| 8192 |
E_DEPRECATED
(integer)
|
Run-time notices. Enable this to receive warnings about code that will not work in future versions. | Since PHP 5.3.0 |
| 16384 |
E_USER_DEPRECATED
(integer)
|
User-generated warning message. This is like an
E_DEPRECATED, except it is generated in PHP code by
using the PHP function trigger_error().
|
Since PHP 5.3.0 |
| 32767 |
E_ALL
(integer)
|
All errors and warnings, as supported, except of level
E_STRICT prior to PHP 5.4.0.
|
32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously |
The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini.
Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer if a critical error in the logic happens.
Example #1 Using error handling in a script
<?php
// we will do our own error handling
error_reporting(0);
// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
// timestamp for the error entry
$dt = date("Y-m-d H:i:s (T)");
// define an assoc array of error string
// in reality the only entries we should
// consider are E_WARNING, E_NOTICE, E_USER_ERROR,
// E_USER_WARNING and E_USER_NOTICE
$errortype = array (
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
);
// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
$err = "<errorentry>\n";
$err .= "\t<datetime>" . $dt . "</datetime>\n";
$err .= "\t<errornum>" . $errno . "</errornum>\n";
$err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
$err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
$err .= "\t<scriptname>" . $filename . "</scriptname>\n";
$err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";
if (in_array($errno, $user_errors)) {
$err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
}
$err .= "</errorentry>\n\n";
// for testing
// echo $err;
// save to the error log, and e-mail me if there is a critical user error
error_log($err, 3, "/usr/local/php4/error.log");
if ($errno == E_USER_ERROR) {
mail("phpdev@example.com", "Critical User Error", $err);
}
}
function distance($vect1, $vect2)
{
if (!is_array($vect1) || !is_array($vect2)) {
trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
return NULL;
}
if (count($vect1) != count($vect2)) {
trigger_error("Vectors need to be of the same size", E_USER_ERROR);
return NULL;
}
for ($i=0; $i<count($vect1); $i++) {
$c1 = $vect1[$i]; $c2 = $vect2[$i];
$d = 0.0;
if (!is_numeric($c1)) {
trigger_error("Coordinate $i in vector 1 is not a number, using zero",
E_USER_WARNING);
$c1 = 0.0;
}
if (!is_numeric($c2)) {
trigger_error("Coordinate $i in vector 2 is not a number, using zero",
E_USER_WARNING);
$c2 = 0.0;
}
$d += $c2*$c2 - $c1*$c1;
}
return sqrt($d);
}
$old_error_handler = set_error_handler("userErrorHandler");
// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;
// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);
// generate a user error
$t1 = distance($c, $b) . "\n";
// generate another user error
$t2 = distance($b, "i am not an array") . "\n";
// generate a warning
$t3 = distance($a, $b) . "\n";
?>
See also syslog().
(PHP 4 >= 4.3.0, PHP 5)
debug_backtrace — Generates a backtrace
$options = DEBUG_BACKTRACE_PROVIDE_OBJECT
[, int $limit = 0
]] )debug_backtrace() generates a PHP backtrace.
optionsAs of 5.3.6, this parameter is a bitmask for the following options:
| DEBUG_BACKTRACE_PROVIDE_OBJECT | Whether or not to populate the "object" index. |
| DEBUG_BACKTRACE_IGNORE_ARGS | Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory. |
TRUE or FALSE, which are the same as
setting or not setting the DEBUG_BACKTRACE_PROVIDE_OBJECT option respectively.
limit
As of 5.4.0, this parameter can be used to limit the number of stack frames returned.
By default (limit=0) it returns all stack frames.
Returns an array of associative arrays. The possible returned elements are as follows:
| Name | Type | Description |
|---|---|---|
| function | string | The current function name. See also __FUNCTION__. |
| line | integer | The current line number. See also __LINE__. |
| file | string | The current file name. See also __FILE__. |
| class | string | The current class name. See also __CLASS__ |
| object | object | The current object. |
| type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned. |
| args | array | If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s). |
| Version | Description |
|---|---|
| 5.4.0 |
Added the optional parameter limit.
|
| 5.3.6 |
The parameter provide_object changed to options and additional option
DEBUG_BACKTRACE_IGNORE_ARGS is added.
|
| 5.2.5 |
Added the optional parameter provide_object.
|
| 5.1.1 | Added the current object as a possible return element. |
Example #1 debug_backtrace() example
<?php
// filename: /tmp/a.php
function a_test($str)
{
echo "\nHi: $str";
var_dump(debug_backtrace());
}
a_test('friend');
?>
<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>
Results similar to the following when executing /tmp/b.php:
Hi: friend
array(2) {
[0]=>
array(4) {
["file"] => string(10) "/tmp/a.php"
["line"] => int(10)
["function"] => string(6) "a_test"
["args"]=>
array(1) {
[0] => &string(6) "friend"
}
}
[1]=>
array(4) {
["file"] => string(10) "/tmp/b.php"
["line"] => int(2)
["args"] =>
array(1) {
[0] => string(10) "/tmp/a.php"
}
["function"] => string(12) "include_once"
}
}
(PHP 5)
debug_print_backtrace — Prints a backtrace
$options = 0
[, int $limit = 0
]] )debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.
optionsAs of 5.3.6, this parameter is a bitmask for the following options:
| DEBUG_BACKTRACE_IGNORE_ARGS | Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory. |
limit
As of 5.4.0, this parameter can be used to limit the number of stack frames printed.
By default (limit=0) it prints all stack frames.
No value is returned.
| Version | Description |
|---|---|
| 5.4.0 |
Added the optional parameter limit.
|
| 5.3.6 |
Added the optional parameter options.
|
Example #1 debug_print_backtrace() example
<?php
// include.php file
function a() {
b();
}
function b() {
c();
}
function c(){
debug_print_backtrace();
}
a();
?>
<?php
// test.php file
// this is the file you should run
include 'include.php';
?>
The above example will output something similar to:
#0 c() called at [/tmp/include.php:10] #1 b() called at [/tmp/include.php:6] #2 a() called at [/tmp/include.php:17] #3 include(/tmp/include.php) called at [/tmp/test.php:3]
(PHP 5 >= 5.2.0)
error_get_last — Get the last occurred error
Gets information about the last error that occurred.
Returns an associative array describing the last error with keys "type",
"message", "file" and "line". If the error has been caused by a PHP
internal function then the "message" begins with its name.
Returns NULL if there hasn't been an error yet.
Example #1 An error_get_last() example
<?php
echo $a;
print_r(error_get_last());
?>
The above example will output something similar to:
Array
(
[type] => 8
[message] => Undefined variable: a
[file] => C:\WWW\index.php
[line] => 2
)
(PHP 4, PHP 5)
error_log — Send an error message to the defined error handling routines
$message
[, int $message_type = 0
[, string $destination
[, string $extra_headers
]]] )Sends an error message to the web server's error log or to a file.
messageThe error message that should be logged.
message_typeSays where the error should go. The possible message types are as follows:
| 0 |
message is sent to PHP's system logger, using
the Operating System's system logging mechanism or a file, depending
on what the error_log
configuration directive is set to. This is the default option.
|
| 1 |
message is sent by email to the address in
the destination parameter. This is the only
message type where the fourth parameter,
extra_headers is used.
|
| 2 | No longer an option. |
| 3 |
message is appended to the file
destination. A newline is not automatically
added to the end of the message string.
|
| 4 |
message is sent directly to the SAPI logging
handler.
|
destination
The destination. Its meaning depends on the
message_type parameter as described above.
extra_headers
The extra headers. It's used when the message_type
parameter is set to 1.
This message type uses the same internal function as
mail() does.
Returns TRUE on success or FALSE on failure.
error_log() is not binary safe. message will be truncated by null character.
message should not contain null character. Note that message may be sent to file, mail, syslog, etc. Use appropriate conversion/escape function, base64_encode(), rawurlencode() or addslashes() before calling error_log().
Example #1 error_log() examples
<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
error_log("Oracle database not available!", 0);
}
// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
error_log("Big trouble, we're all out of FOOs!", 1,
"operator@example.com");
}
// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>
| Version | Description |
|---|---|
| 5.2.7 |
The possible value of 4 was added to message_type.
|
(PHP 4, PHP 5)
error_reporting — Sets which PHP errors are reported
$level
] )
The error_reporting() function sets the
error_reporting
directive at runtime. PHP has many levels of errors, using
this function sets that level for the duration (runtime) of
your script. If the optional level is
not set, error_reporting() will just return
the current error reporting level.
levelThe new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.
The available error level constants and the actual meanings of these error levels are described in the predefined constants.
Returns the old error_reporting
level or the current level if no level parameter is
given.
| Version | Description |
|---|---|
| 5.4.0 | E_STRICT became part of E_ALL. |
| 5.3.0 | E_DEPRECATED and E_USER_DEPRECATED introduced. |
| 5.2.0 | E_RECOVERABLE_ERROR introduced. |
| 5.0.0 | E_STRICT introduced (not part of E_ALL). |
Example #1 error_reporting() examples
<?php
// Turn off all error reporting
error_reporting(0);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
?>
Most of E_STRICT errors are evaluated at the
compile time thus such errors are not reported in the file where
error_reporting is enhanced
to include E_STRICT errors (and vice versa).
Passing in the value -1 will show every possible error,
even when new levels and constants are added in future PHP versions. The
E_ALL constant also behaves this way as of PHP 5.4.
(PHP 4 >= 4.0.1, PHP 5)
restore_error_handler — Restores the previous error handler function
Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).
This function always returns TRUE.
Example #1 restore_error_handler() example
Decide if unserialize() caused an error, then restore the original error handler.
<?php
function unserialize_handler($errno, $errstr)
{
echo "Invalid serialized value.\n";
}
$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>
The above example will output:
Invalid serialized value.
(PHP 5)
restore_exception_handler — Restores the previously defined exception handler function
Used after changing the exception handler function using set_exception_handler(), to revert to the previous exception handler (which could be the built-in or a user defined function).
This function always returns TRUE.
Example #1 restore_exception_handler() example
<?php
function exception_handler_1(Exception $e)
{
echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
}
function exception_handler_2(Exception $e)
{
echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
}
set_exception_handler('exception_handler_1');
set_exception_handler('exception_handler_2');
restore_exception_handler();
throw new Exception('This triggers the first exception handler...');
?>
The above example will output:
[exception_handler_1] This triggers the first exception handler...
(PHP 4 >= 4.0.1, PHP 5)
set_error_handler — Sets a user-defined error handler function
Sets a user function (error_handler) to handle
errors in a script.
This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).
It is important to remember that the standard PHP error handler is completely
bypassed for the error types specified by error_types
unless the callback function returns FALSE.
error_reporting() settings will have no effect and your
error handler will be called regardless - however you are still able to read
the current value of
error_reporting and act
appropriately. Of particular note is that this value will be 0 if the
statement that caused the error was prepended by the
@ error-control
operator.
Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.
The following error types cannot be handled with a user defined
function: E_ERROR, E_PARSE,
E_CORE_ERROR, E_CORE_WARNING,
E_COMPILE_ERROR,
E_COMPILE_WARNING, and
most of E_STRICT raised in the file where
set_error_handler() is called.
If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.
error_handler
A callback with the following signature.
NULL may be passed instead, to reset this handler to its default state.
$errno
, string $errstr
[, string $errfile
[, int $errline
[, array $errcontext
]]] )errnoerrno, contains the
level of the error raised, as an integer.
errstrerrstr, contains the
error message, as a string.
errfileerrfile,
which contains the filename that the error was raised in, as a string.
errlineerrline,
which contains the line number the error was raised at, as an integer.
errcontexterrcontext,
which is an array that points to the active symbol table at the point
the error occurred. In other words, errcontext
will contain an array of every variable that existed in the scope the
error was triggered in.
User error handler must not modify error context.
If the function returns FALSE then the normal error handler continues.
error_types
Can be used to mask the triggering of the
error_handler function just like the error_reporting ini setting
controls which errors are shown. Without this mask set the
error_handler will be called for every error
regardless to the setting of the error_reporting setting.
Returns a string containing the previously defined error handler (if any). If
the built-in error handler is used NULL is returned. NULL is also returned
in case of an error such as an invalid callback. If the previous error handler
was a class method, this function will return an indexed array with the class
and the method name.
| Version | Description |
|---|---|
| 5.5.0 |
error_handler now accepts NULL.
|
| 5.2.0 |
The error handler must return FALSE to populate
$php_errormsg.
|
| 5.0.0 |
The error_types parameter was introduced.
|
| 4.3.0 |
Instead of a function name, an array containing an object reference
and a method name can also be supplied as the
error_handler.
|
| 4.0.2 |
Three optional parameters for the error_handler
user function was introduced. These are the filename, the line number,
and the context.
|
Example #1 Error handling with set_error_handler() and trigger_error()
The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:
<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
switch ($errno) {
case E_USER_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "Aborting...<br />\n";
exit(1);
break;
case E_USER_WARNING:
echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
break;
case E_USER_NOTICE:
echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
break;
default:
echo "Unknown error type: [$errno] $errstr<br />\n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
// function to test the error handling
function scale_by_log($vect, $scale)
{
if (!is_numeric($scale) || $scale <= 0) {
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
}
if (!is_array($vect)) {
trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
return null;
}
$temp = array();
foreach($vect as $pos => $value) {
if (!is_numeric($value)) {
trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
$value = 0;
}
$temp[$pos] = log($scale) * $value;
}
return $temp;
}
// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");
// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);
// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);
// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL
// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>
The above example will output something similar to:
vector a
Array
(
[0] => 2
[1] => 3
[2] => foo
[3] => 5.5
[4] => 43.3
[5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
[0] => 2.2894597716988
[1] => 3.4341896575482
[2] => 0
[3] => 6.2960143721717
[4] => 49.566804057279
[5] => 24.165247890281
)
----
vector c - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />
(PHP 5)
set_exception_handler — Sets a user-defined exception handler function
Sets the default exception handler if an exception is not caught within a
try/catch block. Execution will stop after the
exception_handler is called.
exception_handlerName of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown. This is the handler signature:
NULL may be passed instead, to reset this handler to its default state.
Returns the name of the previously defined exception handler, or NULL on error. If
no previous handler was defined, NULL is also returned.
| Version | Description |
|---|---|
| 5.5.0 |
Previously, if NULL was passed then this function returned TRUE.
It returns the previous handler since PHP 5.5.0.
|
Example #1 set_exception_handler() example
<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
(PHP 4 >= 4.0.1, PHP 5)
trigger_error — Generates a user-level error/warning/notice message
$error_msg
[, int $error_type = E_USER_NOTICE
] )Used to trigger a user error condition, it can be used in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).
This function is useful when you need to generate a particular response to an exception at runtime.
error_msgThe designated error message for this error. It's limited to 1024 bytes in length. Any additional characters beyond 1024 bytes will be truncated.
error_type
The designated error type for this error. It only works with the E_USER
family of constants, and will default to E_USER_NOTICE.
This function returns FALSE if wrong error_type is
specified, TRUE otherwise.
Example #1 trigger_error() example
See set_error_handler() for a more extensive example.
<?php
if ($divisor == 0) {
trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>
HTML entities in error_msg are not
escaped. Use htmlentities() on the message if
the error is to be displayed in a browser.
This function is an alias of: trigger_error().
The htscanner extension gives the possibility to use htaccess-like file to configure PHP per directory, just like apache's htaccess. It is especially useful with fastcgi (ISS5/6/7, lighttpd, etc.).
PHP version 5.2.0 or greater.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/htscanner
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| htscanner.config_file | ".htscanner" | PHP_INI_SYSTEM | |
| htscanner.default_docroot | "/" | PHP_INI_SYSTEM | |
| htscanner.default_ttl | "300" | PHP_INI_SYSTEM | |
| htscanner.stop_on_error | "Off" | PHP_INI_SYSTEM |
Here's a short explanation of the configuration directives.
This extension has no resource types defined.
Traces through and dumps the hierarchy of file inclusions and class inheritance at runtime.
The files may have been included using include, include_once, require, or require_once.
Class inheritance dependencies are also reported.
PHP version 5.1.0 or greater.
The included gengraph.php file utilizes the » graphviz library, however, this is not required.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/inclued
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| inclued.enabled | Off | PHP_INI_SYSTEM | |
| inclued.dumpdir | NULL |
PHP_INI_SYSTEM |
Here's a short explanation of the configuration directives.
inclued.enabled
bool
Whether or not to enable inclued.
inclued.dumpdir
string
Location (path) to the directory that stores inclued files. If set, each PHP request will create a file. These files are serialized versions of what inclued_get_data() would produce, so may be unserialized with unserialize().
Because every request creates a file, this directory may fill up fast!
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
This extension has no constants defined.
This example demonstrates the process of implementing inclued into an existing application, and viewing the results.
Example #1 Getting the data within the PHP application itself (function)
<?php
// File to store the inclued information
$fp = fopen('/tmp/wp.ser', 'w');
if ($fp) {
$clue = inclued_get_data();
if ($clue) {
fwrite($fp, serialize($clue));
}
fclose($fp);
}
?>
Now that some data exists, it's time to make sense of it in the form of a graph. The inclued extension includes a PHP file named gengraph.php that creates a dot file that requires the » graphviz library. However, this form is not required.
Example #2 Example use of gengraph.php
This example creates an image named inclued.png that shows the inclued data.
# First, create the dot file $ php gengraph.php -i /tmp/wp.ser -o wp.dot # Next, create the image $ dot -Tpng -o inclued.png wp.dot
Example #3 Listing data via inclued dumps (configuration)
When using the inclued.dumpdir directive, files (include clues) are dumped with every request. Here's one way to list those files, and unserialize() them.
<?php
$path = ini_get('inclued.dumpdir');
if ($path && is_dir($path)) {
echo "Path: $path", PHP_EOL;
$inclues = new GlobIterator($path . DIRECTORY_SEPARATOR . 'inclued*');
if ($inclues->count() === 0) {
echo 'No clues today', PHP_EOL;
exit;
}
foreach ($inclues as $inclue) {
echo 'Inclued file: ', $inclue->getFilename(), PHP_EOL;
$data = file_get_contents($inclue->getPathname());
if ($data) {
$inc = unserialize($data);
echo ' -- filename: ', $inc['request']['SCRIPT_FILENAME'], PHP_EOL;
echo ' -- number of includes: ', count($inc['includes']), PHP_EOL;
}
echo PHP_EOL;
}
} else {
echo 'I am totally clueless today.', PHP_EOL;
}
?>
The above example will output something similar to:
PATH: /tmp/inclued Inclued file: inclued.56521.1 -- filename: /Users/philip/test.php -- number of includes: 1 Inclued file: inclued.56563.1 -- filename: /tmp/none.php -- number of includes: 0 Inclued file: inclued.56636.1 -- filename: /tmp/three.php -- number of includes: 3
(PECL inclued >= 0.1.0)
inclued_get_data — Get the inclued data
Get the inclued data.
This function has no parameters.
The inclued data.
Example #1 inclued_get_data() example
See the inclued examples section for ways to create graphs with this data.
<?php
include 'x.php';
$clue = inclued_get_data();
print_r($clue);
?>
The above example will output something similar to:
Array
(
[includes] => Array
(
[0] => Array
(
[operation] => include
[op_type] => 2
[filename] => x.php
[opened_path] => /tmp/x.php
[fromfile] => /tmp/z.php
[fromline] => 2
)
)
)
The purpose of this extension is to detect the most memory hungry scripts and functions.
memtrack tracks memory consumption in PHP scripts and produces reports (warnings) when the consumption reaches certain levels set by the user. This is achieved by replacing default executor function by a special function which compares memory usage before and after running the original executor - this way we can tell how much the memory usage has changed during the execution of the current part of the code.
Zend Engine runs its executor for each opcode array (op_array), which usually means function, plain script and such, so memtrack doesn't have any noticeable effect on performance.
memtrack doesn't provide any functions, there are only INI directives which allow you to configure the way it should work.
This extension is EXPERIMENTAL. The behaviour of this extension including the names of its functions and any other documentation surrounding this extension may change without notice in a future release of PHP. This extension should be used at your own risk.
No external libraries are needed to build this extension.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/memtrack
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable |
|---|---|---|
| memtrack.enabled | "0" | PHP_INI_SYSTEM |
| memtrack.soft_limit | "0" | PHP_INI_ALL |
| memtrack.hard_limit | "0" | PHP_INI_ALL |
| memtrack.vm_limit | "0" | PHP_INI_ALL |
| memtrack.ignore_functions | "" | PHP_INI_SYSTEM |
Here's a short explanation of the configuration directives.
memtrack.enabled
boolean
Disables or enables the extension. Default value is 0, i.e. disabled.
memtrack.soft_limit
int
Soft memory limit.
The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the soft limit, but only if the function is not ignored.
Setting this option to 0 also disables both soft and hard limit warnings. Default value is 0, i.e. no warnings is produced.
memtrack.hard_limit
int
Hard memory limit.
The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the hard limit, even if the function is ignored. Setting this option to 0 disables hard limit warnings completely. Default value is 0, i.e. no hard limit warnings is produced.
memtrack.vm_limit
int
Virtual memory limit (set on a process).
This limit is checked only on shutdown and a warning is produced if the value is greater than or equal to the limit.
This option is currently supported only on OSes where mallinfo() function is available (i.e. Linux).
memtrack.ignore_functions
string
A comma or whitespace-separated list of functions which are to be ignored by soft_limit. The values are case-insensitive, for class methods use class::method syntax.
This extension has no resource types defined.
This extension has no constants defined.
Basic example on using memtrack extension:
Example #1 Creating large array in a function
<?php
/* /tmp/example1.php */
function foo() {
$a = array();
for ($i = 0; $i < 10000; $i++) $a[] = "test";
return $a;
}
$arr = foo();
?>
Run the example with the following command:
php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php
The above example will output something similar to:
Warning: [memtrack] [pid 26177] user function foo() executed in /tmp/example1.php on line 10 allocated 4194304 bytes in /tmp/example1.php on line 0 Warning: [memtrack] [pid 26177] virtual memory usage on shutdown: 32911360 bytes in Unknown on line 0
OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.
This extension is bundled with PHP 5.5.0 and later, and is » available in PECL for PHP versions 5.2, 5.3 and 5.4.
No external libraries are needed to build this extension.
The process of installing OPcache varies depending on which version of PHP you're running. Please refer to the appropriate section below.
Note:
If you want to use OPcache with » Xdebug, you must load OPcache before Xdebug.
OPcache can only be compiled as a shared extension. If you have disabled the building of default extensions with --disable-all , you must compile PHP with the --enable-opcache option for OPcache to be available.
Once compiled, you can use the zend_extension configuration directive to load the OPcache extension into PHP. This can be done with zend_extension=/full/path/to/opcache.so on non-Windows platforms, and zend_extension=C:\path\to\php_opcache.dll on Windows.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ZendOpcache.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
The following settings are generally recommended as providing good performance:
opcache.memory_consumption=128 opcache.interned_strings_buffer=8 opcache.max_accelerated_files=4000 opcache.revalidate_freq=60 opcache.fast_shutdown=1 opcache.enable_cli=1
You may also want to consider disabling opcache.save_comments and enabling opcache.enable_file_override, however note that you will have to test your code before using these in production as they are known to break some frameworks and applications, particularly in cases where documentation comment annotations are used.
A full list of configuration directives supported by OPcache is also available.
The behaviour of these functions is affected by settings in php.ini.
Where a configuration setting may be set.
Here's a short explanation of the configuration directives.
opcache.enable
boolean
Enables the opcode cache. When disabled, code is not optimised or cached. The setting opcache.enable can not be enabled at runtime through ini_set(), it can only be disabled. Trying to enable it at in a script will generate a warning.
opcache.enable_cli
boolean
Enables the opcode cache for the CLI version of PHP. This is mostly useful for testing and debugging.
opcache.memory_consumption
integer
The size of the shared memory storage used by OPcache, in megabytes.
opcache.interned_strings_buffer
integer
The amount of memory used to store interned strings, in megabytes. This configuration directive is ignored in PHP < 5.3.0.
opcache.max_accelerated_files
integer
The maximum number of keys (and therefore scripts) in the OPcache hash table. The actual value used will be the first number in the set of prime numbers { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } that is bigger than the configured value. Only numbers between 200 and 100000 are allowed.
opcache.max_wasted_percentage
integer
The maximum percentage of wasted memory that is allowed before a restart is scheduled.
opcache.use_cwd
boolean
If enabled, OPcache appends the current working directory to the script key, thereby eliminating possible collisions between files with the same base name. Disabling this directive improves performance, but may break existing applications.
opcache.validate_timestamps
boolean
If enabled, OPcache will check for updated scripts every opcache.revalidate_freq seconds. When this directive is disabled, you must reset OPcache manually via opcache_reset(), opcache_invalidate() or by restarting the Web server for changes to the filesystem to take effect.
opcache.revalidate_freq
integer
How often to check script timestamps for updates, in seconds. 0 will result in OPcache checking for updates on every request.
This configuration directive is ignored if opcache.validate_timestamps is disabled.
opcache.revalidate_path
boolean
If disabled, existing cached files using the same include_path will be reused. Thus, if a file with the same name is elsewhere in the include_path, it won't be found.
opcache.save_comments
boolean
If disabled, all documentation comments will be discarded from the opcode cache to reduce the size of the optimised code. Disabling this configuration directive may break applications and frameworks that rely on comment parsing for annotations, including Doctrine, Zend Framework 2 and PHPUnit.
opcache.load_comments
boolean
If disabled, documentation comments won't be loaded from the opcode cache even if they exist. This can be used with opcache.save_comments to only load comments for applications that require them.
opcache.fast_shutdown
boolean
If enabled, a fast shutdown sequence is used that doesn't free each allocated block, but relies on the Zend Engine memory manager to deallocate the entire set of request variables en masse.
opcache.enable_file_override
boolean
When enabled, the opcode cache will be checked for whether a file has already been cached when file_exists(), is_file() and is_readable() are called. This may increase performance in applications that check the existence and readability of PHP scripts, but risks returning stale data if opcache.validate_timestamps is disabled.
opcache.optimization_level
integer
A bitmask that controls which optimisation passes are executed.
opcache.inherited_hack
boolean
In PHP < 5.3, OPcache stores the places where DECLARE_CLASS opcodes used inheritance; when the file is loaded, OPcache then tries to bind the inherited classes using the current environment. The problem is that while the DECLARE_CLASS opcode may not be needed for the current script, if the script requires that the opcode be defined, it may not run.
This configuration directive is ignored in PHP 5.3 and later.
opcache.dups_fix
boolean
This hack should only be enabled to work around "Cannot redeclare class" errors.
opcache.blacklist_filename
string
The location of the OPcache blacklist file. A blacklist file is a text file containing the names of files that should not be accelerated, one per line. Wildcards are allowed, and prefixes can also be provided. Lines starting with a semi-colon are ignored as comments.
A simple blacklist file might look as follows:
; Matches a specific file. /var/www/broken.php ; A prefix that matches all files starting with x. /var/www/x ; A wildcard match. /var/www/*-broken.php
opcache.max_file_size
integer
The maximum file size that will be cached, in bytes. If this is 0, all files will be cached.
opcache.consistency_checks
integer
If non-zero, OPcache will verify the cache checksum every N requests, where N is the value of this configuration directive. This should only be enabled when debugging, as it will impair performance.
opcache.force_restart_timeout
integer
The length of time to wait for a scheduled restart to begin if the cache isn't active, in seconds. If the timeout is hit, then OPcache assumes that something is wrong and will kill the processes holding locks on the cache to permit a restart.
If opcache.log_verbosity_level is set to 3 or above, an error will be recorded in the error log when this occurs.
opcache.error_log
string
The error log for OPcache errors. An empty string is treated the same as stderr, and will result in logs being sent to standard error (which will be the Web server error log in most cases).
opcache.log_verbosity_level
integer
The log verbosity level. By default, only fatal errors (level 0) and errors (level 1) are logged. Other levels available are warnings (level 2), information messages (level 3) and debug messages (level 4).
opcache.preferred_memory_model
string
The preferred memory model for OPcache to use. If left empty, OPcache will choose the most appropriate model, which is the correct behaviour in virtually all cases.
Possible values include mmap, shm, posix and win32.
opcache.protect_memory
boolean
Protects shared memory from unexpected writes while executing scripts. This is useful for internal debugging only.
opcache.mmap_base
string
The base used for shared memory segments on Windows. All PHP processes have to map shared memory into the same address space. Using this directive allows "Unable to reattach to base address" errors to be fixed.
This extension has no resource types defined.
(PHP 5 >= 5.5.5, PECL ZendOpcache > 7.0.2)
opcache_compile_file — Compiles and caches a PHP script without executing it
$file
)This function compiles a PHP script and adds it to the opcode cache without executing it. This can be used to prime the cache after a Web server restart by pre-caching files that will be included in later requests.
fileThe path to the PHP script to be compiled.
Returns TRUE if file was compiled successfully
or FALSE on failure.
If file cannot be loaded or compiled, an error of
level E_WARNING is generated. You may use
@ to suppress this
warning.
(PHP 5 >= 5.5.5, PECL ZendOpcache > 7.0.2)
opcache_get_configuration — Get configuration information about the cache
This function returns configuration information about the cache instance
Returns an array of information, including ini, blacklist and version
If opcache.restrict_api is in use and the current path is in violation of the rule, an E_WARNING will be raised; no status information will be returned.
(PHP 5 >= 5.5.5, PECL ZendOpcache > 7.0.2)
opcache_get_status — Get status information about the cache
$get_scripts = TRUE
] )This function returns state information about the cache instance
get_scriptsInclude script specific state information
Returns an array of information, optionally containing script specific state information
If opcache.restrict_api is in use and the current path is in violation of the rule, an E_WARNING will be raised; no status information will be returned.
(PHP 5 >= 5.5.0, PECL ZendOpcache >= 7.0.0)
opcache_invalidate — Invalidates a cached script
$script
[, boolean $force = FALSE
] )
This function invalidates a particular script from the opcode cache. If
force is unset or FALSE, the script will only be
invalidated if the modification time of the script is newer than the cached
opcodes.
scriptThe path to the script being invalidated.
force
If set to TRUE, the script will be invalidated regardless of whether
invalidation is necessary.
Returns TRUE if the opcode cache for script was
invalidated or if there was nothing to invalidate, or FALSE if the opcode
cache is disabled.
(PHP 5 >= 5.5.0, PECL ZendOpcache >= 7.0.0)
opcache_reset — Resets the contents of the opcode cache
This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit.
This function has no parameters.
Returns TRUE if the opcode cache was reset, or FALSE if the opcode
cache is disabled.
The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo and data between blocks of PHP code.
Note:
When upgrading from PHP 4.1.x (and 4.2.x) to 4.3.x due to a bug in earlier versions you must ensure that implicit_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.
No external libraries are needed to build this extension.
There is no installation needed to use these functions; they are part of the PHP core.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| output_buffering | "0" | PHP_INI_PERDIR | |
| output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4. |
| implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3. |
Here's a short explanation of the configuration directives.
output_buffering
boolean/integer
You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI.
output_handler
string
You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.
Note:
You cannot use both mb_output_handler() with ob_iconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.
Note:
Only built-in functions can be used with this directive. For user defined functions, use ob_start().
implicit_flush
boolean
FALSE by default. Changing this to TRUE tells PHP to tell the
output layer to flush itself automatically after every output block.
This is equivalent to calling the PHP function
flush() after each and every call to
print or echo and each and
every HTML block.
When using PHP within an web environment, turning
this option on has serious performance implications and is generally
recommended for debugging purposes only. This value defaults to
TRUE when operating under the CLI SAPI.
See also ob_implicit_flush().
This extension has no resource types defined.
The constants below are always available as part of the PHP core.
PHP_OUTPUT_HANDLER_START
(integer)
Indicates that output buffering has begun.
PHP_OUTPUT_HANDLER_WRITE
(integer)
Indicates that the output buffer is being flushed, and had data to output.
Available since PHP 5.4.
PHP_OUTPUT_HANDLER_FLUSH
(integer)
Indicates that the buffer has been flushed.
Available since PHP 5.4.
PHP_OUTPUT_HANDLER_CLEAN
(integer)
Indicates that the output buffer has been cleaned.
Available since PHP 5.4.
PHP_OUTPUT_HANDLER_FINAL
(integer)
Indicates that this is the final output buffering operation.
Available since PHP 5.4.
PHP_OUTPUT_HANDLER_CONT
(integer)
Indicates that the buffer has been flushed, but output buffering will continue.
As of PHP 5.4, this is an alias for
PHP_OUTPUT_HANDLER_WRITE.
PHP_OUTPUT_HANDLER_END
(integer)
Indicates that output buffering has ended.
As of PHP 5.4, this is an alias for
PHP_OUTPUT_HANDLER_FINAL.
PHP_OUTPUT_HANDLER_CLEANABLE
(integer)
Controls whether an output buffer created by ob_start() can be cleaned.
Available since PHP 5.4.
PHP_OUTPUT_HANDLER_FLUSHABLE
(integer)
Controls whether an output buffer created by ob_start() can be flushed.
Available since PHP 5.4.
PHP_OUTPUT_HANDLER_REMOVABLE
(integer)
Controls whether an output buffer created by ob_start() can be removed before the end of the script.
Available since PHP 5.4.
PHP_OUTPUT_HANDLER_STDFLAGS
(integer)
The default set of output buffer flags; currently equivalent to
PHP_OUTPUT_HANDLER_CLEANABLE |
PHP_OUTPUT_HANDLER_FLUSHABLE |
PHP_OUTPUT_HANDLER_REMOVABLE.
Available since PHP 5.4.
Example #1 Output Control example
<?php
ob_start();
echo "Hello\n";
setcookie("cookiename", "cookiedata");
ob_end_flush();
?>
In the above example, the output from echo would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)
See also header() and setcookie().
(PHP 4, PHP 5)
flush — Flush the output buffer
Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.
flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.
Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.
Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.
Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.
Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
No value is returned.
(PHP 4 >= 4.2.0, PHP 5)
ob_clean — Clean (erase) the output buffer
This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean() does.
No value is returned.
(PHP 4, PHP 5)
ob_end_clean — Clean (erase) the output buffer and turn off output buffering
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.
Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the
function without an active buffer or that for some reason a buffer could
not be deleted (possible for special buffer).
If the function fails it generates an E_NOTICE.
| Version | Description |
|---|---|
| 4.2.0 | The boolean return value was added. |
The following example shows an easy way to get rid of all output buffers:
Example #1 ob_end_clean() example
<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>
(PHP 4, PHP 5)
ob_end_flush — Flush (send) the output buffer and turn off output buffering
This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.
Note: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.
Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the
function without an active buffer or that for some reason a buffer could
not be deleted (possible for special buffer).
If the function fails it generates an E_NOTICE.
| Version | Description |
|---|---|
| 4.2.0 | The boolean return value was added. |
Example #1 ob_end_flush() example
The following example shows an easy way to flush and end all output buffers:
<?php
while (@ob_end_flush());
?>
(PHP 4 >= 4.2.0, PHP 5)
ob_flush — Flush (send) the output buffer
This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.
No value is returned.
(PHP 4 >= 4.3.0, PHP 5)
ob_get_clean — Get current buffer contents and delete current output buffer
Gets the current buffer contents and delete current output buffer.
ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().
Returns the contents of the output buffer and end output buffering.
If output buffering isn't active then FALSE is returned.
Example #1 A simple ob_get_clean() example
<?php
ob_start();
echo "Hello World";
$out = ob_get_clean();
$out = strtolower($out);
var_dump($out);
?>
The above example will output:
string(11) "hello world"
(PHP 4, PHP 5)
ob_get_contents — Return the contents of the output buffer
Gets the contents of the output buffer without clearing it.
This will return the contents of the output buffer or FALSE, if output
buffering isn't active.
Example #1 A simple ob_get_contents() example
<?php
ob_start();
echo "Hello ";
$out1 = ob_get_contents();
echo "World";
$out2 = ob_get_contents();
ob_end_clean();
var_dump($out1, $out2);
?>
The above example will output:
string(6) "Hello " string(11) "Hello World"
(PHP 4 >= 4.3.0, PHP 5)
ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering.
Note: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.
Returns the output buffer or FALSE if no buffering is active.
Example #1 ob_get_flush() example
<?php
//using output_buffering=On
print_r(ob_list_handlers());
//save buffer in a file
$buffer = ob_get_flush();
file_put_contents('buffer.txt', $buffer);
print_r(ob_list_handlers());
?>
The above example will output:
Array
(
[0] => default output handler
)
Array
(
)
(PHP 4 >= 4.0.2, PHP 5)
ob_get_length — Return the length of the output buffer
This will return the length of the contents in the output buffer.
Returns the length of the output buffer contents or FALSE if no
buffering is active.
Example #1 A simple ob_get_length() example
<?php
ob_start();
echo "Hello ";
$len1 = ob_get_length();
echo "World";
$len2 = ob_get_length();
ob_end_clean();
echo $len1 . ", ." . $len2;
?>
The above example will output:
6, 11
(PHP 4 >= 4.2.0, PHP 5)
ob_get_level — Return the nesting level of the output buffering mechanism
Returns the nesting level of the output buffering mechanism.
Returns the level of nested output buffering handlers or zero if output buffering is not active.
(PHP 4 >= 4.2.0, PHP 5)
ob_get_status — Get status of output buffers
$full_status = FALSE
] )
ob_get_status() returns status information on either
the top level output buffer or all active output buffer levels if
full_status is set to TRUE.
full_status
TRUE to return all active output buffer levels. If FALSE or not
set, only the top level output buffer is returned.
If called without the full_status parameter
or with full_status = FALSE a simple array
with the following elements is returned:
Array
(
[level] => 2
[type] => 0
[status] => 0
[name] => URL-Rewriter
[del] => 1
)
| Key | Value |
|---|---|
| level | Output nesting level |
| type | PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1) |
| status | One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2) |
| name | Name of active output handler or ' default output handler' if none is set |
| del | Erase-flag as set by ob_start() |
If called with full_status = TRUE an array
with one element for each active output buffer level is returned.
The output level is used as key of the top level array and each array
element itself is another array holding status information
on one active output level.
Array
(
[0] => Array
(
[chunk_size] => 0
[size] => 40960
[block_size] => 10240
[type] => 1
[status] => 0
[name] => default output handler
[del] => 1
)
[1] => Array
(
[chunk_size] => 0
[size] => 40960
[block_size] => 10240
[type] => 0
[buffer_size] => 0
[status] => 0
[name] => URL-Rewriter
[del] => 1
)
)
The full output contains these additional elements:
| Key | Value |
|---|---|
| chunk_size | Chunk size as set by ob_start() |
| size | ... |
| blocksize | ... |
(PHP 4 >= 4.0.4, PHP 5)
ob_gzhandler — ob_start callback function to gzip output buffer
$buffer
, int $mode
)
ob_gzhandler() is intended to be used as a callback
function for ob_start() to help facilitate sending
gz-encoded data to web browsers that support compressed web pages.
Before ob_gzhandler() actually sends compressed data,
it determines what type of content encoding the browser will accept
("gzip", "deflate" or none at all) and will return its output accordingly.
All browsers are supported since it's up to the browser to send the
correct header saying that it accepts compressed web pages. If a browser
doesn't support compressed pages this function returns FALSE.
buffer
mode
| Version | Description |
|---|---|
| 4.0.5 |
The mode parameter was added.
|
Example #1 ob_gzhandler() example
<?php
ob_start("ob_gzhandler");
?>
<html>
<body>
<p>This should be a compressed page.</p>
</body>
</html>
Note:
ob_gzhandler() requires the zlib extension.
Note:
You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler().
(PHP 4, PHP 5)
ob_implicit_flush — Turn implicit flush on/off
$flag = true
] )ob_implicit_flush() will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.
flag
TRUE to turn implicit flushing on, FALSE otherwise.
No value is returned.
(PHP 4 >= 4.3.0, PHP 5)
ob_list_handlers — List all output handlers in use
Lists all output handlers in use.
This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".
Example #1 ob_list_handlers() example
<?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();
ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();
// anonymous functions
ob_start(function($string) { return $string; });
print_r(ob_list_handlers());
ob_end_flush();
?>
The above example will output:
Array
(
[0] => default output handler
)
Array
(
[0] => ob_gzhandler
)
Array
(
[0] => Closure::__invoke
)
(PHP 4, PHP 5)
ob_start — Turn on output buffering
$output_callback = NULL
[, int $chunk_size = 0
[, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS
]]] )This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
output_callback
An optional output_callback function may be
specified. This function takes a string as a parameter and should
return a string. The function will be called when
the output buffer is flushed (sent) or cleaned (with
ob_flush(), ob_clean() or similar
function) or when the output buffer
is flushed to the browser at the end of the request. When
output_callback is called, it will receive the
contents of the output buffer as its parameter and is expected to
return a new output buffer as a result, which will be sent to the
browser. If the output_callback is not a
callable function, this function will return FALSE.
This is the callback signature:
$buffer
[, int $phase
] )bufferphasePHP_OUTPUT_HANDLER_* constants.
If output_callback returns FALSE original
input is sent to the browser.
The output_callback parameter may be bypassed
by passing a NULL value.
ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.
Note:
In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.
chunk_size
If the optional parameter chunk_size is passed, the
buffer will be flushed after any output call which causes the buffer's
length to equal or exceed chunk_size. The default
value 0 means that the output function will only be
called when the output buffer is closed.
Prior to PHP 5.4.0, the value 1 was a special case value that set the chunk size to 4096 bytes.
flags
The flags parameter is a bitmask that controls
the operations that can be performed on the output buffer. The default
is to allow output buffers to be cleaned, flushed and removed, which
can be set explicitly via
PHP_OUTPUT_HANDLER_CLEANABLE |
PHP_OUTPUT_HANDLER_FLUSHABLE |
PHP_OUTPUT_HANDLER_REMOVABLE, or
PHP_OUTPUT_HANDLER_STDFLAGS as shorthand.
Each flag controls access to a set of functions, as described below:
| Constant | Functions |
|---|---|
PHP_OUTPUT_HANDLER_CLEANABLE |
ob_clean(), ob_end_clean(), and ob_get_clean(). |
PHP_OUTPUT_HANDLER_FLUSHABLE |
ob_end_flush(), ob_flush(), and ob_get_flush(). |
PHP_OUTPUT_HANDLER_REMOVABLE |
ob_end_clean(), ob_end_flush(), and ob_get_flush(). |
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.4.0 |
The third parameter of ob_start() changed from a
boolean parameter called erase
(which, if set to FALSE, would prevent the output buffer from being
deleted until the script finished executing) to an
integer parameter called flags.
Unfortunately, this results in an API compatibility break for code
written prior to PHP 5.4.0 that uses the third parameter. See
the flags example
for an example of how to handle this with code that needs to be
compatible with both.
|
| 5.4.0 | A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer. |
| 4.3.2 |
This function was changed to return FALSE in case the passed
output_callback can not be executed.
|
| 4.2.0 |
Added the erase parameter.
|
Example #1 User defined callback function example
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
The above example will output:
<html> <body> <p>It's like comparing oranges to oranges.</p> </body> </html>
Example #2 Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4
<?php
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^
PHP_OUTPUT_HANDLER_REMOVABLE);
} else {
ob_start(null, 0, false);
}
?>
(PHP 4 >= 4.3.0, PHP 5)
output_add_rewrite_var — Add URL rewriter values
$name
, string $value
)This function adds another name/value pair to the URL rewrite mechanism. The name and value will be added to URLs (as GET parameter) and forms (as hidden input fields) the same way as the session ID when transparent URL rewriting is enabled with session.use_trans_sid. Please note that absolute URLs (http://example.com/..) aren't rewritten.
This function's behavior is controlled by the url_rewriter.tags php.ini parameter.
Note: Calling this function will implicitly start output buffering if it is not active already.
nameThe variable name.
valueThe variable value.
Returns TRUE on success or FALSE on failure.
Example #1 output_add_rewrite_var() example
<?php
output_add_rewrite_var('var', 'value');
// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';
// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';
print_r(ob_list_handlers());
?>
The above example will output:
<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>
<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>
Array
(
[0] => URL-Rewriter
)
(PHP 4 >= 4.3.0, PHP 5)
output_reset_rewrite_vars — Reset URL rewriter values
This function resets the URL rewriter and removes all rewrite variables previously set by the output_add_rewrite_var() function or the session mechanism (if session.use_trans_sid was set on session_start()).
Returns TRUE on success or FALSE on failure.
Example #1 output_reset_rewrite_vars() example
<?php
session_start();
output_add_rewrite_var('var', 'value');
echo '<a href="file.php">link</a>';
ob_flush();
output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>
The above example will output:
<a href="file.php?PHPSESSID=xxx&var=value">link</a> <a href="file.php">link</a>
This functions enable you to get a lot of information about PHP itself, e.g. runtime configuration, loaded extensions, version and much more. You'll also find functions to set options for your running PHP. The probably best known function of PHP - phpinfo() - can be found here.
No external libraries are needed to build this extension.
There is no installation needed to use these functions; they are part of the PHP core.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| assert.active | "1" | PHP_INI_ALL | |
| assert.bail | "0" | PHP_INI_ALL | |
| assert.warning | "1" | PHP_INI_ALL | |
| assert.callback | NULL | PHP_INI_ALL | |
| assert.quiet_eval | "0" | PHP_INI_ALL | |
| enable_dl | "1" | PHP_INI_SYSTEM | This deprecated feature will certainly be removed in the future. |
| max_execution_time | "30" | PHP_INI_ALL | |
| max_input_time | "-1" | PHP_INI_PERDIR | Available since PHP 4.3.0. |
| max_input_nesting_level | "64" | PHP_INI_PERDIR | Available since PHP 4.4.8 and PHP 5.2.3. |
| max_input_vars | 1000 | PHP_INI_PERDIR | Available since PHP 5.3.9. |
| magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Removed in PHP 5.4.0. |
| magic_quotes_runtime | "0" | PHP_INI_ALL | Removed in PHP 5.4.0. |
| zend.enable_gc | "1" | PHP_INI_ALL | Available since PHP 5.3.0. |
Here's a short explanation of the configuration directives.
assert.active
boolean
Enable assert() evaluation.
assert.bail
boolean
Terminate script execution on failed assertions.
assert.warning
boolean
Issue a PHP warning for each failed assertion.
assert.callback
string
user function to call on failed assertions
assert.quiet_eval
boolean
Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting()
enable_dl
boolean
This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl() on and off per virtual server or per directory.
The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using safe mode. In safe mode, it's always impossible to use dl().
max_execution_time
integer
This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0.
The maximum execution time is not affected by system calls, stream operations etc. Please see the set_time_limit() function for more details.
You can not change this setting with ini_set() when running in safe mode. The only workaround is to turn off safe mode or by changing the time limit in the php.ini.
Your web server can have other timeout configurations that may also interrupt PHP execution. Apache has a Timeout directive and IIS has a CGI timeout function. Both default to 300 seconds. See your web server documentation for specific details.
max_input_time
integer
This sets the maximum time in seconds a script is allowed to parse input data, like POST and GET. Timing begins at the moment PHP is invoked at the server and ends when execution begins.
max_input_nesting_level
integer
Sets the max nesting depth of input variables (i.e. $_GET, $_POST..)
max_input_vars
integer
How many input
variables may be accepted (limit is applied to
$_GET, $_POST and $_COOKIE superglobal separately). Use of this directive
mitigates the possibility of denial of service attacks which use hash collisions.
If there are more input variables than specified by this directive,
an E_WARNING is issued, and further input
variables are truncated from the request.
magic_quotes_gpc
boolean
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.
Note:
In PHP 4, also $_ENV variables are escaped.
Note:
If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped.
See also get_magic_quotes_gpc()
magic_quotes_runtime
boolean
This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
If magic_quotes_runtime is enabled,
most functions that return data from any sort of external
source including databases and text files will have quotes
escaped with a backslash. If
magic_quotes_sybase
is also on, a single-quote is escaped with a single-quote instead
of a backslash.
Functions affected by magic_quotes_runtime
(does not include functions from PECL):
zend.enable_gc
boolean
Enables or disables the circular reference collector.
This extension has no resource types defined.
The constants below are always available as part of the PHP core.
| Constant | Value | Description |
|---|---|---|
CREDITS_GROUP |
1 | A list of the core developers |
CREDITS_GENERAL |
2 | General credits: Language design and concept, PHP authors and SAPI module. |
CREDITS_SAPI |
4 | A list of the server API modules for PHP, and their authors. |
CREDITS_MODULES |
8 | A list of the extension modules for PHP, and their authors. |
CREDITS_DOCS |
16 | The credits for the documentation team. |
CREDITS_FULLPAGE |
32 | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags. |
CREDITS_QA |
64 | The credits for the quality assurance team. |
CREDITS_ALL |
-1 | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value. |
| Constant | Value | Description |
|---|---|---|
INFO_GENERAL |
1 | The configuration line, php.ini location, build date, Web Server, System and more. |
INFO_CREDITS |
2 | PHP Credits. See also phpcredits(). |
INFO_CONFIGURATION |
4 | Current Local and Master values for PHP directives. See also ini_get(). |
INFO_MODULES |
8 | Loaded modules and their respective settings. |
INFO_ENVIRONMENT |
16 | Environment Variable information that's also available in $_ENV. |
INFO_VARIABLES |
32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE |
64 | PHP License information. See also the » license faq. |
INFO_ALL |
-1 | Shows all of the above. This is the default value. |
| Constant | Value | Description |
|---|---|---|
| INI_USER | 1 | Unused |
| INI_PERDIR | 2 | Unused |
| INI_SYSTEM | 4 | Unused |
| INI_ALL | 7 | Unused |
Assert constants, these values are used to set the assertion options in assert_options().
| Constant | INI Setting | Description |
|---|---|---|
ASSERT_ACTIVE |
assert.active | Enable assert() evaluation. |
ASSERT_CALLBACK |
assert.callback | Callback to call on failed assertions. |
ASSERT_BAIL |
assert.bail | Terminate execution on failed assertions. |
ASSERT_WARNING |
assert.warning | Issues a PHP warning for each failed assertion |
ASSERT_QUIET_EVAL |
assert.quiet_eval | Disable error_reporting during assertion expression evaluation. |
The following constants are only available if the host operating system is Windows, and can tell different versioning information so its possible to detect various features and make use of them. They are all available as of PHP 5.3.0.
| Constant | Description |
|---|---|
PHP_WINDOWS_VERSION_MAJOR |
The major version of Windows, this can be either 4 (NT4/Me/98/95), 5 (XP/2003 R2/2003/2000) or 6 (Vista/2008). |
PHP_WINDOWS_VERSION_MINOR |
The minor version of Windows, this can be either 0 (Vista/2008/2000/NT4/95), 1 (XP), 2 (2003 R2/2003/XP x64), 10 (98) or 90 (ME). |
PHP_WINDOWS_VERSION_BUILD |
The Windows build number (for example, Windows Vista with SP1 applied is build 6001) |
PHP_WINDOWS_VERSION_PLATFORM |
The platform that PHP currently is running on, this value is 2 on Windows Vista/XP/2000/NT4, Server 2008/2003 and on Windows ME/98/95 this value is 1. |
PHP_WINDOWS_VERSION_SP_MAJOR |
The major version of the service pack installed, this value is 0 if no service pack is installed. For example, Windows XP with service pack 3 installed will make this value 3. |
PHP_WINDOWS_VERSION_SP_MINOR |
The minor version of the service pack installed, this value is 0 if no service pack is installed. |
PHP_WINDOWS_VERSION_SUITEMASK |
The suitemask is a bitmask that can tell if various features of Windows is installed, see the table below for possible bitfield values. |
PHP_WINDOWS_VERSION_PRODUCTTYPE |
This contains the value used to determine the PHP_WINDOWS_NT_* constants. This value may be one of the PHP_WINDOWS_NT_* constants indicating the platform type. |
PHP_WINDOWS_NT_DOMAIN_CONTROLLER |
This is a domain controller |
PHP_WINDOWS_NT_SERVER |
This is a server system (eg. Server 2008/2003/2000), note that if this is a
domain controller its reported as PHP_WINDOWS_NT_DOMAIN_CONTROLLER.
|
PHP_WINDOWS_NT_WORKSTATION |
This is a workstation system (eg. Vista/XP/2000/NT4) |
This table shows a list of features that can be checked for using the
PHP_WINDOWS_VERSION_SUITEMASK bitmask.
| Bits | Description |
|---|---|
| 0x00000004 | Microsoft BackOffice components are installed. |
| 0x00000400 | Windows Server 2003, Web Edition is installed. |
| 0x00004000 | Windows Server 2003, Compute Cluster Edition is installed. |
| 0x00000080 | Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition or Windows 2000 Datacenter Server is installed. |
| 0x00000002 | Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0 Enterprise Edition is installed. |
| 0x00000040 | Windows XP Embedded is installed. |
| 0x00000200 | Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed. |
| 0x00000100 | Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode. |
| 0x00000001 | Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows. |
| 0x00000020 | Microsoft Small Business Server is installed with the restrictive client license in force. |
| 0x00002000 | Windows Storage Server 2003 R2 or Windows Storage Server 2003 is installed. |
| 0x00000010 | Terminal Services is installed. This value is always set. If this value is set but 0x00000100 is not set, then the system is running in application server mode. |
| 0x00008000 | Windows Home Server is installed. |
(PHP 4, PHP 5)
assert_options — Set/get the various assert flags
Set the various assert() control options or just query their current settings.
what
| Option | INI Setting | Default value | Description |
|---|---|---|---|
| ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation |
| ASSERT_WARNING | assert.warning | 1 | issue a PHP warning for each failed assertion |
| ASSERT_BAIL | assert.bail | 0 | terminate execution on failed assertions |
| ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disable error_reporting during assertion expression evaluation |
| ASSERT_CALLBACK | assert.callback | (NULL) |
Callback to call on failed assertions |
valueAn optional new value for the option.
Returns the original setting of any option or FALSE on errors.
Example #1 assert_options() example
<?php
// This is our function to handle
// assert failures
function assert_failure()
{
echo 'Assert failed';
}
// This is our test function
function test_assert($parameter)
{
assert(is_bool($parameter));
}
// Set our assert options
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_BAIL, true);
assert_options(ASSERT_WARNING, false);
assert_options(ASSERT_CALLBACK, 'assert_failure');
// Make an assert that would fail
test_assert(1);
// This is never reached due to ASSERT_BAIL
// being true
echo 'Never reached';
?>
(PHP 4, PHP 5)
assert — Checks if assertion is FALSE
assert() will check the given
assertion and take appropriate action if
its result is FALSE.
If the assertion is given as a string it
will be evaluated as PHP code by assert().
The advantages of a string assertion are
less overhead when assertion checking is off and messages
containing the assertion expression when
an assertion fails. This means that if you pass a boolean condition
as assertion this condition will not show up as
parameter to the assertion function which you may have defined with the
assert_options() function, the condition is converted
to a string before calling that handler function, and the boolean FALSE
is converted as the empty string.
Assertions should be used as a debugging feature only. You may
use them for sanity-checks that test for conditions that should
always be TRUE and that indicate some programming errors if not
or to check for the presence of certain features like extension
functions or certain system limits and features.
Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.
The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.
The assert_options() function and/or
ASSERT_CALLBACK configuration directive allow a
callback function to be set to handle failed assertions.
assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!
The callback function should accept three arguments. The first
argument will contain the file the assertion failed in. The
second argument will contain the line the assertion failed on and
the third argument will contain the expression that failed (if
any — literal values such as 1 or "two" will not be passed via
this argument). Users of PHP 5.4.8 and later may also provide a fourth
optional argument, which will contain the
description given to assert(), if
it was set.
assertionThe assertion.
description
An optional description that will be included in the failure message if
the assertion fails.
FALSE if the assertion is false, TRUE otherwise.
| Version | Description |
|---|---|
| 5.4.8 |
The description parameter was added. The
description is also now provided to a callback
function in ASSERT_CALLBACK mode as the fourth
argument.
|
Example #1 Handle a failed assertion with a custom handler
<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
// Create a handler function
function my_assert_handler($file, $line, $code)
{
echo "<hr>Assertion Failed:
File '$file'<br />
Line '$line'<br />
Code '$code'<br /><hr />";
}
// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Make an assertion that should fail
assert('mysql_query("")');
?>
Example #2 Using a custom handler to print a description
<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
// Create a handler function
function my_assert_handler($file, $line, $code, $desc = null)
{
echo "Assertion failed at $file:$line: $code";
if ($desc) {
echo ": $desc";
}
echo "\n";
}
// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>
The above example will output:
Assertion failed at test.php:21: 2 < 1 Assertion failed at test.php:22: 2 < 1: Two is less than one
(PHP 5 >= 5.5.0)
cli_get_process_title — Returns the current process title
Returns the current process title, as set by cli_set_process_title(). Note that this may not exactly match what is shown in ps or top, depending on your operating system.
This function is available only in CLI mode.
This function has no parameters.
Return a string with the current process title or NULL on error.
An E_WARNING will be generated if the operating system
is unsupported.
Example #1 cli_get_process_title() example
<?php
echo "Process title: " . cli_get_process_title() . "\n";
?>
(PHP 5 >= 5.5.0)
cli_set_process_title — Sets the process title
$title
)Sets the process title visible in tools such as top and ps. This function is available only in CLI mode.
titleThe new title.
Returns TRUE on success or FALSE on failure.
An E_WARNING will be generated if the operating system
is unsupported.
Example #1 cli_set_process_title() example
<?php
$title = "My Amazing PHP Script";
$pid = getmypid(); // you can use this to see your process title in ps
if (!cli_set_process_title($title)) {
echo "Unable to set process title for PID $pid...\n";
exit(1);
} else {
echo "The process title '$title' for PID $pid has been set for your process!\n";
sleep(5);
}
?>
(PHP 4, PHP 5)
dl — Loads a PHP extension at runtime
$library
)
Loads the PHP extension given by the parameter
library.
Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).
This function has been removed from some SAPIs in PHP 5.3.
libraryThis parameter is only the filename of the extension to load which also depends on your platform. For example, the sockets extension (if compiled as a shared module, not the default!) would be called sockets.so on Unix platforms whereas it is called php_sockets.dll on the Windows platform.
The directory where the extension is loaded from depends on your platform:
Windows - If not explicitly set in the php.ini, the extension is loaded from C:\php4\extensions\ (PHP 4) or C:\php5\ (PHP 5) by default.
Unix - If not explicitly set in the php.ini, the default extension directory depends on
Returns TRUE on success or FALSE on failure. If the functionality of loading modules is not available
or has been disabled (either by setting
enable_dl off or by enabling safe mode
in php.ini) an E_ERROR is emitted
and execution is stopped. If dl() fails because the
specified library couldn't be loaded, in addition to FALSE an
E_WARNING message is emitted.
Example #1 dl() examples
<?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
dl('php_sqlite.dll');
} else {
dl('sqlite.so');
}
}
// Or, the PHP_SHLIB_SUFFIX constant is available as of PHP 4.3.0
if (!extension_loaded('sqlite')) {
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>
| Version | Description |
|---|---|
| 5.3.0 | dl() is now disabled in some SAPIs due to stability issues. The only SAPIs that allow dl() are CLI and Embed. Use the Extension Loading Directives instead. |
Note:
dl() is not supported when PHP is built with ZTS support. Use the Extension Loading Directives instead.
Note:
dl() is case sensitive on Unix platforms.
Note: This function is disabled when PHP is running in safe mode.
(PHP 4, PHP 5)
extension_loaded — Find out whether an extension is loaded
$name
)Finds out whether the extension is loaded.
nameThe extension name.
You can see the names of various extensions by using phpinfo() or if you're using the CGI or CLI version of PHP you can use the -m switch to list all available extensions:
$ php -m [PHP Modules] xml tokenizer standard sockets session posix pcre overload mysql mbstring ctype [Zend Modules]
Returns TRUE if the extension identified by name
is loaded, FALSE otherwise.
Example #1 extension_loaded() example
<?php
if (!extension_loaded('gd')) {
if (!dl('gd.so')) {
exit;
}
}
?>
| Version | Description |
|---|---|
| 5.0.0 | extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extensions available which also use uppercase letters. Prior to PHP 5, this function compared the names case sensitively. |
(PHP 5 >= 5.3.0)
gc_collect_cycles — Forces collection of any existing garbage cycles
Forces collection of any existing garbage cycles.
This function has no parameters.
Returns number of collected cycles.
(PHP 5 >= 5.3.0)
gc_disable — Deactivates the circular reference collector
Deactivates the circular reference collector, setting zend.enable_gc to 0.
This function has no parameters.
No value is returned.
(PHP 5 >= 5.3.0)
gc_enable — Activates the circular reference collector
Activates the circular reference collector, setting zend.enable_gc to 1.
This function has no parameters.
No value is returned.
(PHP 5 >= 5.3.0)
gc_enabled — Returns status of the circular reference collector
Returns status of the circular reference collector.
This function has no parameters.
Returns TRUE if the garbage collector is enabled, FALSE otherwise.
Example #1 A gc_enabled() example
<?php
if(gc_enabled()) gc_collect_cycles();
?>
(PHP 4, PHP 5)
get_cfg_var — Gets the value of a PHP configuration option
$option
)
Gets the value of a PHP configuration option.
This function will not return configuration information set when the PHP was compiled, or read from an Apache configuration file.
To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.
optionThe configuration option name.
Returns the current value of the PHP configuration variable specified by
option, or FALSE if an error occurs.
| Version | Description |
|---|---|
| 5.3.0 | get_cfg_var() was fixed to be able to return "array" ini options. |
(PHP 4, PHP 5)
get_current_user — Gets the name of the owner of the current PHP script
Returns the name of the owner of the current PHP script.
Returns the username as a string.
Example #1 get_current_user() example
<?php
echo 'Current script owner: ' . get_current_user();
?>
The above example will output something similar to:
Current script owner: SYSTEM
(PHP 4 >= 4.1.0, PHP 5)
get_defined_constants — Returns an associative array with the names of all the constants and their values
$categorize = false
] )Returns the names and values of all the constants currently defined. This includes those created by extensions as well as those created with the define() function.
categorizeCausing this function to return a multi-dimensional array with categories in the keys of the first dimension and constants and their values in the second dimension.
<?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?>
The above example will output something similar to:
Array
(
[Core] => Array
(
[E_ERROR] => 1
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_ALL] => 2047
[TRUE] => 1
)
[pcre] => Array
(
[PREG_PATTERN_ORDER] => 1
[PREG_SET_ORDER] => 2
[PREG_OFFSET_CAPTURE] => 256
[PREG_SPLIT_NO_EMPTY] => 1
[PREG_SPLIT_DELIM_CAPTURE] => 2
[PREG_SPLIT_OFFSET_CAPTURE] => 4
[PREG_GREP_INVERT] => 1
)
[user] => Array
(
[MY_CONSTANT] => 1
)
)
Returns an array of constant name => constant value array, optionally groupped by extension name registering the constant.
| Version | Description |
|---|---|
| 5.3.1 | Windows only: Core constants are categorized under Core, previously mhash. |
| 5.3.0 | Core constants are categorized under Core, previously internal. On Windows, the Core Constants are categorized under mhash. |
| 5.2.11 |
The categorize parameter now operates appropriately.
Previously, the categorize parameter was interpreted
as !is_null($categorize), making any value other than NULL
force the constants to be categorized.
|
| 5.0.0 |
The categorize parameter was added.
|
Example #1 get_defined_constants() Example
<?php
print_r(get_defined_constants());
?>
The above example will output something similar to:
Array
(
[E_ERROR] => 1
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_ALL] => 2047
[TRUE] => 1
)
(PHP 4, PHP 5)
get_extension_funcs — Returns an array with the names of the functions of a module
$module_name
)
This function returns the names of all the functions defined in
the module indicated by module_name.
module_nameThe module name.
Note:
This parameter must be in lowercase.
Returns an array with all the functions, or FALSE if
module_name is not a valid extension.
Example #1 Prints the XML functions
<?php
print_r(get_extension_funcs("xml"));
?>
The above example will output something similar to:
Array
(
[0] => xml_parser_create
[1] => xml_parser_create_ns
[2] => xml_set_object
[3] => xml_set_element_handler
[4] => xml_set_character_data_handler
[5] => xml_set_processing_instruction_handler
[6] => xml_set_default_handler
[7] => xml_set_unparsed_entity_decl_handler
[8] => xml_set_notation_decl_handler
[9] => xml_set_external_entity_ref_handler
[10] => xml_set_start_namespace_decl_handler
[11] => xml_set_end_namespace_decl_handler
[12] => xml_parse
[13] => xml_parse_into_struct
[14] => xml_get_error_code
[15] => xml_error_string
[16] => xml_get_current_line_number
[17] => xml_get_current_column_number
[18] => xml_get_current_byte_index
[19] => xml_parser_free
[20] => xml_parser_set_option
[21] => xml_parser_get_option
[22] => utf8_encode
[23] => utf8_decode
)
(PHP 4 >= 4.3.0, PHP 5)
get_include_path — Gets the current include_path configuration option
Gets the current include_path configuration option value.
Returns the path, as a string.
Example #1 get_include_path() example
<?php
// Works as of PHP 4.3.0
echo get_include_path();
// Works in all PHP versions
echo ini_get('include_path');
?>
(PHP 4, PHP 5)
get_included_files — Returns an array with the names of included or required files
Gets the names of all files that have been included using include, include_once, require or require_once.
Returns an array of the names of all files.
The script originally called is considered an "included file," so it will be listed together with the files referenced by include and family.
Files that are included or required multiple times only show up once in the returned array.
| Version | Description |
|---|---|
| 4.0.1 | In PHP 4.0.1 and previous versions this function assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include and include_once. |
Example #1 get_included_files() example
<?php
// This file is abc.php
include 'test1.php';
include_once 'test2.php';
require 'test3.php';
require_once 'test4.php';
$included_files = get_included_files();
foreach ($included_files as $filename) {
echo "$filename\n";
}
?>
The above example will output:
abc.php test1.php test2.php test3.php test4.php
Note:
Files included using the auto_prepend_file configuration directive are not included in the returned array.
(PHP 4, PHP 5)
get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
$zend_extensions = false
] )This function returns the names of all the modules compiled and loaded in the PHP interpreter.
zend_extensions
Only return Zend extensions, if not then regular extensions, like
mysqli are listed. Defaults to FALSE (return regular extensions).
Returns an indexed array of all the modules names.
| Version | Description |
|---|---|
| 5.2.4 |
The optional zend_extensions parameter was added
|
Example #1 get_loaded_extensions() Example
<?php
print_r(get_loaded_extensions());
?>
The above example will output something similar to:
Array ( [0] => xml [1] => wddx [2] => standard [3] => session [4] => posix [5] => pgsql [6] => pcre [7] => gd [8] => ftp [9] => db [10] => calendar [11] => bcmath )
(PHP 4, PHP 5)
get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc
Returns the current configuration setting of magic_quotes_gpc
Keep in mind that attempting to set magic_quotes_gpc at runtime will not work.
For more information about magic_quotes, see this security section.
Returns 0 if magic_quotes_gpc is off, 1 otherwise.
Or always returns FALSE as of PHP 5.4.0.
| Version | Description |
|---|---|
| 5.4.0 |
Always returns FALSE because the magic quotes feature was removed from PHP.
|
Example #1 get_magic_quotes_gpc() example
<?php
// If magic quotes are enabled
echo $_POST['lastname']; // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly
// Usage across all PHP versions
if (get_magic_quotes_gpc()) {
$lastname = stripslashes($_POST['lastname']);
}
else {
$lastname = $_POST['lastname'];
}
// If using MySQL
$lastname = mysql_real_escape_string($lastname);
echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>
Note:
If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns
TRUEneither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''
(PHP 4, PHP 5)
get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
Returns the current active configuration setting of magic_quotes_runtime.
Returns 0 if magic_quotes_runtime is off, 1 otherwise.
Or always returns FALSE as of PHP 5.4.0.
| Version | Description |
|---|---|
| 5.4.0 |
Always returns FALSE because the magic quotes feature was removed from PHP.
|
Example #1 get_magic_quotes_runtime() example
<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
// Deactivate
set_magic_quotes_runtime(false);
}
?>
This function is an alias of: get_included_files().
(PHP 4, PHP 5)
getenv — Gets the value of an environment variable
$varname
)Gets the value of an environment variable.
You can see a list of all the environmental variables by using phpinfo(). Many of these variables are listed within » RFC 3875, specifically section 4.1, "Request Meta-Variables".
varnameThe variable name.
Returns the value of the environment variable
varname, or FALSE if the environment
variable varname does not exist.
Example #1 getenv() Example
<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');
// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?>
(PHP 4, PHP 5)
getlastmod — Gets time of last page modification
Gets the time of the last modification of the main script of execution.
If you're interested in getting the last modification time of a different file, consider using filemtime().
Returns the time of the last modification of the current
page. The value returned is a Unix timestamp, suitable for
feeding to date(). Returns FALSE on error.
Example #1 getlastmod() example
<?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>
(PHP 4 >= 4.1.0, PHP 5)
getmygid — Get PHP script owner's GID
Gets the group ID of the current script.
Returns the group ID of the current script, or FALSE on error.
(PHP 4, PHP 5)
getmyinode — Gets the inode of the current script
Gets the inode of the current script.
Returns the current script's inode as an integer, or FALSE on error.
(PHP 4, PHP 5)
getmypid — Gets PHP's process ID
Gets the current PHP process ID.
Returns the current PHP process ID, or FALSE on error.
Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.
(PHP 4, PHP 5)
getmyuid — Gets PHP script owner's UID
Gets the user ID of the current script.
Returns the user ID of the current script, or FALSE on error.
(PHP 4 >= 4.3.0, PHP 5)
getopt — Gets options from the command line argument list
$options
[, array $longopts
] )Parses options passed to the script.
optionslongopts
The options parameter may contain the following
elements:
Note: Optional values do not accept " " (space) as a separator.
Note:
The format for the
optionsandlongoptsis almost the same, the only difference is thatlongoptstakes an array of options (where each element is the option) whereasoptionstakes a string (where each character is the option).
This function will return an array of option / argument pairs or FALSE on
failure.
Note:
The parsing of options will end at the first non-option found, anything that follows is discarded.
| Version | Description |
|---|---|
| 5.3.0 | Added support for "=" as argument/value separator. |
| 5.3.0 | Added support for optional values (specified with "::"). |
| 5.3.0 |
Parameter longopts is available on all systems.
|
| 5.3.0 | This function is no longer system dependent, and now works on Windows, too. |
Example #1 getopt() example
<?php
$options = getopt("f:hp:");
var_dump($options);
?>
Running the above script with php script.php -fvalue -h will output:
array(2) {
["f"]=>
string(5) "value"
["h"]=>
bool(false)
}
Example #2 getopt() example#2
<?php
$shortopts = "";
$shortopts .= "f:"; // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values
$longopts = array(
"required:", // Required value
"optional::", // Optional value
"option", // No value
"opt", // No value
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>
Running the above script with php script.php -f "value for f" -v -a --required value --optional="optional value" --option will output:
array(6) {
["f"]=>
string(11) "value for f"
["v"]=>
bool(false)
["a"]=>
bool(false)
["required"]=>
string(5) "value"
["optional"]=>
string(14) "optional value"
["option"]=>
bool(false)
}
Example #3 getopt() example#3
Passing multiple options as one
<?php
$options = getopt("abc");
var_dump($options);
?>
Running the above script with php script.php -aaac will output:
array(2) {
["a"]=>
array(3) {
[0]=>
bool(false)
[1]=>
bool(false)
[2]=>
bool(false)
}
["c"]=>
bool(false)
}
(PHP 4, PHP 5)
getrusage — Gets the current resource usages
$who = 0
] )This is an interface to getrusage(2). It gets data returned from the system call.
who
If who is 1, getrusage will be called with
RUSAGE_CHILDREN.
Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names.
Example #1 getrusage() example
<?php
$dat = getrusage();
echo $dat["ru_nswap"]; // number of swaps
echo $dat["ru_majflt"]; // number of page faults
echo $dat["ru_utime.tv_sec"]; // user time used (seconds)
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)
?>
Note: This function is not implemented on Windows platforms.
This function is an alias of: ini_set().
(PHP 4 >= 4.2.0, PHP 5)
ini_get_all — Gets all configuration options
$extension
[, bool $details = true
]] )Returns all the registered configuration options.
extensionAn optional extension name. If set, the function return only options specific for that extension.
details
Retrieve details settings or only the current value for each setting.
Default is TRUE (retrieve details).
Returns an associative array with directive name as the array key.
When details is TRUE (default) the array will
contain global_value (set in
php.ini), local_value (perhaps set with
ini_set() or .htaccess), and
access (the access level).
When details is FALSE the value will be the
current value of the option.
See the manual section for information on what access levels mean.
Note:
It's possible for a directive to have multiple access levels, which is why access shows the appropriate bitmask values.
| Version | Description |
|---|---|
| 5.3.0 |
Added details.
|
Example #1 ini_get_all() examples
<?php
print_r(ini_get_all("pcre"));
print_r(ini_get_all());
?>
The above example will output something similar to:
Array
(
[pcre.backtrack_limit] => Array
(
[global_value] => 100000
[local_value] => 100000
[access] => 7
)
[pcre.recursion_limit] => Array
(
[global_value] => 100000
[local_value] => 100000
[access] => 7
)
)
Array
(
[allow_call_time_pass_reference] => Array
(
[global_value] => 0
[local_value] => 0
[access] => 6
)
[allow_url_fopen] => Array
(
[global_value] => 1
[local_value] => 1
[access] => 4
)
...
)
Example #2 Disabling details
<?php
print_r(ini_get_all("pcre", false)); // Added in PHP 5.3.0
print_r(ini_get_all(null, false)); // Added in PHP 5.3.0
?>
The above example will output something similar to:
Array
(
[pcre.backtrack_limit] => 100000
[pcre.recursion_limit] => 100000
)
Array
(
[allow_call_time_pass_reference] => 0
[allow_url_fopen] => 1
...
)
(PHP 4, PHP 5)
ini_get — Gets the value of a configuration option
$varname
)Returns the value of the configuration option on success.
varnameThe configuration option name.
Returns the value of the configuration option as a string on success, or an
empty string for null values. Returns FALSE if the
configuration option doesn't exist.
Example #1 A few ini_get() examples
<?php
/*
Our php.ini contains the following settings:
display_errors = On
register_globals = Off
post_max_size = 8M
*/
echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
?>
The above example will output something similar to:
display_errors = 1 register_globals = 0 post_max_size = 8M post_max_size+1 = 9 post_max_size in bytes = 8388608
Note: When querying boolean values
A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on will be returned as "1". The function can also return the literal string of INI value.
Note: When querying memory size values
Many ini memory size values, such as upload_max_filesize, are stored in the php.ini file in shorthand notation. ini_get() will return the exact string stored in the php.ini file and NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it.
| Version | Description |
|---|---|
| 5.3.0 | Previously, the empty string was returned if the configuration
option didn't exist. now, FALSE is returned instead.
|
(PHP 4, PHP 5)
ini_restore — Restores the value of a configuration option
$varname
)Restores a given configuration option to its original value.
varnameThe configuration option name.
No value is returned.
Example #1 ini_restore() example
<?php
$setting = 'y2k_compliance';
echo 'Current value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
ini_set($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>
The above example will output:
Current value for 'y2k_compliance': 1 New value for 'y2k_compliance': 0 Original value for 'y2k_compliance': 1
(PHP 4, PHP 5)
ini_set — Sets the value of a configuration option
$varname
, string $newvalue
)Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.
varname
Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.
newvalueThe new value for the option.
Returns the old value on success, FALSE on failure.
Example #1 Setting an ini option
<?php
echo ini_get('display_errors');
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
echo ini_get('display_errors');
?>
This function is an alias of: set_magic_quotes_runtime()
main — Dummy for main()
There is no function named main() except in the PHP source. In PHP 4.3.0, a new type of error handling in the PHP source (php_error_docref) was introduced. One feature is to provide links to a manual page in PHP error messages when the PHP directives html_errors (on by default) and docref_root (on by default until PHP 4.3.2) are set.
Sometimes error messages refer to a manual page for the function main() which is why this page exists. If you discover such a reference, please » file a bug report, indicating the PHP function caused the error that linked to main() and it will be fixed and properly documented.
| Function name | No longer points here as of |
|---|---|
| include | 5.1.0 |
| include_once | 5.1.0 |
| require | 5.1.0 |
| require_once | 5.1.0 |
(PHP 5 >= 5.2.0)
memory_get_peak_usage — Returns the peak of memory allocated by PHP
$real_usage = false
] )Returns the peak of memory, in bytes, that's been allocated to your PHP script.
real_usage
Set this to TRUE to get the real size of memory allocated from
system. If not set or FALSE only the memory used by
emalloc() is reported.
Returns the memory peak in bytes.
| Version | Description |
|---|---|
| 5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist. |
| 5.2.0 |
real_usage was added.
|
(PHP 4 >= 4.3.2, PHP 5)
memory_get_usage — Returns the amount of memory allocated to PHP
$real_usage = false
] )Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.
real_usage
Set this to TRUE to get the real size of memory allocated from
system. If not set or FALSE only the memory used by
emalloc() is reported.
Returns the memory amount in bytes.
| Version | Description |
|---|---|
| 5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist. |
| 5.2.0 |
real_usage was added.
|
Example #1 A memory_get_usage() example
<?php
// This is only an example, the numbers below will
// differ depending on your system
echo memory_get_usage() . "\n"; // 36640
$a = str_repeat("Hello", 4242);
echo memory_get_usage() . "\n"; // 57960
unset($a);
echo memory_get_usage() . "\n"; // 36744
?>
(PHP 5 >= 5.2.4)
php_ini_loaded_file — Retrieve a path to the loaded php.ini file
Check if a php.ini file is loaded, and retrieve its path.
This function has no parameters.
The loaded php.ini path, or FALSE if one is not loaded.
Example #1 php_ini_loaded_file() example
<?php
$inipath = php_ini_loaded_file();
if ($inipath) {
echo 'Loaded php.ini: ' . $inipath;
} else {
echo 'A php.ini file is not loaded';
}
?>
The above example will output something similar to:
Loaded php.ini: /usr/local/php/php.ini
(PHP 4 >= 4.3.0, PHP 5)
php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. These files are found in a directory defined by the --with-config-file-scan-dir option which is set during compilation.
The returned configuration files also include the path as declared in the --with-config-file-scan-dir option.
Returns a comma-separated string of .ini files on success. Each comma is
followed by a newline. If the directive --with-config-file-scan-dir
wasn't set,
FALSE is returned. If it was set and the directory was empty, an
empty string is returned. If a file is unrecognizable, the file will
still make it into the returned string but a PHP error will also result.
This PHP error will be seen both at compile time and while using
php_ini_scanned_files().
Example #1 A simple example to list the returned ini files
<?php
if ($filelist = php_ini_scanned_files()) {
if (strlen($filelist) > 0) {
$files = explode(',', $filelist);
foreach ($files as $file) {
echo "<li>" . trim($file) . "</li>\n";
}
}
}
?>
(PHP 4, PHP 5 < 5.5)
php_logo_guid — Gets the logo guid
This function returns the ID which can be used to display the PHP logo using the built-in image. Logo is displayed only if expose_php is On.
This function has been DEPRECATED and REMOVED as of PHP 5.5.0.
Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.
| Version | Description |
|---|---|
| 5.5.0 | php_logo_guid() has been removed from PHP. |
Example #1 php_logo_guid() example
<?php
echo '<img src="' . $_SERVER['PHP_SELF'] .
'?=' . php_logo_guid() . '" alt="PHP Logo !" />';
?>
(PHP 4 >= 4.0.1, PHP 5)
php_sapi_name — Returns the type of interface between web server and PHP
Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values depending on the exact SAPI used. Possible values are listed below.
Returns the interface type, as a lowercase string.
Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
Example #1 php_sapi_name() example
This example checks for the substring cgi because it may also be cgi-fcgi.
<?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
echo "You are using CGI PHP\n";
} else {
echo "You are not using CGI PHP\n";
}
?>
Note: An alternative approach
The PHP constant
PHP_SAPIhas the same value as php_sapi_name().
The defined SAPI may not be obvious, because for example instead of apache it may be defined as apache2handler or apache2filter.
(PHP 4 >= 4.0.2, PHP 5)
php_uname — Returns information about the operating system PHP is running on
$mode = "a"
] )
php_uname() returns a description of the operating
system PHP is running on. This is the same string you see at the very
top of the phpinfo() output. For the name of just
the operating system, consider using the PHP_OS
constant, but keep in mind this constant will contain the operating
system PHP was built on.
On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work.
mode
mode is a single character that defines what
information is returned:
Returns the description, as a string.
Example #1 Some php_uname() examples
<?php
echo php_uname();
echo PHP_OS;
/* Some possible outputs:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux
FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD
Windows NT XN1 5.1 build 2600
WINNT
*/
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!';
}
?>
There are also some related Predefined PHP constants that may come in handy, for example:
Example #2 A few OS related constant examples
<?php
// *nix
echo DIRECTORY_SEPARATOR; // /
echo PHP_SHLIB_SUFFIX; // so
echo PATH_SEPARATOR; // :
// Win*
echo DIRECTORY_SEPARATOR; // \
echo PHP_SHLIB_SUFFIX; // dll
echo PATH_SEPARATOR; // ;
?>
(PHP 4, PHP 5)
phpcredits — Prints out the credits for PHP
$flag = CREDITS_ALL
] )This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate HTML codes to insert the information in a page.
flag
To generate a custom credits page, you may want to use the
flag parameter.
| name | description |
|---|---|
| CREDITS_ALL |
All the credits, equivalent to using: CREDITS_DOCS +
CREDITS_GENERAL + CREDITS_GROUP +
CREDITS_MODULES + CREDITS_FULLPAGE.
It generates a complete stand-alone HTML page with the appropriate tags.
|
| CREDITS_DOCS | The credits for the documentation team |
| CREDITS_FULLPAGE | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags. |
| CREDITS_GENERAL | General credits: Language design and concept, PHP authors and SAPI module. |
| CREDITS_GROUP | A list of the core developers |
| CREDITS_MODULES | A list of the extension modules for PHP, and their authors |
| CREDITS_SAPI | A list of the server API modules for PHP, and their authors |
Returns TRUE on success or FALSE on failure.
Example #1 Prints the general credits
<?php
phpcredits(CREDITS_GENERAL);
?>
Example #2 Prints the core developers and the documentation group
<?php
phpcredits(CREDITS_GROUP | CREDITS_DOCS | CREDITS_FULLPAGE);
?>
Example #3 Printing all the credits
<html>
<head>
<title>My credits page</title>
</head>
<body>
<?php
// some code of your own
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);
// some more code
?>
</body>
</html>
Note:
phpcredits() outputs plain text instead of HTML when using the CLI mode.
(PHP 4, PHP 5)
phpinfo — Outputs information about PHP's configuration
$what = INFO_ALL
] )Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.
Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system.
phpinfo() is also a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.
what
The output may be customized by passing one or more of the
following constants bitwise values summed
together in the optional what parameter.
One can also combine the respective constants or bitwise values
together with the or operator.
| Name (constant) | Value | Description |
|---|---|---|
| INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more. |
| INFO_CREDITS | 2 | PHP Credits. See also phpcredits(). |
| INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get(). |
| INFO_MODULES | 8 | Loaded modules and their respective settings. See also get_loaded_extensions(). |
| INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV. |
| INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). |
| INFO_LICENSE | 64 | PHP License information. See also the » license FAQ. |
| INFO_ALL | -1 | Shows all of the above. |
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| 5.5.0 | Logo GUIDs were replaced with data URIs, and so turning off expose_php now has no effect on the result of phpinfo(). Credits are also now embedded within the output itself instead of linked. |
| 5.2.2 | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed. |
Example #1 phpinfo() Example
<?php
// Show all information, defaults to INFO_ALL
phpinfo();
// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);
?>
Note:
In versions of PHP before 5.5, parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.
Note:
phpinfo() outputs plain text instead of HTML when using the CLI mode.
(PHP 4, PHP 5)
phpversion — Gets the current PHP version
$extension
] )Returns a string containing the version of the currently running PHP parser or extension.
extensionAn optional extension name.
If the optional extension parameter is
specified, phpversion() returns the version of that
extension, or FALSE if there is no version information associated or
the extension isn't enabled.
Example #1 phpversion() example
<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();
// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>
Example #2 PHP_VERSION_ID example and usage
<?php
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}
// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7
if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);
// and so on, ...
}
?>
Note:
This information is also available in the predefined constant
PHP_VERSION. More versioning information is available using thePHP_VERSION_*constants.
(PHP 4, PHP 5)
putenv — Sets the value of an environment variable
$setting
)
Adds setting to the server environment. The
environment variable will only exist for the duration of the current
request. At the end of the request the environment is restored to its
original state.
Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!
The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.
settingThe setting, like "FOO=BAR"
Returns TRUE on success or FALSE on failure.
Example #1 Setting an environment variable
<?php
putenv("UNIQID=$uniqid");
?>
The safe_mode_allowed_env_vars and safe_mode_protected_env_vars directives only take effect when safe_mode is enabled.
(PHP 4 >= 4.3.0, PHP 5)
restore_include_path — Restores the value of the include_path configuration option
Restores the include_path configuration option back to its original master value as set in php.ini
No value is returned.
Example #1 restore_include_path() example
<?php
echo get_include_path(); // .:/usr/local/lib/php
set_include_path('/inc');
echo get_include_path(); // /inc
// Works as of PHP 4.3.0
restore_include_path();
// Works in all PHP versions
ini_restore('include_path');
echo get_include_path(); // .:/usr/local/lib/php
?>
(PHP 4 >= 4.3.0, PHP 5)
set_include_path — Sets the include_path configuration option
$new_include_path
)Sets the include_path configuration option for the duration of the script.
Returns the old include_path on
success or FALSE on failure.
Example #1 set_include_path() example
<?php
// Works as of PHP 4.3.0
set_include_path('/usr/lib/pear');
// Works in all PHP versions
ini_set('include_path', '/usr/lib/pear');
?>
Example #2 Adding to the include path
Making use of the PATH_SEPARATOR constant, it is
possible to extend the include path regardless of the operating system.
In this example we add /usr/lib/pear to the end of the existing include_path.
<?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>
(PHP 4, PHP 5)
set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
$new_setting
)Set the current active configuration setting of magic_quotes_runtime.
This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
Since PHP 5.3 this function has been deprecated and will raise an E_DEPRECATED warning upon execution. Since PHP 5.4 this function will also raise an E_CORE_ERROR on trying to enable magic quotes.
new_setting
FALSE for off, TRUE for on.
Returns TRUE on success or FALSE on failure.
Example #1 set_magic_quotes_runtime() example
<?php
// Create a temporary file pointer
$fp = tmpfile();
// Write some data to the pointer
fwrite($fp, '\'PHP\' is a Recursive acronym');
// Without magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(false);
echo 'Without magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;
// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);
echo 'With magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;
// Clean up
fclose($fp);
?>
The above example will output:
Without magic_quotes_runtime: 'PHP' is a Recursive acronym With magic_quotes_runtime: \'PHP\' is a Recursive acronym
(PHP 4, PHP 5)
set_time_limit — Limits the maximum execution time
$seconds
)Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
secondsThe maximum execution time, in seconds. If set to zero, no time limit is imposed.
No value is returned.
This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.
Note:
The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.
(PHP 5 >= 5.2.1)
sys_get_temp_dir — Returns directory path used for temporary files
Returns the path of the directory PHP stores temporary files in by default.
Returns the path of the temporary directory.
Example #1 sys_get_temp_dir() example
<?php
// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');
echo $temp_file;
?>
The above example will output something similar to:
C:\Windows\Temp\TuxA318.tmp
(PHP 4 >= 4.1.0, PHP 5)
version_compare — Compares two "PHP-standardized" version number strings
version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.
The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state.
version1First version number.
version2Second version number.
operator
If you specify the third optional operator
argument, you can test for a particular relationship. The
possible operators are: <,
lt, <=,
le, >,
gt, >=,
ge, ==,
=, eq,
!=, <>,
ne respectively.
This parameter is case-sensitive, so values should be lowercase.
By default, version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and 1 if the second is lower.
When using the optional operator argument, the
function will return TRUE if the relationship is the one specified
by the operator, FALSE otherwise.
The examples below use the PHP_VERSION constant,
because it contains the value of the PHP version that is executing
the code.
Example #1 version_compare() examples
<?php
if (version_compare(PHP_VERSION, '6.0.0') >= 0) {
echo 'I am at least PHP version 6.0.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
echo 'I am using PHP 5, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
echo 'I am using PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>
Note:
The
PHP_VERSIONconstant holds current PHP version.
Note:
Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0).
Note:
Special version strings such as alpha and beta are case sensitive. Version strings from arbitrary sources that do not adhere to the PHP standard may need to be lowercased via strtolower() before calling version_compare().
(PHP 4, PHP 5 < 5.5)
zend_logo_guid — Gets the Zend guid
This function returns the ID which can be used to display the Zend logo using the built-in image.
This function has been DEPRECATED and REMOVED as of PHP 5.5.0.
Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.
| Version | Description |
|---|---|
| 5.5.0 | zend_logo_guid() has been removed from PHP. |
Example #1 zend_logo_guid() example
<?php
echo '<img src="' . $_SERVER['PHP_SELF'] .
'?=' . zend_logo_guid() . '" alt="Zend Logo !" />';
?>
(PHP 5)
zend_thread_id — Returns a unique identifier for the current thread
This function returns a unique identifier for the current thread.
Returns the thread id as an integer.
Example #1 zend_thread_id() example
<?php
$thread_id = zend_thread_id();
echo 'Current thread id is: ' . $thread_id;
?>
The above example will output something similar to:
Current thread id is: 7864
Note:
This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (--enable-debug).
(PHP 4, PHP 5)
zend_version — Gets the version of the current Zend engine
Returns a string containing the version of the currently running Zend Engine.
Returns the Zend Engine version number, as a string.
Example #1 zend_version() example
<?php
echo "Zend engine version: " . zend_version();
?>
The above example will output something similar to:
Zend engine version: 2.2.0
The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.
This package is meant as a feature added replacement for the » classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
RUNKIT_IMPORT_FUNCTIONS
(integer)
RUNKIT_IMPORT_CLASS_METHODS
(integer)
RUNKIT_IMPORT_CLASS_CONSTS
(integer)
RUNKIT_IMPORT_CLASS_PROPS
(integer)
RUNKIT_IMPORT_CLASSES
(integer)
RUNKIT_IMPORT_CLASS_*
constants.
RUNKIT_IMPORT_OVERRIDE
(integer)
RUNKIT_ACC_PUBLIC
(integer)
RUNKIT_ACC_PROTECTED
(integer)
RUNKIT_ACC_PRIVATE
(integer)
CLASSKIT_ACC_PUBLIC
(integer)
CLASSKIT_ACC_PROTECTED
(integer)
CLASSKIT_ACC_PRIVATE
(integer)
CLASSKIT_AGGREGATE_OVERRIDE
(integer)
RUNKIT_VERSION
(string)
CLASSKIT_VERSION
(string)
Modifying Constants, Functions, Classes, and Methods works with all releases of PHP 4 and PHP 5. No special requirements are necessary.
Custom Superglobals are only available in PHP 4.2.0 or later.
Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/runkit.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| runkit.superglobal | "" | PHP_INI_PERDIR | |
| runkit.internal_override | "0" | PHP_INI_SYSTEM |
Here's a short explanation of the configuration directives.
runkit.superglobal
string
Example #1 Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
<?php
function show_values() {
echo "Foo is $_FOO\n";
echo "Bar is $_BAR\n";
echo "Baz is $_BAZ\n";
}
$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';
/* Displays foo and bar, but not baz */
show_values();
?>
runkit.internal_override
boolean
This extension has no resource types defined.
(PECL runkit >= 0.7.0)
Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.
$options
] )
options is an associative array containing
any combination of the special ini options listed below.
safe_modeIf the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.
safe_mode_gidIf the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.
safe_mode_include_dirIf the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.
open_basedir
open_basedir may be set to any path below the
current setting of open_basedir. If
open_basedir is not set within the global scope,
then it is assumed to be the root directory and may be set to any location.
allow_url_fopen
Like safe_mode, this setting can only be made more restrictive,
in this case by setting it to FALSE when it is previously set to TRUE
disable_functionsComma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.
disable_classesComma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.
runkit.superglobalComma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.
runkit.internal_overrideIni option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.
Example #1 Instantiating a restricted sandbox
<?php
$options = array(
'safe_mode'=>true,
'open_basedir'=>'/var/www/users/jdoe/',
'allow_url_fopen'=>'false',
'disable_functions'=>'exec,shell_exec,passthru,system',
'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>
All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.
Example #2 Working with variables in a sandbox
<?php
$sandbox = new Runkit_Sandbox();
$sandbox->foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>
The above example will output:
bar barbaz bool(false)
Any function defined within the sandbox may be called as a method on the sandbox object. This also includes a few pseudo-function language constructs: eval(), include, include_once, require, require_once, echo, print, die(), and exit().
Example #3 Calling sandbox functions
<?php
$sandbox = new Runkit_Sandbox();
echo $sandbox->str_replace('a','f','abc');
?>
The above example will output:
fbc
When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.
Example #4 Passing arguments to sandbox functions
<?php
$sandbox = new Runkit_Sandbox();
$foo = 'bar';
$sandbox->foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>
The above example will output:
bar baz
As of runkit version 0.5, certain Sandbox settings may
be modified on the fly using ArrayAccess syntax.
Some settings, such as active
are read-only and meant to provide status information.
Other settings, such as output_handler
may be set and read much like a normal array offset.
Future settings may be write-only, however no such
settings currently exist.
| Setting | Type | Purpose | Default |
|---|---|---|---|
| active | Boolean (Read Only) |
TRUE if the Sandbox is still in a usable state,
FALSE if the request is in bailout due to a
call to die(), exit(), or because of a fatal
error condition.
|
TRUE (Initial) |
| output_handler | Callback | When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. | None |
| parent_access | Boolean | May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. | FALSE |
| parent_read | Boolean | May the sandbox read variables in its parent's context? | FALSE |
| parent_write | Boolean | May the sandbox modify variables in its parent's context? | FALSE |
| parent_eval | Boolean | May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS | FALSE |
| parent_include | Boolean | May the sandbox include php code files in its parent's context? DANGEROUS | FALSE |
| parent_echo | Boolean | May the sandbox echo data in its parent's context effectively bypassing its own output_handler? | FALSE |
| parent_call | Boolean | May the sandbox call functions in its parent's context? | FALSE |
| parent_die | Boolean | May the sandbox kill its own parent? (And thus itself) | FALSE |
| parent_scope | Integer | What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceding calling scope, 3 == The scope before that, etc..., etc... | 0 (Global) |
| parent_scope | String | When parent_scope is set to a string value, it refers to a named array variable in the global scope. If the named variable does not exist at the time of access it will be created as an empty array. If the variable exists but it not an array, a dummy array will be created containing a reference to the named global variable. |
(PECL runkit >= 0.7.0)
Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.
In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.
Example #1 Working with variables in a sandbox
<?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>
Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.
Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.
Example #2 Accessing parental variables
<?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;
$test = "Global";
$php->eval('$PARENT = new Runkit_Sandbox_Parent;');
$php['parent_scope'] = 0;
one();
$php['parent_scope'] = 1;
one();
$php['parent_scope'] = 2;
one();
$php['parent_scope'] = 3;
one();
$php['parent_scope'] = 4;
one();
$php['parent_scope'] = 5;
one();
function one() {
$test = "one()";
two();
}
function two() {
$test = "two()";
three();
}
function three() {
$test = "three()";
$GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>
The above example will output:
string(6) "Global" string(7) "three()" string(5) "two()" string(5) "one()" string(6) "Global" string(6) "Global"
Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print and echo are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include, include_once, require, and require_once are enabled through parent_include.
(PECL runkit >= 0.7.0)
runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
$classname
, string $parentname
)
classnameName of class to be adopted
parentnameParent class which child class is extending
Returns TRUE on success or FALSE on failure.
Example #1 A runkit_class_adopt() example
<?php
class myParent {
function parentFunc() {
echo "Parent Function Output\n";
}
}
class myChild {
}
runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>
The above example will output:
Parent Function Output
(PECL runkit >= 0.7.0)
runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
$classname
)
classnameName of class to emancipate
Returns TRUE on success or FALSE on failure.
Example #1 A runkit_class_emancipate() example
<?php
class myParent {
function parentFunc () {
echo "Parent Function Output\n";
}
}
class myChild extends myParent {
}
myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>
The above example will output:
Parent Function Output Fatal error: Call to undefined function: parentFunc() in example.php on line 12
(PECL runkit >= 0.7.0)
runkit_constant_add — Similar to define(), but allows defining in class definitions as well
constnameName of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.
valueNULL, Bool, Long, Double, String, or Resource value to store in the new constant.
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_constant_redefine — Redefine an already defined constant
constnameConstant to redefine. Either string indicating global constant, or classname::constname indicating class constant.
newvalueNew value to assign to constant.
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_constant_remove — Remove/Delete an already defined constant
$constname
)
constnameName of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_function_add — Add a new function, similar to create_function()
$funcname
, string $arglist
, string $code
)
funcnameName of function to be created
arglistComma separated argument list
codeCode making up the function
Returns TRUE on success or FALSE on failure.
Example #1 A runkit_function_add() example
<?php
runkit_function_add('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>
The above example will output:
The value of a is 1 The value of b is 2
(PECL runkit >= 0.7.0)
runkit_function_copy — Copy a function to a new function name
$funcname
, string $targetname
)
funcnameName of existing function
targetnameName of new function to copy definition to
Returns TRUE on success or FALSE on failure.
Example #1 A runkit_function_copy() example
<?php
function original() {
echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>
The above example will output:
In a function In a function
(PECL runkit >= 0.7.0)
runkit_function_redefine — Replace a function definition with a new implementation
$funcname
, string $arglist
, string $code
)Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.
funcnameName of function to redefine
arglistNew list of arguments to be accepted by function
codeNew code implementation
Returns TRUE on success or FALSE on failure.
Example #1 A runkit_function_redefine() example
<?php
function testme() {
echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>
The above example will output:
Original Testme Implementation New Testme Implementation
(PECL runkit >= 0.7.0)
runkit_function_remove — Remove a function definition
$funcname
)Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.
funcnameName of function to be deleted
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_function_rename — Change a function's name
$funcname
, string $newname
)Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.
funcnameCurrent function name
newnameNew function name
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
$filename
[, int $flags = RUNKIT_IMPORT_CLASS_METHODS
] )
Similar to include however any code residing outside
of a function or class is simply ignored.
Additionally, depending on the value of flags,
any functions or classes which already exist in the currently running environment
will be automatically overwritten by their new definitions.
filenameFilename to import function and class definitions from
flags
Bitwise OR of the RUNKIT_IMPORT_* family of constants.
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_lint_file — Check the PHP syntax of the specified file
$filename
)The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.
filenameFile containing PHP Code to be lint checked
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_lint — Check the PHP syntax of the specified php code
$code
)The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the command line except runkit_lint() accepts actual code rather than a filename.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.
codePHP Code to be lint checked
Returns TRUE on success or FALSE on failure.
(PECL runkit >= 0.7.0)
runkit_method_add — Dynamically adds a new method to a given class
$classname
, string $methodname
, string $args
, string $code
[, int $flags = RUNKIT_ACC_PUBLIC
] )This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
classnameThe class to which this method will be added
methodnameThe name of the method to add
argsComma-delimited list of arguments for the newly-created method
code
The code to be evaluated when methodname
is called
flags
The type of method to create, can be
RUNKIT_ACC_PUBLIC,
RUNKIT_ACC_PROTECTED or
RUNKIT_ACC_PRIVATE
Note:
This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Returns TRUE on success or FALSE on failure.
Example #1 runkit_method_add() example
<?php
class Example {
function foo() {
echo "foo!\n";
}
}
// create an Example object
$e = new Example();
// Add a new public method
runkit_method_add(
'Example',
'add',
'$num1, $num2',
'return $num1 + $num2;',
RUNKIT_ACC_PUBLIC
);
// add 12 + 4
echo $e->add(12, 4);
?>
The above example will output:
16
(PECL runkit >= 0.7.0)
runkit_method_copy — Copies a method from class to another
$dClass
, string $dMethod
, string $sClass
[, string $sMethod
] )This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
dClassDestination class for copied method
dMethodDestination method name
sClassSource class of the method to copy
sMethod
Name of the method to copy from the source class. If this parameter is
omitted, the value of dMethod is assumed.
Returns TRUE on success or FALSE on failure.
Example #1 runkit_method_copy() example
<?php
class Foo {
function example() {
return "foo!\n";
}
}
class Bar {
// initially, no methods
}
// copy the example() method from the Foo class to the Bar class, as baz()
runkit_method_copy('Bar', 'baz', 'Foo', 'example');
// output copied function
echo Bar::baz();
?>
The above example will output:
foo!
(PECL runkit >= 0.7.0)
runkit_method_redefine — Dynamically changes the code of the given method
$classname
, string $methodname
, string $args
, string $code
[, int $flags = RUNKIT_ACC_PUBLIC
] )Note: This function cannot be used to manipulate the currently running (or chained) method.
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
classnameThe class in which to redefine the method
methodnameThe name of the method to redefine
argsComma-delimited list of arguments for the redefined method
code
The new code to be evaluated when methodname
is called
flags
The redefined method can be
RUNKIT_ACC_PUBLIC,
RUNKIT_ACC_PROTECTED or
RUNKIT_ACC_PRIVATE
Note:
This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Returns TRUE on success or FALSE on failure.
Example #1 runkit_method_redefine() example
<?php
class Example {
function foo() {
return "foo!\n";
}
}
// create an Example object
$e = new Example();
// output Example::foo() (before redefine)
echo "Before: " . $e->foo();
// Redefine the 'foo' method
runkit_method_redefine(
'Example',
'foo',
'',
'return "bar!\n";',
RUNKIT_ACC_PUBLIC
);
// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>
The above example will output:
Before: foo! After: bar!
(PECL runkit >= 0.7.0)
runkit_method_remove — Dynamically removes the given method
$classname
, string $methodname
)Note: This function cannot be used to manipulate the currently running (or chained) method.
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
classnameThe class in which to remove the method
methodnameThe name of the method to remove
Returns TRUE on success or FALSE on failure.
Example #1 runkit_method_remove() example
<?php
class Example {
function foo() {
return "foo!\n";
}
function bar() {
return "bar!\n";
}
}
// Remove the 'foo' method
runkit_method_remove(
'Example',
'foo'
);
echo implode(' ', get_class_methods('Example'));
?>
The above example will output:
bar
(PECL runkit >= 0.7.0)
runkit_method_rename — Dynamically changes the name of the given method
$classname
, string $methodname
, string $newname
)Note: This function cannot be used to manipulate the currently running (or chained) method.
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
classnameThe class in which to rename the method
methodnameThe name of the method to rename
newnameThe new name to give to the renamed method
Returns TRUE on success or FALSE on failure.
Example #1 runkit_method_rename() example
<?php
class Example {
function foo() {
return "foo!\n";
}
}
// Rename the 'foo' method to 'bar'
runkit_method_rename(
'Example',
'foo',
'bar'
);
// output renamed function
echo Example::bar();
?>
The above example will output:
foo!
(PECL runkit >= 0.8.0)
runkit_return_value_used — Determines if the current functions return value will be used
Returns TRUE if the function's return value is used by the calling scope,
otherwise FALSE
Example #1 runkit_return_value_used() example
<?php
function foo() {
var_dump(runkit_return_value_used());
}
foo();
$f = foo();
?>
The above example will output:
bool(false) bool(true)
(PECL runkit >= 0.7.0)
runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
Ordinarily, anything output (such as with echo or print) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.
Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.
Note: Deprecated
As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.
sandboxObject instance of Runkit_Sandbox class on which to set output handling.
callback
Name of a function which expects one parameter.
Output generated by sandbox will be passed
to this callback. Anything returned by the callback will be displayed
normally. If this parameter is not passed then output handling will not be changed.
If a non-truth value is passed, output handling will be disabled and will revert to
direct display.
Returns the name of the previously defined output handler callback, or
FALSE if no handler was previously defined.
Example #1 Feeding output to a variable
<?php
function capture_output($str) {
$GLOBALS['sandbox_output'] .= $str;
return '';
}
$sandbox_output = '';
$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);
echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>
The above example will output:
Sandbox Complete Hello string(9) "Excuse me" I lost myself.
(PECL runkit >= 0.7.0)
runkit_superglobals — Return numerically indexed array of registered superglobals
Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES
The scream extension gives the possibility to disable the silencing error control operator so all errors are being reported. This feature is controlled by an ini setting.
PHP version 5.2.0 or greater.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/scream
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| scream.enabled | Off | PHP_INI_ALL |
Here's a short explanation of the configuration directives.
scream.enabled
int
Whether or not to enable scream.
This extension has no resource types defined.
This example demonstrates how scream affects the behaviour of PHP's error handler.
Example #1 Enabling and disabling scream at runtime
<?php
// Make sure errors will be shown
ini_set('display_errors', true);
error_reporting(E_ALL);
// Disable scream - this is the default and produce an error
ini_set('scream.enabled', false);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');
// Now enable scream and try again
ini_set('scream.enabled', true);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/another-not-existing-file', 'r');
?>
The above example will output something similar to:
Opening http://example.com/not-existing-file Opening http://example.com/not-existing-file Warning: fopen(http://example.com/another-not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14
Note: Usually one would set this in the php.ini configuration file instead of changing the code.
The uopz - User Operations for Zend - extension exposes Zend Engine functionality normally used at compilation and execution time in order to allow modification of the internal structures that represent PHP code, and for user code to interact with the VM.
uopz supports the following activities:
Note:
All of the activities supported are compatible with opcache
uopz requires 5.4+
uopz releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » http://pecl.php.net/package/uopz.
Windows users can download prebuilt release binaries from the » PECL website.
uopz must be loaded as a zend_extension
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The following opcodes are defined as constants by uopz:
ZEND_EXIT
(integer)
TRUE to exit, FALSE to continue
ZEND_NEW
(integer)
ZEND_THROW
(integer)
ZEND_ADD_TRAIT
(integer)
ZEND_ADD_INTERFACE
(integer)
ZEND_INSTANCEOF
(integer)
The following constants control the VM's behaviour after a user handler is invoked, be extremely careful!
ZEND_USER_OPCODE_CONTINUE
(integer)
ZEND_USER_OPCODE_ENTER
(integer)
ZEND_USER_OPCODE_LEAVE
(integer)
ZEND_USER_OPCODE_DISPATCH
(integer)
ZEND_USER_OPCODE_DISPATCH_TO
(integer)
ZEND_USER_OPCODE_RETURN
(integer)
(PECL uopz >= 1.0.3)
uopz_backup — Backup a function
$class
, string $function
)$function
)Backup a function at runtime, to be restored on shutdown
classThe name of the class containing the function to backup
functionThe name of the function
Example #1 uopz_backup() example
<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
return true;
});
var_dump(fgets());
?>
The above example will output something similar to:
bool(true)
(PECL uopz >= 1.0.0)
uopz_compose — Compose a class
Creates a new class of the given name that implements, extends, or uses all of the provided classes
nameA legal class name
classesAn array of class, interface and trait names
Example #1 uopz_compose() example
<?php
class myClass {}
trait myTrait {}
interface myInterface {}
uopz_compose(
Composed::class, [
myClass::class,
myTrait::class,
myInterface::class
]);
var_dump(
class_uses(Composed::class),
class_parents(Composed::class),
class_implements(Composed::class));
?>
The above example will output something similar to:
array(1) {
["myTrait"]=>
string(7) "myTrait"
}
array(1) {
["myClass"]=>
string(7) "myClass"
}
array(1) {
["myInterface"]=>
string(11) "myInterface"
}
(PECL uopz >= 1.0.4)
uopz_copy — Copy a function
Copy a function by name
classThe name of the class containing the function to copy
functionThe name of the function
A Closure for the specified function
Example #1 uopz_copy() example
<?php
$strtotime = uopz_copy('strtotime');
uopz_function("strtotime", function($arg1, $arg2) use($strtotime) {
/* can call original strtotime from here */
var_dump($arg1);
});
var_dump(strtotime('dummy'));
?>
The above example will output something similar to:
string(5) "dummy"
(PECL uopz >= 1.0.0)
uopz_delete — Delete a function
$class
, string $function
)$function
)Deletes a function or method
class
function
Example #1 uopz_delete() example
<?php
uopz_delete("strlen");
echo strlen("Hello World");
?>
The above example will output something similar to:
PHP Fatal error: Call to undefined function strlen() in /path/to/script.php on line 4
Example #2 uopz_delete() class example
<?php
class My {
public static function strlen($arg) {
return strlen($arg);
}
}
uopz_delete(My::class, "strlen");
echo My::strlen("Hello World");
?>
The above example will output something similar to:
PHP Fatal error: Call to undefined method My::strlen() in /path/to/script.php on line 10
(PECL uopz >= 1.0.0)
uopz_extend — Extend a class at runtime
$class
, string $parent
)
Makes class extend parent
classThe name of the class to extend
parentThe name of the class to inherit
Example #1 uopz_extend() example
<?php
class A {}
class B {}
uopz_extend(A::class, B::class);
var_dump(class_parents(A::class));
?>
The above example will output something similar to:
array(1) {
["B"]=>
string(1) "B"
}
(PECL uopz >= 1.0.0)
uopz_function — Creates a function at runtime
Creates a function at runtime
classThe name of the class to receive the new function
functionThe name of the function
handlerThe Closure for the function
staticSet true to create static function, by default false
Example #1 uopz_function() example
<?php
uopz_function("my_strlen", function($arg) {
return strlen($arg);
});
echo my_strlen("Hello World");
?>
The above example will output something similar to:
11
Example #2 uopz_function() class example
<?php
class My {}
uopz_function(My::class, "strlen", function($arg) {
return strlen($arg);
});
echo My::strlen("Hello World");
?>
The above example will output something similar to:
11
(PECL uopz >= 1.0.0)
uopz_implement — Implements an interface at runtime
$class
, string $interface
)
Makes class implement interface
class
interface
Example #1 uopz_implement() example
<?php
interface myInterface {}
class myClass {}
uopz_implement(myClass::class, myInterface::class);
var_dump(class_implements(myClass::class));
?>
The above example will output something similar to:
array(1) {
["myInterface"]=>
string(11) "myInterface"
}
(PECL uopz >= 1.0.0)
uopz_overload — Overload a VM opcode
Overloads the specified opcode with the user defined function
opcodeA valid opcode, see constants for details of supported codes
callable
Example #1 uopz_overload() example
<?php
uopz_overload(ZEND_EXIT, function(){});
exit();
echo "Hello World";
?>
The above example will output something similar to:
Hello World
(PECL uopz >= 1.0.0)
uopz_redefine — Redefine a constant
Redefines the given constant as value
classThe name of the class containing the constant
constantThe name of the constant
valueThe new value for the constant, must be a valid type for a constant variable
Example #1 uopz_redefine() example
<?php
define("MY", 100);
uopz_redefine("MY", 1000);
echo MY;
?>
The above example will output something similar to:
1000
(PECL uopz >= 1.0.0)
uopz_rename — Rename a function at runtime
$class
, string $function
, string $rename
)$function
, string $rename
)
Renames function to rename
Note:
If both functions exist, this effectively swaps their names
classThe name of the class containing the function
functionThe name of an existing function
renameThe new name for the function
Example #1 uopz_rename() example
<?php
uopz_rename("strlen", "original_strlen");
echo original_strlen("Hello World");
?>
The above example will output something similar to:
11
Example #2 uopz_rename() class example
<?php
class My {
public function strlen($arg) {
return strlen($arg);
}
}
uopz_rename(My::class, "strlen", "original_strlen");
echo My::original_strlen("Hello World");
?>
The above example will output something similar to:
11
(PECL uopz >= 1.0.3)
uopz_restore — Restore a previously backed up function
$class
, string $function
)$function
)Restore a previously backed up function
classThe name of the class containing the function to restore
functionThe name of the function
Example #1 uopz_restore() example
<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
return true;
});
var_dump(fgets());
uopz_restore('fgets');
fgets();
?>
The above example will output something similar to:
Warning: fgets() expects at least 1 parameter, 0 given in /path/to/script.php on line 8
(PECL uopz >= 1.0.0)
uopz_undefine — Undefine a constant
$class
, string $constant
)$constant
)Removes the constant at runtime
class
The name of the class containing constant
constantThe name of an existing constant
Example #1 uopz_undefine() example
<?php
define("MY", true);
uopz_undefine("MY");
var_dump(defined("MY"));
?>
The above example will output something similar to:
bool(false)
Weak references provide a non-intrusive gateway to ephemeral objects. Unlike normal (strong) references, weak references do not prevent the garbage collector from freeing that object. For this reason, an object may be destroyed even though a weak reference to that object still exists. In such conditions, the weak reference seamlessly becomes invalid.
Example #1 Weakref usage example
<?php
class MyClass {
public function __destruct() {
echo "Destroying object!\n";
}
}
$o1 = new MyClass;
$r1 = new Weakref($o1);
if ($r1->valid()) {
echo "Object still exists!\n";
var_dump($r1->get());
} else {
echo "Object is dead!\n";
}
unset($o1);
if ($r1->valid()) {
echo "Object still exists!\n";
var_dump($r1->get());
} else {
echo "Object is dead!\n";
}
?>
The above example will output:
Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!
No external libraries are needed to build this extension.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/weakref.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no resource types defined.
(PECL weakref >= 0.1.0)
The WeakRef class provides a gateway to objects without preventing the garbage collector from freeing those objects. It also provides a way to turn a weak reference into a strong one.
Example #1 WeakRef usage example
<?php
class MyClass {
public function __destruct() {
echo "Destroying object!\n";
}
}
$o1 = new MyClass;
$r1 = new WeakRef($o1);
if ($r1->valid()) {
echo "Object still exists!\n";
var_dump($r1->get());
} else {
echo "Object is dead!\n";
}
unset($o1);
if ($r1->valid()) {
echo "Object still exists!\n";
var_dump($r1->get());
} else {
echo "Object is dead!\n";
}
?>
The above example will output:
Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!
(PECL weakref >= 0.1.0)
Weakref::acquire — Acquires a strong reference on that object
Acquires a strong reference on that object, virtually turning the weak reference into a strong one.
This function has no parameters.
Returns TRUE if the reference was valid and could be turned into a strong
reference, FALSE otherwise.
Example #1 Weakref::acquire() example
<?php
class MyClass {
public function __destruct() {
echo "Destroying object!\n";
}
}
$o1 = new MyClass;
$r1 = new Weakref($o1);
$r1->acquire();
echo "Unsetting o1...\n";
unset($o1);
$o2 = $r1->get();
$r1->release();
echo "Unsetting o2...\n";
unset($o2);
?>
The above example will output:
Unsetting o1... Unsetting o2... Destroying object!
Example #2 Nested acquire/release example
<?php
class MyClass {
public function __destruct() {
echo "Destroying object!\n";
}
}
$o1 = new MyClass;
$r1 = new Weakref($o1);
echo "Acquiring...\n";
$r1->acquire();
echo " Unsetting...\n";
unset($o1);
echo " Acquiring...\n";
$r1->acquire();
echo " Acquiring...\n";
$r1->acquire();
echo " Releasing...\n";
$r1->release();
echo " Releasing...\n";
$r1->release();
echo "Releasing...\n";
$r1->release();
?>
The above example will output:
Acquiring...
Unsetting...
Acquiring...
Acquiring...
Releasing...
Releasing...
Releasing...
Destroying object!
(PECL weakref >= 0.1.0)
Weakref::__construct — Constructs a new weak reference
$object
] )Constructs a new weak reference.
objectThe object to reference.
No value is returned.
Example #1 Weakref::__construct() example
<?php
class MyClass {
public function __destruct() {
echo "Destroying object!\n";
}
}
$o1 = new MyClass;
$r1 = new Weakref($o1);
if ($r1->valid()) {
echo "Object still exists!\n";
var_dump($r1->get());
} else {
echo "Object is dead!\n";
}
unset($o1);
if ($r1->valid()) {
echo "Object still exists!\n";
var_dump($r1->get());
} else {
echo "Object is dead!\n";
}
?>
The above example will output:
Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!
(PECL weakref >= 0.1.0)
Weakref::get — Returns the object pointed to by the weak reference
Returns the object pointed to by the weak reference.
This function has no parameters.
Returns the object if the reference is still valid, NULL otherwise.
(PECL weakref >= 0.1.0)
Weakref::release — Releases a previously acquired reference
Releases a previously acquired reference. Potentially turning a strong reference back into a weak reference.
This function has no parameters.
Returns TRUE if the reference was previously acquired and thus could be
released, FALSE otherwise.
Example #1 Weakref::release() example
<?php
class MyClass {
public function __destruct() {
echo "Destroying object!\n";
}
}
$o1 = new MyClass;
$r1 = new Weakref($o1);
$r1->acquire();
echo "Unsetting o1...\n";
unset($o1);
$o2 = $r1->get();
$r1->release();
echo "Unsetting o2...\n";
unset($o2);
?>
The above example will output:
Unsetting o1... Unsetting o2... Destroying object!
(PECL weakref >= 0.1.0)
Weakref::valid — Checks whether the object referenced still exists
Checks whether the object referenced still exists.
This function has no parameters.
Returns TRUE if the object still exists and is thus still accessible via
Weakref::get(), FALSE otherwise.
(PECL weakref >= 0.2.0)
Example #1 Weakmap usage example
<?php
$wm = new WeakMap();
$o = new StdClass;
class A {
public function __destruct() {
echo "Dead!\n";
}
}
$wm[$o] = new A;
var_dump(count($wm));
echo "Unsetting..\n";
unset($o);
echo "Done\n";
var_dump(count($wm));
The above example will output:
int(1) Unsetting.. Dead! Done int(0)
(PECL weakref >= 0.2.0)
WeakMap::__construct — Constructs a new map
Constructs a new map.
This function has no parameters.
No value is returned.
(PECL weakref >= 0.2.0)
WeakMap::count — Counts the number of live entries in the map
Counts the number of live entries in the map.
This function has no parameters.
Returns the number of live entries in the map.
(PECL weakref >= 0.2.0)
WeakMap::current — Returns the current value under iteration
Returns the current value being iterated on in the map.
This function has no parameters.
The value currently being iterated on.
(PECL weakref >= 0.2.0)
WeakMap::key — Returns the current key under iteration.
Returns the object serving as key in the map, at the current iterating position.
This function has no parameters.
The object key currently being iterated.
(PECL weakref >= 0.2.0)
WeakMap::next — Advances to the next map element
Advances to the next map element.
This function has no parameters.
No value is returned.
(PECL weakref >= 0.2.0)
WeakMap::offsetExists — Checks whether a certain object is in the map
$object
)Checks whether the passed object is referenced in the map.
objectObject to check for.
Returns TRUE if the object is contained in the map, FALSE otherwise.
(PECL weakref >= 0.2.0)
WeakMap::offsetGet — Returns the value pointed to by a certain object
Returns the value pointed to by a certain object.
objectSome object contained as key in the map.
Returns the value associated to the object passed as argument, NULL
otherwise.
(PECL weakref >= 0.2.0)
WeakMap::offsetSet — Updates the map with a new key-value pair
Updates the map with a new key-value pair. If the key already existed in the map, the old value is replaced with the new.
objectThe object serving as key of the key-value pair.
valueThe arbitrary data serving as value of the key-value pair.
No value is returned.
(PECL weakref >= 0.2.0)
WeakMap::offsetUnset — Removes an entry from the map
$object
)Removes an entry from the map.
objectThe key object to remove from the map.
No value is returned.
(PECL weakref >= 0.2.0)
WeakMap::rewind — Rewinds the iterator to the beginning of the map
Rewinds the iterator to the beginning of the map.
This function has no parameters.
No value is returned.
(PECL weakref >= 0.2.0)
WeakMap::valid — Returns whether the iterator is still on a valid map element
Returns whether the iterator is still on a valid map element.
This function has no parameters.
Returns TRUE if the iterator is on a valid element that can be
accessed, FALSE otherwise.
Windows Cache Extension for PHP is a PHP accelerator that is used to increase the speed of PHP applications running on Windows and Windows Server. Once the Windows Cache Extension for PHP is enabled and loaded by the PHP engine, PHP applications can take advantage of the functionality without any code modifications.
The Windows Cache Extension includes 5 different types of caches. The following describes the purpose of each cache type and the benefits it provides.
PHP Opcode Cache - PHP is a script processing engine, which reads an input stream of data that contains text and/or PHP instructions and produces another stream of data, most commonly in the HTML format. This means that on a web server the PHP engine reads, parses, compiles and executes a PHP script each time that it is requested by a Web client. The reading, parsing and compilation operations put additional load on the web server's CPU and file system and thus affect the overall performance of a PHP web application. The PHP bytecode (opcode) cache is used to store the compiled script bytecode in shared memory so that it can be re-used by PHP engine for subsequent executions of the same script.
File Cache - Even with the PHP opcode cache enabled, the PHP engine has to accesses the script files on a file system. When PHP scripts are stored on a remote UNC file share, the file operations introduce a significant performance overhead. The Windows Cache Extension for PHP includes a file cache that is used to store the content of the PHP script files in shared memory, which reduces the amount of file system operations performed by PHP engine.
Resolve File Path Cache - PHP scripts very often include or operate with files by using relative file paths. Every file path has to be normalized to an absolute file path by the PHP engine. When a PHP application uses many PHP files and accesses them by relative paths, the operation of resolving the paths may negatively impact the application's performance. The Windows Cache Extension for PHP provides a Resolve File Path cache, which is used to store the mappings between relative and absolute file paths, thereby reducing the number of path resolutions that the PHP engine has to perform.
User Cache (available since version 1.1.0) - PHP scripts can take advantage of the shared memory cache by using the user cache API's. PHP objects and variables can be stored in the user cache and then re-used on subsequent requests. This can be used to improve performance of PHP scripts and to share the data across multiple PHP processes.
Session Handler (available since version 1.1.0) - The WinCache session handler can be used to store the PHP session data in the shared memory cache. This avoids file system operations for reading and writing session data, which improves performance when large amount of data is stored in PHP session.
The extension is currently supported only on the following configurations:
Windows OS:
PHP:
Note: The WinCache Extension can only be used when IIS is configured to run PHP via FastCGI.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/wincache.
There are two packages for this extension: one package is for PHP versions 5.2.X, and the other package is for PHP 5.3.X. Select the package that is appropriate for the PHP version being used.
To install and enable the extension, follow these steps:
Unpack the package into some temporary location.
Copy the php_wincache.dll file into the PHP extensions folder. Typically this folder is called "ext" and it is located in the same folder with all PHP binary files. For example: C:\Program Files\PHP\ext.
Using a text editor, open the php.ini file, which is usually located in the same folder where all PHP binary files are. For example: C:\Program Files\PHP\php.ini.
Add the following line at the end of the php.ini file: extension = php_wincache.dll.
Save and close the php.ini file.
Recycle the IIS Application Pools for PHP to pick up the configuration changes. To check that the extension has been enabled, create a file called phpinfo.php with a PHP code that calls phpinfo function.
Save the phpinfo.php file in the root folder of a IIS web site that uses PHP, then open a browser and make a request to http://localhost/phpinfo.php. Search within the returned web page for a section called wincache. If the extension is enabled, then the phpinfo output will list the configuration settings provided by the WinCache.
Note: Do not forget to remove phpinfo.php file from the web site's root folder after verifying that extension has been enabled.
The behaviour of these functions is affected by settings in php.ini.
The following table lists and explains the configuration settings provided by the WinCache extension:
| Name | Default | Minimum | Maximum | Changeable | Changelog |
|---|---|---|---|---|---|
| wincache.fcenabled | "1" | "0" | "1" | PHP_INI_ALL | Available since WinCache 1.0.0 |
| wincache.fcenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.fcachesize | "24" | "5" | "255" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.fcndetect | "1" | "0" | "1" | PHP_INI_SYSTEM | Available since WinCache 1.1.0 |
| wincache.maxfilesize | "256" | "10" | "2048" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.ocenabled | "1" | "0" | "1" | PHP_INI_ALL | Available since WinCache 1.0.0 |
| wincache.ocenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.ocachesize | "96" | "15" | "255" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.filecount | "4096" | "1024" | "16384" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.chkinterval | "30" | "0" | "300" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.ttlmax | "1200" | "0" | "7200" | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.enablecli | 0 | 0 | 1 | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.ignorelist | NULL | NULL | NULL | PHP_INI_ALL | Available since WinCache 1.0.0 |
| wincache.namesalt | NULL | NULL | NULL | PHP_INI_SYSTEM | Available since WinCache 1.0.0 |
| wincache.ucenabled | 1 | 0 | 1 | PHP_INI_SYSTEM | Available since WinCache 1.1.0 |
| wincache.ucachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available since WinCache 1.1.0 |
| wincache.scachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available since WinCache 1.1.0 |
| wincache.rerouteini | NULL | NULL | NULL | PHP_INI_SYSTEM | Available since WinCache 1.2.0 |
Here's a short explanation of the configuration directives.
wincache.fcenabled
boolean
wincache.fcenabledfilter
string
wincache.fcachesize
integer
wincache.fcndetect
boolean
wincache.maxfilesize
integer
wincache.ocenabled
boolean
wincache.ocenabledfilter
string
wincache.ocachesize
integer
wincache.filecount
integer
wincache.chkinterval
integer
wincache.ttlmax
integer
wincache.enablecli
boolean
wincache.ignorelist
string
Defines a list of files that should not be cached by the extension. The files list is specified by using file names only, separated by the pipe symbol - "|".
Example #1 wincache.ignorelist example
wincache.ignorelist = "index.php|misc.php|admin.php"
wincache.namesalt
string
wincache.ucenabled
boolean
wincache.ucachesize
integer
wincache.scachesize
integer
wincache.rerouteini
string
The installation package for WinCache includes a PHP script, wincache.php, that can be used to obtain cache information and statistics.
If the WinCache extension was installed via the Microsoft Web Platform Installer, then this script is located in %SystemDrive%\Program Files\IIS\Windows Cache for PHP\. On a 64-bit version of the Windows Server operating system, the script is located in %SystemDrive%\Program Files (x86)\IIS\Windows Cache for PHP. If the extension was installed manually, then the wincache.php will be located in the same folder from which the content of the installation package was extracted.
To use wincache.php, copy it into a root folder of a Web site or into any subfolder. To protect the script, open it in any text editor and replace the values for USERNAME and PASSWORD constants. If any other IIS authentication is enabled on the server, then follow the instructions in the comments:
Example #1 Authentication configuration for wincache.php
<?php
/**
* ======================== CONFIGURATION SETTINGS ==============================
* If you do not want to use authentication for this page, set USE_AUTHENTICATION to 0.
* If you use authentication then replace the default password.
*/
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'wincache');
define('PASSWORD', 'wincache');
/**
* The Basic PHP authentication will work only when IIS is configured to support
* Anonymous Authentication' and nothing else. If IIS is configured to support/use
* any other kind of authentication like Basic/Negotiate/Digest etc, this will not work.
* In that case use the array below to define the names of users in your
* domain/network/workgroup which you want to grant access to.
*/
$user_allowed = array('DOMAIN\user1', 'DOMAIN\user2', 'DOMAIN\user3');
/**
* If the array contains string 'all', then all the users authenticated by IIS
* will have access to the page. Uncomment the below line and comment above line
* to grant access to all users who gets authenticated by IIS.
*/
/* $user_allowed = array('all'); */
/** ===================== END OF CONFIGURATION SETTINGS ========================== */
?>
Note: Always protect the wincache.php script by using either the built-in authentication or the server's authentication mechanism. Leaving this script unprotected may compromise the security of your web application and web server.
The WinCache session handler (available since WinCache 1.1.0) can be used to configure PHP to store the session data in shared memory session cache. Using shared memory instead of the default file session storage helps improve performance of PHP applications that store large amount of data in session objects. Wincache session cache uses file-backed shared memory, which ensures that the session data is not lost during recycling of IIS application pools.
To configure PHP to use WinCache session handler set the php.ini setting session.save_handler to wincache. By default the Windows temporary file location is used for storing the session data. To change the location of the session file use session.save_path directive.
Example #1 Enabling WinCache session handler
session.save_handler = wincache session.save_path = C:\inetpub\temp\session\
The WinCache functions reroutes (available since WinCache 1.2.0) can be used to replace built-in PHP functions with their equivalents that are optimized for a particular purpose. WinCache extension includes Windows-optimized implementation of PHP file functions that may improve performance of PHP applications in cases when PHP has to access files on network shares. The optimized implementation is provided for the following functions:
To configure WinCache to use the functions reroutes use the file reroute.ini that is included in WinCache installation package. Copy this file into the same directory where php.ini file is located. After that add the wincache.rerouteini setting in php.ini and specify an absolute or relative path to the reroute.ini file.
Example #1 Enabling WinCache functions reroutes
wincache.rerouteini = C:\PHP\reroute.ini
Note: If WinCache functions reroutes are enabled it is recommended to increase the WinCache file cache size. This can be done by using wincache.fcachesize setting.
The reroute.ini file contains the mappings between the native PHP functions and their equivalents in WinCache. Each line in the file defines a mapping by using the following syntax:
<PHP function name>:[<number of function parameters>]=<wincache function name>
The example of the file is shown below. In this example the calls to PHP function file_get_contents() will be replaced with calls to wincache_file_get_contents() only if the number of parameters passed to the function is less than or equals to 2. Specifying the number of parameters is useful when replacement function does not handle all the function's parameters.
Example #2 Reroute.ini file content
[FunctionRerouteList] file_exists=wincache_file_exists file_get_contents:2=wincache_file_get_contents readfile:2=wincache_readfile is_readable=wincache_is_readable is_writable=wincache_is_writable is_writeable=wincache_is_writable is_file=wincache_is_file is_dir=wincache_is_dir realpath=wincache_realpath filesize=wincache_filesize
This extension has no resource types defined.
This extension has no constants defined.
(PECL wincache >= 1.0.0)
wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
$summaryonly = false
] )Retrieves information about file cache content and its usage.
summaryonlyControls whether the returned array will contain information about individual cache entries along with the file cache summary.
Array of meta data about file cache or FALSE on failure
The array returned by this function contains the following elements:
file_entries - an array that contains the information about all the cached files:
Example #1 A wincache_fcache_fileinfo() example
<pre>
<?php
print_r(wincache_fcache_fileinfo());
?>
</pre>
The above example will output:
Array
( [total_cache_uptime] => 3234
[total_file_count] => 5
[total_hit_count] => 0
[total_miss_count] => 1
[file_entries] => Array
(
[1] => Array
(
[file_name] => c:\inetpub\wwwroot\checkcache.php
[add_time] => 1
[use_time] => 0
[last_check] => 1
[hit_count] => 1
[file_size] => 2435
)
[2] => Array (...iterates for each cached file)
)
)
(PECL wincache >= 1.0.0)
wincache_fcache_meminfo — Retrieves information about file cache memory usage
Retrieves information about memory usage by file cache.
Array of meta data about file cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
Example #1 A wincache_fcache_meminfo() example
<pre>
<?php
print_r(wincache_fcache_meminfo());
?>
</pre>
The above example will output:
Array
(
[memory_total] => 134217728
[memory_free] => 131339120
[num_used_blks] => 361
[num_free_blks] => 3
[memory_overhead] => 5856
)
(PECL wincache >= 1.1.0)
wincache_lock — Acquires an exclusive lock on a given key
$key
[, bool $isglobal = false
] )Obtains an exclusive lock on a given key. The execution of the current script will be blocked until the lock can be obtained. Once the lock is obtained, the other scripts that try to request the lock by using the same key will be blocked, until the current script releases the lock by using wincache_unlock().
Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.
keyName of the key in the cache to get the lock on.
isglobalControls whether the scope of the lock is system-wide or local. Local locks are scoped to the application pool in IIS FastCGI case or to all php processes that have the same parent process identifier.
Returns TRUE on success or FALSE on failure.
Example #1 Using wincache_lock()
<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (wincache_lock(“lock_txt_lock”)) { // do an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
wincache_unlock(“lock_txt_lock”); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>
(PECL wincache >= 1.0.0)
wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
$summaryonly = false
] )Retrieves information about opcode cache content and its usage.
summaryonlyControls whether the returned array will contain information about individual cache entries along with the opcode cache summary.
Array of meta data about opcode cache or FALSE on failure
The array returned by this function contains the following elements:
file_entries - an array that contains the information about all the cached files:
Example #1 A wincache_ocache_fileinfo() example
<pre>
<?php
print_r(wincache_ocache_fileinfo());
?>
</pre>
The above example will output:
Array
(
[total_cache_uptime] => 17357
[total_file_count] => 121
[total_hit_count] => 36562
[total_miss_count] => 201
[file_entries] => Array
(
[1] => Array
(
[file_name] => c:\inetpub\wwwroot\checkcache.php
[add_time] => 17356
[use_time] => 7
[last_check] => 10
[hit_count] => 454
[function_count] => 0
[class_count] => 1
)
[2] => Array (...iterates for each cached file)
)
)
(PECL wincache >= 1.0.0)
wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
Retrieves information about memory usage by opcode cache.
Array of meta data about opcode cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
Example #1 A wincache_ocache_meminfo() example
<pre>
<?php
print_r(wincache_ocache_meminfo());
?>
</pre>
The above example will output:
Array
(
[memory_total] => 134217728
[memory_free] => 112106972
[num_used_blks] => 15469
[num_free_blks] => 4
[memory_overhead] => 247600
)
(PECL wincache >= 1.0.0)
wincache_refresh_if_changed — Refreshes the cache entries for the cached files
$files
] )Refreshes the cache entries for the files, whose names were passed in the input argument. If no argument is specified then refreshes all the entries in the cache.
filesAn array of file names for files that need to be refreshed. An absolute or relative file paths can be used.
Returns TRUE on success or FALSE on failure.
WinCache performs regular checks on the cached files to ensure that if any file has changed then the corresponding entry in the cache is updated. By default this check is performed every 30 seconds. If, for example, a PHP script updates another PHP script where the application's configuration settings are stored, then it may happen that after the configuration settings have been saved to a file, the application is still using old settings for some time until the cache is refreshed. In those cases it may be preferrable to refresh the cache right after the file has been changed. The following example shows how this can be done.
Example #1 A wincache_refresh_if_changed() example
<?php
$filename = 'C:\inetpub\wwwroot\config.php';
$handle = fopen($filename, 'w+');
if ($handle === FALSE) die('Failed to open file '.$filename.' for writing');
fwrite($handle, '<?php $setting=something; ?>');
fclose($handle);
wincache_refresh_if_changed(array($filename));
?>
(PECL wincache >= 1.0.0)
wincache_rplist_fileinfo — Retrieves information about resolve file path cache
$summaryonly = false
] )Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.
Array of meta data about the resolve file path cache or FALSE on failure
The array returned by this function contains the following elements:
rplist_entries - an array that contains the information about all the cached file paths:
Example #1 A wincache_rplist_fileinfo() example
<pre>
<?php
print_r(wincache_rplist_fileinfo());
?>
</pre>
The above example will output:
Array
(
[total_file_count] => 5
[rplist_entries] => Array
(
[1] => Array
(
[resolve_path] => checkcache.php
[subkey_data] => c:\inetpub\wwwroot|c:\inetpub\wwwroot\checkcache.php
)
[2] => Array (...iterates for each cached file)
)
)
(PECL wincache >= 1.0.0)
wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
Retrieves information about memory usage by resolve file path cache.
Array of meta data that describes memory usage by resolve file path cache. or FALSE on failure
The array returned by this function contains the following elements:
Example #1 A wincache_rplist_meminfo() example
<pre>
<?php
print_r(wincache_rplist_meminfo());
?>
</pre>
The above example will output:
Array
(
[memory_total] => 9437184
[memory_free] => 9416744
[num_used_blks] => 23
[num_free_blks] => 1
[memory_overhead] => 416
)
(PECL wincache >= 1.1.0)
wincache_scache_info — Retrieves information about files cached in the session cache
$summaryonly = false
] )Retrieves information about session cache content and its usage.
summaryonlyControls whether the returned array will contain information about individual cache entries along with the session cache summary.
Array of meta data about session cache or FALSE on failure
The array returned by this function contains the following elements:
scache_entries - an array that contains the information about all the cached items:
Example #1 A wincache_scache_info() example
<pre>
<?php
print_r(wincache_scache_info());
?>
</pre>
The above example will output:
Array
(
[total_cache_uptime] => 17357
[total_file_count] => 121
[total_hit_count] => 36562
[total_miss_count] => 201
[scache_entries] => Array
(
[1] => Array
(
[file_name] => c:\inetpub\wwwroot\checkcache.php
[add_time] => 17356
[use_time] => 7
[last_check] => 10
[hit_count] => 454
[function_count] => 0
[class_count] => 1
)
[2] => Array (...iterates for each cached file)
)
)
(PECL wincache >= 1.1.0)
wincache_scache_meminfo — Retrieves information about session cache memory usage
Retrieves information about memory usage by session cache.
Array of meta data about session cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
Example #1 A wincache_scache_meminfo() example
<pre>
<?php
print_r(wincache_scache_meminfo());
?>
</pre>
The above example will output:
Array
(
[memory_total] => 5242880
[memory_free] => 5215056
[num_used_blks] => 6
[num_free_blks] => 3
[memory_overhead] => 176
)
(PECL wincache >= 1.1.0)
wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
Adds a variable in user cache, only if this variable doesn't already exist in the cache. The added variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.
key
Store the variable using this key name. If a variable with same key is already present the function
will fail and return FALSE. key is case sensitive. To override the value even if
key is present use wincache_ucache_set() function instad.
key can also take array of name => value pairs where names will be used as keys.
This can be used to add multiple values in the cache in one operation, thus avoiding race condition.
value
Value of a variable to store. Value supports all data types except resources, such as file handles.
This paramter is ignored if first argument is an array. A general guidance is to pass NULL
as value while using array as key. If value is an
object, or an array containing objects, then the objects will be serialized. See
__sleep() for details on serializing objects.
valuesAssociative array of keys and values.
ttl
Time for the variable to live in the cache in seconds. After the value specified in ttl has passed
the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means
the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete()
or wincache_ucache_clear() functions.
If key is string, the function returns TRUE on success and FALSE on failure.
If key is an array, the function returns:
FALSE;
Example #1 wincache_ucache_add() with key as a string
<?php
$bar = 'BAR';
var_dump(wincache_ucache_add('foo', $bar));
var_dump(wincache_ucache_add('foo', $bar));
var_dump(wincache_ucache_get('foo'));
?>
The above example will output:
bool(true) bool(false) string(3) "BAR"
Example #2 wincache_ucache_add() with key as an array
<?php
$colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>
The above example will output:
array(0) { }
array(4) {
["green"]=> int(-1)
["Blue"]=> int(-1)
["yellow"]=> int(-1)
["cyan"]=> int(-1)
}
string(1) "6"
(PECL wincache >= 1.1.0)
wincache_ucache_cas — Compares the variable with old value and assigns new value to it
$key
, int $old_value
, int $new_value
)
Compares the variable associated with the key with old_value
and if it matches then assigns the new_value to it.
key
The key that is used to store the variable in the cache.
key is case sensitive.
old_value
Old value of the variable pointed by key in the user cache.
The value should be of type long, otherwise the function returns
FALSE.
new_value
New value which will get assigned to variable pointer by key if a
match is found. The value should be of type long, otherwise
the function returns FALSE.
Returns TRUE on success or FALSE on failure.
Example #1 Using wincache_ucache_cas()
<?php
wincache_ucache_set('counter', 2922);
var_dump(wincache_ucache_cas('counter', 2922, 1));
var_dump(wincache_ucache_get('counter'));
?>
The above example will output:
bool(true) int(1)
(PECL wincache >= 1.1.0)
wincache_ucache_clear — Deletes entire content of the user cache
Clears/deletes all the values stored in the user cache.
Returns TRUE on success or FALSE on failure.
Example #1 using wincache_ucache_clear()
<?php
wincache_ucache_set('green', 1);
wincache_ucache_set('red', 2);
wincache_ucache_set('orange', 4);
wincache_ucache_set('blue', 8);
wincache_ucache_set('cyan', 16);
$array1 = array('green', 'red', 'orange', 'blue', 'cyan');
var_dump(wincache_ucache_get($array1));
var_dump(wincache_ucache_clear());
var_dump(wincache_ucache_get($array1));
?>
The above example will output:
array(5) { ["green"]=> int(1)
["red"]=> int(2)
["orange"]=> int(4)
["blue"]=> int(8)
["cyan"]=> int(16) }
bool(true)
bool(false)
(PECL wincache >= 1.1.0)
wincache_ucache_dec — Decrements the value associated with the key
Decrements the value associated with the key by 1 or as specified
by dec_by.
key
The key that was used to store the variable in the cache.
key is case sensitive.
dec_by
The value by which the variable associated with the key will get decremented.
If the argument is a floating point number it will be truncated to nearest integer. The variable
associated with the key should be of type long, otherwise
the function fails and returns FALSE.
success
Will be set to TRUE on success and FALSE on failure.
Returns the decremented value on success and FALSE on failure.
Example #1 Using wincache_ucache_dec()
<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_dec('counter', 2923, $success));
var_dump($success);
?>
The above example will output:
int(2922) bool(true)
(PECL wincache >= 1.1.0)
wincache_ucache_delete — Deletes variables from the user cache
Deletes the elements in the user cache pointed by key.
key
The key that was used to store the variable in the cache.
key is case sensitive. key can be an
array of keys.
Returns TRUE on success or FALSE on failure.
If key is an array then the function returns FALSE
if every element of the array fails to get deleted from the user cache, otherwise returns an
array which consists of all the keys that are deleted.
Example #1 Using wincache_ucache_delete() with key as a string
<?php
wincache_ucache_set('foo', 'bar');
var_dump(wincache_ucache_delete('foo'));
var_dump(wincache_ucache_exists('foo'));
?>
The above example will output:
bool(true) bool(false)
Example #2 Usingwincache_ucache_delete() with key as an array
<?php
$array1 = array('green' => '5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'blue', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>
The above example will output:
array(4) { [0]=> string(5) "green"
[1]=> string(4) "Blue"
[2]=> string(6) "yellow"
[3]=> string(4) "cyan" }
Example #3 Using wincache_ucache_delete() with key as an array where some elements cannot be deleted
<?php
$array1 = array('green' => '5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('orange', 'red', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>
The above example will output:
array(2) { [0]=> string(6) "yellow"
[1]=> string(4) "cyan" }
(PECL wincache >= 1.1.0)
wincache_ucache_exists — Checks if a variable exists in the user cache
$key
)
Checks if a variable with the key exists in the user cache or not.
key
The key that was used to store the variable in the cache.
key is case sensitive.
Returns TRUE if variable with the key exitsts,
otherwise returns FALSE.
Example #1 Using wincache_ucache_exists()
<?php
if (!wincache_ucache_exists('green'))
wincache_ucache_set('green', 1);
var_dump(wincache_ucache_exists('green'));
?>
The above example will output:
bool(true)
(PECL wincache >= 1.1.0)
wincache_ucache_get — Gets a variable stored in the user cache
Gets a variable stored in the user cache.
key
The key that was used to store the variable in the cache.
key is case sensitive. key can be an
array of keys. In this case the return value will be an array of values of each element
in the key array. If an object, or an array containing objects,
is returned, then the objects will be unserialized. See
__wakeup() for details on unserializing objects.
success
Will be set to TRUE on success and FALSE on failure.
If key is a string, the function returns the value of the variable stored with that key.
The success is set to TRUE on success and
to FALSE on failure.
The key is an array, the parameter success
is always set to TRUE. The returned array (name => value pairs) will
contain only those name => value pairs for which the get operation in user cache was
successful. If none of the keys in the key array finds a match in the user cache
an empty array will be returned.
Example #1 wincache_ucache_get() with key as a string
<?php
wincache_ucache_add('color', 'blue');
var_dump(wincache_ucache_get('color', $success));
var_dump($success);
?>
The above example will output:
string(4) "blue" bool(true)
Example #2 wincache_ucache_get() with key as an array
<?php
$array1 = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'Blue', 'yellow', 'cyan');
var_dump(wincache_ucache_get($array2, $success));
var_dump($success);
?>
The above example will output:
array(4) { ["green"]=> string(1) "5"
["Blue"]=> string(1) "6"
["yellow"]=> string(1) "7"
["cyan"]=> string(1) "8" }
bool(true)
(PECL wincache >= 1.1.0)
wincache_ucache_inc — Increments the value associated with the key
Increments the value associated with the key by 1 or as specified
by inc_by.
key
The key that was used to store the variable in the cache.
key is case sensitive.
inc_by
The value by which the variable associated with the key will get incremented.
If the argument is a floating point number it will be truncated to nearest integer. The variable
associated with the key should be of type long, otherwise
the function fails and returns FALSE.
success
Will be set to TRUE on success and FALSE on failure.
Returns the incremented value on success and FALSE on failure.
Example #1 Using wincache_ucache_inc()
<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_inc('counter', 2921, $success));
var_dump($success);
?>
The above example will output:
int(2922) bool(true)
(PECL wincache >= 1.1.0)
wincache_ucache_info — Retrieves information about data stored in the user cache
$summaryonly = false
[, string $key
]] )Retrieves information about data stored in the user cache.
summaryonlyControls whether the returned array will contain information about individual cache entries along with the user cache summary.
key
The key of an entry in the user cache. If specified then the returned array will contain information
only about that cache entry. If not specified and summaryonly is set to
FALSE then the returned array will contain information about all entries in the cache.
Array of meta data about user cache or FALSE on failure
The array returned by this function contains the following elements:
ucache_entries - an array that contains the information about all the cached items:
Example #1 Using wincache_ucache_info()
<?php
wincache_ucache_get('green');
wincache_ucache_set('green', 2922);
wincache_ucache_get('green');
wincache_ucache_get('green');
wincache_ucache_get('green');
print_r(wincache_ucache_info());
?>
The above example will output:
Array
( ["total_cache_uptime"] => int(0)
["is_local_cache"] => bool(false)
["total_item_count"] => int(1)
["total_hit_count"] => int(3)
["total_miss_count"] => int(1)
["ucache_entries"] => Array(1)
( [1] => Array(6)
(
["key_name"] => string(5) "green"
["value_type"] => string(4) "long"
["is_session"] => int(0)
["ttl_seconds"] => int(0)
["age_seconds"] => int(0)
["hitcount"] => int(3)
)
)
)
(PECL wincache >= 1.1.0)
wincache_ucache_meminfo — Retrieves information about user cache memory usage
Retrieves information about memory usage by user cache.
Array of meta data about user cache memory usage or FALSE on failure
The array returned by this function contains the following elements:
Example #1 A wincache_ucache_meminfo() example
<pre>
<?php
print_r(wincache_ucache_meminfo());
?>
</pre>
The above example will output:
Array
(
[memory_total] => 5242880
[memory_free] => 5215056
[num_used_blks] => 6
[num_free_blks] => 3
[memory_overhead] => 176
)
(PECL wincache >= 1.1.0)
wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
Adds a variable in user cache. Overwrites a variable if it already exists in the cache. The added or updated variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.
key
Store the variable using this key name. If a variable with same
key is already present the function will overwrite the previous
value with the new one. key is case sensitive.
key can also take array of name => value pairs where names will be used as
keys. This can be used to add multiple values in the cache in one operation, thus avoiding
race condition.
value
Value of a variable to store. Value supports all data types except resources, such as file handles.
This paramter is ignored if first argument is an array. A general guidance is to pass NULL
as value while using array as key. If value is an
object, or an array containing objects, then the objects will be serialized. See
__sleep() for details on serializing objects.
valuesAssociative array of keys and values.
ttl
Time for the variable to live in the cache in seconds. After the value specified in ttl has passed
the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means
the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete()
or wincache_ucache_clear() functions.
If key is string, the function returns TRUE on success and FALSE on failure.
If key is an array, the function returns:
FALSE;
Example #1 wincache_ucache_set() with key as a string
<?php
$bar = 'BAR';
var_dump(wincache_ucache_set('foo', $bar));
var_dump(wincache_ucache_get('foo'));
$bar1 = 'BAR1';
var_dump(wincache_ucache_set('foo', $bar1));
var_dump(wincache_ucache_get('foo'));
?>
The above example will output:
bool(true) string(3) "BAR" bool(true) string(3) "BAR1"
Example #2 wincache_ucache_set() with key as an array
<?php
$colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>
The above example will output:
array(0) {}
array(0) {}
string(1) "6"
(PECL wincache >= 1.1.0)
wincache_unlock — Releases an exclusive lock on a given key
$key
)Releases an exclusive lock that was obtained on a given key by using wincache_lock(). If any other process was blocked waiting for the lock on this key, that process will be able to obtain the lock.
Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.
keyName of the key in the cache to release the lock on.
Returns TRUE on success or FALSE on failure.
Example #1 Using wincache_unlock()
<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (wincache_lock(“lock_txt_lock”)) { // do an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
wincache_unlock(“lock_txt_lock”); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>
Building WinCache extension will require:
For completing first two steps, follow the step-by-step guide for how to » build PHP on Windows.
For getting the WinCache source code follow the instructions described in Downloading PECL extensions.
The following steps describe how to compile and build WinCache on Windows OS:
Open a command prompt which is used to build PHP
Go to the root folder where PHP sources are present
Run the command:
cscript.exe win32\build\buildconf.js
Run the command:
configure.bat --help
Run the command:
configure.js [all options used to build PHP] --enable-wincache
Run the command:
nmake
The following steps describe how to verify that WinCache has been built correctly:
Go to the folder where the PHP binaries are built
Run the command:
php.exe -n -d extension=php_wincache.dll -re wincache
XHProf is a light-weight hierarchical and instrumentation based profiler. During the data collection phase, it keeps track of call counts and inclusive metrics for arcs in the dynamic callgraph of a program. It computes exclusive metrics in the reporting/post processing phase, such as wall (elapsed) time, CPU time and memory usage. A functions profile can be broken down by callers or callees. XHProf handles recursive functions by detecting cycles in the callgraph at data collection time itself and avoiding the cycles by giving unique depth qualified names for the recursive invocations.
XHProf includes a simple HTML based user interface (written in PHP). The browser based UI for viewing profiler results makes it easy to view results or to share results with peers. A callgraph image view is also supported.
XHProf reports can often be helpful in understanding the structure of the code being executed. The hierarchical nature of the reports can be used to determine, for example, what chain of calls led to a particular function getting called.
XHProf supports ability to compare two runs (a.k.a. "diff" reports) or aggregate data from multiple runs. Diff and aggregate reports, much like single run reports, offer "flat" as well as "hierarchical" views of the profile.
Additional documentation can be found via the » facebook xhprof website.
Although not required, xhprof includes an interface that's written in PHP. It's used to save and display the profiled data in a usable way, where viewing is done via a web browser. So, a PHP enabled web server will likely make the xhprof experience more useful.
There's also a fork of the GUI interface at » http://github.com/preinheimer/xhprof
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/xhprof
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| xhprof.output_dir | "" | PHP_INI_ALL |
Here's a short explanation of the configuration directives.
xhprof.output_dir
string
Directory used by the default implementation of the iXHProfRuns interface (namely, the XHProfRuns_Default class) for storing XHProf runs.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
Example #1 Xhprof example with the optional GUI
This example starts and stops the profiler, then uses the bundled GUI interface to save and parse the results. In other words, the code from the extension itself ends at the call to xhprof_disable().
<?php
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
for ($i = 0; $i <= 1000; $i++) {
$a = $i * $i;
}
$xhprof_data = xhprof_disable();
$XHPROF_ROOT = "/tools/xhprof/";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";
$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_testing");
echo "http://localhost/xhprof/xhprof_html/index.php?run={$run_id}&source=xhprof_testing\n";
?>
The above example will output something similar to:
http://localhost/xhprof/xhprof_html/index.php?run=t11_4bdf44d21121f&source=xhprof_testing
(PECL xhprof >= 0.9.0)
xhprof_disable — Stops xhprof profiler
Stops the profiler, and returns xhprof data from the run.
This function has no parameters.
An array of xhprof data, from the run.
Example #1 xhprof_disable() example
<?php
xhprof_enable();
$foo = strlen("foo bar");
$xhprof_data = xhprof_disable();
print_r($xhprof_data);
?>
The above example will output something similar to:
Array
(
[main()==>strlen] => Array
(
[ct] => 1
[wt] => 279
)
[main()==>xhprof_disable] => Array
(
[ct] => 1
[wt] => 9
)
[main()] => Array
(
[ct] => 1
[wt] => 610
)
)
(PECL xhprof >= 0.9.0)
xhprof_enable — Start xhprof profiler
$flags = 0
[, array $options
]] )Start xhprof profiling.
flags
Optional flags to add additional information to the profiling. See the
XHprof constants for further
information about these flags, e.g., XHPROF_FLAGS_MEMORY
to enable memory profiling.
optionsAn array of optional options, namely, the 'ignored_functions' option to pass in functions to be ignored during profiling.
NULL
| Version | Description |
|---|---|
| 0.9.2 |
The optional options parameter was added.
|
Example #1 xhprof_enable() examples
<?php
// 1. elapsed time + memory + CPU profiling; and ignore built-in (internal) functions
xhprof_enable(XHPROF_FLAGS_NO_BUILTINS | XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
// 2. elapsed time profiling; ignore call_user_func* during profiling
xhprof_enable(
0,
array('ignored_functions' => array('call_user_func',
'call_user_func_array')));
// 3. elapsed time + memory profiling; ignore call_user_func* during profiling
xhprof_enable(
XHPROF_FLAGS_MEMORY,
array('ignored_functions' => array('call_user_func',
'call_user_func_array')));
?>
(PECL xhprof >= 0.9.0)
xhprof_sample_disable — Stops xhprof sample profiler
Stops the sample mode xhprof profiler, and
This function has no parameters.
An array of xhprof sample data, from the run.
Example #1 xhprof_sample_disable() example
<?php
xhprof_sample_enable();
for ($i = 0; $i <= 10000; $i++) {
$a = strlen($i);
$b = $i * $a;
$c = rand();
}
$xhprof_data = xhprof_sample_disable();
print_r($xhprof_data);
?>
The above example will output something similar to:
Array
(
[1272935300.800000] => main()
[1272935300.900000] => main()
)
(PECL xhprof >= 0.9.0)
xhprof_sample_enable — Start XHProf profiling in sampling mode
Starts profiling in sample mode, which is a lighter weight version of xhprof_enable(). The sampling interval is 0.1 seconds, and samples record the full function call stack. The main use case is when lower overhead is required when doing performance monitoring and diagnostics.
This function has no parameters.
NULL
These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.
Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.
No external libraries are needed to build this extension.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/id3.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.
ID3_V1_0
(integer)
ID3_V1_0 is used if you are working with
ID3 V1.0 tags. These tags may contain the fields title, artist,
album, genre, year and comment.
ID3_V1_1
(integer)
ID3_V1_1 is used if you are working with
ID3 V1.1 tags. These tags may all information contained in v1.0
tags plus the track number.
ID3_V2_1
(integer)
ID3_V2_1 is used if you are working with
ID3 V2.1 tags.
ID3_V2_2
(integer)
ID3_V2_2 is used if you are working with
ID3 V2.2 tags.
ID3_V2_3
(integer)
ID3_V2_3 is used if you are working with
ID3 V2.3 tags.
ID3_V2_4
(integer)
ID3_V2_4 is used if you are working with
ID3 V2.4 tags.
ID3_BEST
(integer)
ID3_BEST is used if would like to let the id3 functions
determine which tag version should be used.
(PECL id3 >= 0.2)
id3_get_frame_long_name — Get the long name of an ID3v2 frame
$frameId
)id3_get_frame_long_name() returns the long name for an ID3v2 frame.
frameIdAn ID3v2 frame
Returns the frame long name or FALSE on errors.
Example #1 id3_get_frame_long_name() example
<?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?>
The above example will output:
Original lyricist(s)/text writer(s)
(PECL id3 >= 0.2)
id3_get_frame_short_name — Get the short name of an ID3v2 frame
$frameId
)id3_get_frame_short_name() returns the short name for an ID3v2 frame.
frameIdAn ID3v2 frame
Returns the frame short name or FALSE on errors.
The values returned by id3_get_frame_short_name() are used in the array returned by id3_get_tag().
Example #1 id3_get_frame_short_name() example
<?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?>
The above example will output:
originalLyricist
(PECL id3 >= 0.1)
id3_get_genre_id — Get the id for a genre
$genre
)id3_get_genre_id() returns the id for a genre.
genreGenre name as string.
The genre id or FALSE on errors.
Example #1 id3_get_genre_id() example
<?php
$id = id3_get_genre_id("Alternative");
echo $id;
?>
The above example will output:
20
(PECL id3 >= 0.1)
id3_get_genre_list — Get all possible genre values
id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.
This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.
Returns an array containing all possible genres that may be stored in an ID3 tag.
Example #1 id3_get_genre_list() example
<?php
$genres = id3_get_genre_list();
print_r($genres);
?>
The above example will output:
Array
(
[0] => Blues
[1] => Classic Rock
[2] => Country
[3] => Dance
[4] => Disco
[5] => Funk
[6] => Grunge
[7] => Hip-Hop
[8] => Jazz
[9] => Metal
[10] => New Age
[11] => Oldies
[12] => Other
[13] => Pop
[14] => R&B
[15] => Rap
[16] => Reggae
[17] => Rock
[18] => Techno
[19] => Industrial
[20] => Alternative
[21] => Ska
[22] => Death Metal
[23] => Pranks
[24] => Soundtrack
[25] => Euro-Techno
[26] => Ambient
[27] => Trip-Hop
[28] => Vocal
[29] => Jazz+Funk
[30] => Fusion
[31] => Trance
[32] => Classical
[33] => Instrumental
[34] => Acid
[35] => House
[36] => Game
[37] => Sound Clip
[38] => Gospel
[39] => Noise
[40] => Alternative Rock
[41] => Bass
[42] => Soul
[43] => Punk
[44] => Space
[45] => Meditative
[46] => Instrumental Pop
[47] => Instrumental Rock
[48] => Ethnic
[49] => Gothic
[50] => Darkwave
[51] => Techno-Industrial
[52] => Electronic
[53] => Pop-Folk
[54] => Eurodance
[55] => Dream
[56] => Southern Rock
[57] => Comedy
[58] => Cult
[59] => Gangsta
[60] => Top 40
[61] => Christian Rap
[62] => Pop/Funk
[63] => Jungle
[64] => Native US
[65] => Cabaret
[66] => New Wave
[67] => Psychadelic
[68] => Rave
[69] => Showtunes
[70] => Trailer
[71] => Lo-Fi
[72] => Tribal
[73] => Acid Punk
[74] => Acid Jazz
[75] => Polka
[76] => Retro
[77] => Musical
[78] => Rock & Roll
[79] => Hard Rock
[80] => Folk
[81] => Folk-Rock
[82] => National Folk
[83] => Swing
[84] => Fast Fusion
[85] => Bebob
[86] => Latin
[87] => Revival
[88] => Celtic
[89] => Bluegrass
[90] => Avantgarde
[91] => Gothic Rock
[92] => Progressive Rock
[93] => Psychedelic Rock
[94] => Symphonic Rock
[95] => Slow Rock
[96] => Big Band
[97] => Chorus
[98] => Easy Listening
[99] => Acoustic
[100] => Humour
[101] => Speech
[102] => Chanson
[103] => Opera
[104] => Chamber Music
[105] => Sonata
[106] => Symphony
[107] => Booty Bass
[108] => Primus
[109] => Porn Groove
[110] => Satire
[111] => Slow Jam
[112] => Club
[113] => Tango
[114] => Samba
[115] => Folklore
[116] => Ballad
[117] => Power Ballad
[118] => Rhytmic Soul
[119] => Freestyle
[120] => Duet
[121] => Punk Rock
[122] => Drum Solo
[123] => Acapella
[124] => Euro-House
[125] => Dance Hall
[126] => Goa
[127] => Drum & Bass
[128] => Club-House
[129] => Hardcore
[130] => Terror
[131] => Indie
[132] => BritPop
[133] => Negerpunk
[134] => Polsk Punk
[135] => Beat
[136] => Christian Gangsta
[137] => Heavy Metal
[138] => Black Metal
[139] => Crossover
[140] => Contemporary C
[141] => Christian Rock
[142] => Merengue
[143] => Salsa
[144] => Thrash Metal
[145] => Anime
[146] => JPop
[147] => SynthPop
)
(PECL id3 >= 0.1)
id3_get_genre_name — Get the name for a genre id
$genre_id
)id3_get_genre_name() returns the name for a genre id.
genre_idAn integer ranging from 0 to 147
Returns the name as a string.
Example #1 id3_get_genre_name() example
<?php
$genre = id3_get_genre_name(20);
echo $genre;
?>
The above example will output:
Alternative
(PECL id3 >= 0.1)
id3_get_tag — Get all information stored in an ID3 tag
$filename
[, int $version = ID3_BEST
] )id3_get_tag() is used to get all information stored in the id3 tag of the specified file.
filenameThe path to the MP3 file
Instead of a filename you may also pass a valid stream resource
versionAllows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags
Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter. ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.
Returns an associative array with various keys like: title, artist, ..
The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.
Example #1 id3_get_tag() example
<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>
The above example will output something similar to:
Array
(
[title] => DN-38416
[artist] => Re:\Legion
[album] => Reflections
[year] => 2004
[genre] => 19
)
Example #2 id3_get_tag() example
<?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?>
The above example will output something similar to:
Array
(
[copyright] => Dirty Mac
[originalArtist] => Dirty Mac
[composer] => Marcus Götze
[artist] => Dirty Mac
[title] => Little Big Man
[album] => Demo-Tape
[track] => 5/12
[genre] => (17)Rock
[year] => 2001
)
(PECL id3 >= 0.1)
id3_get_version — Get version of an ID3 tag
$filename
)id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file.
If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.
filenameThe path to the MP3 file
Instead of a filename you may also pass a valid stream resource
Returns the version number of the ID3 tag of the file.
As a tag can contain ID3 v1.x and v2.x tags, the return value of this
function should be bitwise compared with the predefined constants
ID3_V1_0, ID3_V1_1 and
ID3_V2.
Example #1 id3_get_version() example
<?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version & ID3_V1_0) {
echo "Contains a 1.x tag\n";
}
if ($version & ID3_V1_1) {
echo "Contains a 1.1 tag\n";
}
if ($version & ID3_V2) {
echo "Contains a 2.x tag\n";
}
?>
The above example will output something similar to:
Contains a 1.x tag Contains a 1.1 tag
(PECL id3 >= 0.1)
id3_remove_tag — Remove an existing ID3 tag
$filename
[, int $version = ID3_V1_0
] )id3_remove_tag() is used to remove the information stored of an ID3 tag.
filenameThe path to the MP3 file
Instead of a filename you may also pass a valid stream resource
versionAllows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Returns TRUE on success or FALSE on failure.
Example #1 id3_remove_tag() example
<?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
echo "Tag successfully removed\n";
}
?>
If the file is writable and contained a 1.0 tag, this will output:
Tag successfully removed
Note: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.
(PECL id3 >= 0.1)
id3_set_tag — Update information stored in an ID3 tag
$filename
, array $tag
[, int $version = ID3_V1_0
] )id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.
filenameThe path to the MP3 file
Instead of a filename you may also pass a valid stream resource
tagAn associative array of tag keys and values
The following keys may be used in the associative array:
| key | possible value | available in version |
|---|---|---|
| title | string with maximum of 30 characters | v1.0, v1.1 |
| artist | string with maximum of 30 characters | v1.0, v1.1 |
| album | string with maximum of 30 characters | v1.0, v1.1 |
| year | 4 digits | v1.0, v1.1 |
| genre | integer value between 0 and 147 | v1.0, v1.1 |
| comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1 |
| track | integer between 0 and 255 | v1.1 |
versionAllows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags
Returns TRUE on success or FALSE on failure.
Example #1 id3_set_tag() example
<?php
$data = array(
"title" => "Re:Start",
"artist" => "Re:\Legion",
"comment" => "A nice track"
);
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
echo "Tag successfully updated\n";
}
?>
If the file is writable, this will output:
Tag successfully updated
Note: Currently id3_set_tag() only supports version 1.0 and 1.1.
KTaglib is an object oriented binding to the taglib library from the KDE project used in projects like Amarok to read and write ID3 and Ogg tags. The library also provides access to audio information. The bindings are designed usually follow the underlying C++ API, but were changed whenever there is a more PHP-like way.
Note:
At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.
If you want to build ktaglib you need at least taglib 1.5 installed. To obtain the taglib see the » taglib project page. Windows DLL's are build static against taglib, therefore there is no need to have taglib installed.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ktaglib.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.
KTaglib_MPEG_Header::Version1
(integer)
KTaglib_MPEG_Header::Version2
(integer)
KTaglib_MPEG_Header::Version2_5
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Other
(integer)
KTaglib_ID3v2_AttachedPictureFrame::FileIcon
(integer)
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon
(integer)
KTaglib_ID3v2_AttachedPictureFrame::FrontCover
(integer)
KTaglib_ID3v2_AttachedPictureFrame::BackCover
(integer)
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Media
(integer)
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Artist
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Conductor
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Band
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Composer
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Lyricist
(integer)
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation
(integer)
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording
(integer)
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance
(integer)
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture
(integer)
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish
(integer)
KTaglib_ID3v2_AttachedPictureFrame::Illustration
(integer)
KTaglib_ID3v2_AttachedPictureFrame::BandLogo
(integer)
(0.0.1)
Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.
(0.0.1)
KTaglib_MPEG_File::__construct — Opens a new file
$filename
)Opens a new MPEG file.
filenameThe file to read
Example #1 Opens a new MP3 file and read the title
<?php
$mpeg = new KTaglib_MPEG_File('example.mp3');
echo $mpeg->getID3v1Tag()->getTitle();
?>
(0.0.1)
KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
Returns an object that provides access to the audio properties of the mpeg file.
Returns an KTaglib_MPEG_AudioProperties object or false.
(0.0.1)
KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
$create = false
] )Returns an object that represents an ID3v1 tag, which can be used to get information about the ID3v1 tag.
Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.
(0.0.1)
KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an KTaglib_TagNotFoundException is thrown.
Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is no ID3v2 tag
(0.0.1)
Represents the audio properties of a MPEG file, like length, bitrate or samplerate.
(0.0.1)
KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
Returns the bitrate of the MPEG file
Returns the bitrate as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
Returns the amount of channels of the MPEG file
Returns the channel count as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
Returns the layer of the MPEG file (usually 3 for MP3).
Returns the layer as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
Returns the length of the MPEG file
Returns the length as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
Returns the sample bitrate of the MPEG file
Returns the sample bitrate as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
Returns the version of the MPEG file header. The possible versions are defined in Tag_MPEG_Header (Version1, Version2, Version2.5).
Returns the version
(0.0.1)
KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the copyright status of an MPEG file
Returns true if the MPEG file is copyrighted
Returns true if the MPEG file is copyrighted
(0.0.1)
KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file
Returns true if the file is marked as the original file
Returns true if the file is marked as the original file
(0.0.1)
KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled
Returns true if protection mechanisms (like DRM) are enabled for this file
Returns true if protection mechanisms (like DRM) are enabled for this file
(0.0.1)
Base class for ID3v1 or ID3v2 tags
(0.0.1)
KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the album string
(0.0.1)
KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the artist string
(0.0.1)
KTaglib_Tag::getComment — Returns the comment from a ID3 tag
Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the comment string
(0.0.1)
KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the genre string
(0.0.1)
KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the title string
(0.0.1)
KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the track number as an integer
(0.0.1)
KTaglib_Tag::getYear — Returns the year from a ID3 tag
Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the year as an integer
(0.0.1)
KTaglib_Tag::isEmpty — Returns true if the tag is empty
Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.
Returns true if the tag is empty, otherwise false.
(0.0.1)
Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be used to add and remove additional frames.
(0.0.1)
KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
Adds a frame to the ID3v2 tag. The frame must be a valid KTaglib_ID3v2_Frame object. To save the tag, the save function needs to be invoked.
Returns true on success, otherwise false.
(0.0.1)
KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
Returns an array of ID3v2 frames, associated with the ID3v2 tag.
Return an array of KTaglib_ID3v2_Frame objects
(0.0.1)
The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.
(0.0.1)
KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
Returns the size of the frame in bytes. Please refer to id3.org to see what ID3v2 frames are and how they are defined.
Returns the size of the frame in bytes
(0.0.1)
KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
Returns a string representation of the frame. This might be just the frame id, but might contain more information. Please see the ktaglib documentation for more information
Returns a string representation of the frame.
(0.0.1)
Represents an ID3v2 frame that can hold a picture.
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
Returns the attached description for a picture frame in an ID3v2.x frame.
Returns a description for the picture in a picture frame
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
Returns the mime type of the image represented by the attached picture frame.
Please notice that this method might return different types. While ID3v2.2 have a mime type that doesn't start with "image/", ID3v2.3 and v2.4 usually start with "image/". Therefore the method might return "image/png" for IDv2.3 frames and just "PNG" for ID3v2.2 frames.
Notice that even the frame is an attached picture, the mime type might not be set and therefore an empty string might be returned.
Returns the mime type of the image represented by the attached picture frame.
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
Returns the type of the image.
The ID3v2 specification allows an AttachedPictureFrame to set the type of an image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types.
Returns the integer representation of the type.
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
$filename
)Saves the attached picture to the given filename.
Returns true on success, otherwise false
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
Sets the mime type of the image. This should in most cases be "image/png" or "image/jpeg".
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
$filename
)Sets the picture to the give image. The image is loaded from the given filename. Please note that the picture is not saved unless you call the save method of the corresponding file object.
Returns true on success, otherwise false
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image
$type
)Sets the type of the image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types and their constant mappings.
The OGG/Vorbis file format, as defined by » http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed below.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/oggvorbis
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
| Constant | Definition |
|---|---|
OGGVORBIS_PCM_U8 |
Unsigned 8-bit PCM. |
OGGVORBIS_PCM_S8 |
Signed 8-bit PCM. |
OGGVORBIS_PCM_U16_LE |
Unsigned 16-bit PCM. Little Endian byte order. |
OGGVORBIS_PCM_U16_BE |
Unsigned 16-bit PCM. Big Endian byte order. |
OGGVORBIS_PCM_S16_LE |
Signed 16-bit PCM. Little Endian byte order. |
OGGVORBIS_PCM_S16_BE |
Signed 16-bit PCM. Big Endian byte order. |
| Option | Definition | Relevance | Default |
|---|---|---|---|
| pcm_mode | PCM byte encoding used. See constants below. | Read / Write | OGGVORBIS_PCM_S16_LE |
| rate | PCM Sampling rate. Measured in Hz. | Write only | 44100 |
| bitrate | Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. | Write only | 128000 |
| channels | Number of PCM channels. 1 == Mono, 2 == Stereo. | Write only | 2 |
| serialno | Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. | Write only | Random |
| comments | Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 | Write only | array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis') |
Example #1 Reading an OGG/Vorbis file
<?php
dl("oggvorbis.so");
/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp = fopen('ogg://myaudio.ogg', 'r');
/* Collect some information about the file. */
$metadata = stream_get_meta_data($fp);
/* Inspect the first song (usually the only song,
but OGG/Vorbis files may be chained) */
$songdata = $metadata['wrapper_data'][0];
echo "OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo " {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach($songdata['comments'] as $comment) {
echo " $comment\n";
}
while ($audio_data = fread($fp, 8192)) {
/* Do something with the PCM audio we're extracting from the OGG.
Copying to /dev/dsp is a good target on linux systems,
just remember to setup the device for your sampling mode first. */
}
fclose($fp);
?>
Example #2 Encode an audio file to OGG/Vorbis
<?php
dl('oggvorbis.so');
$context = stream_context_create(array('ogg'=>array(
'pcm_mode' => OGGVORBIS_PCM_S8, /* Signed 8bit audio */
'rate' => 44100, /* 44kHz CD quality */
'bitrate' => 0.5, /* Midquality VBR */
'channels' => 1, /* Mono */
'serialno' => 12345))); /* Unique within our stream */
/* Open file for appending. This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);
$pcm = fopen('mysample.pcm', 'r');
/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);
fclose($pcm);
fclose($ogg);
?>
No external libraries are needed to build this extension.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/openal.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension defines four resource types: Open AL(Device) - Returned by openal_device_open(), Open AL(Context) - Returned by openal_context_create(), Open AL(Buffer) - Returned by openal_buffer_create(), and Open AL(Source) - Returned by openal_source_create().
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
ALC_FREQUENCY
(integer)
ALC_REFRESH
(integer)
ALC_SYNC
(integer)
AL_FREQUENCY
(integer)
AL_BITS
(integer)
AL_CHANNELS
(integer)
AL_SIZE
(integer)
AL_BUFFER
(integer)
AL_SOURCE_RELATIVE
(integer)
AL_SOURCE_STATE
(integer)
AL_PITCH
(integer)
AL_GAIN
(integer)
AL_MIN_GAIN
(integer)
AL_MAX_GAIN
(integer)
AL_MAX_DISTANCE
(integer)
AL_ROLLOFF_FACTOR
(integer)
AL_CONE_OUTER_GAIN
(integer)
AL_CONE_INNER_ANGLE
(integer)
AL_CONE_OUTER_ANGLE
(integer)
AL_REFERENCE_DISTANCE
(integer)
AL_POSITION
(integer)
AL_VELOCITY
(integer)
AL_DIRECTION
(integer)
AL_ORIENTATION
(integer)
AL_FORMAT_MONO8
(integer)
AL_FORMAT_MONO16
(integer)
AL_FORMAT_STEREO8
(integer)
AL_FORMAT_STEREO16
(integer)
AL_INITIAL
(integer)
AL_PLAYING
(integer)
AL_PAUSED
(integer)
AL_STOPPED
(integer)
AL_LOOPING
(integer)
AL_TRUE
(integer)
AL_FALSE
(integer)
(PECL openal >= 0.1.0)
openal_buffer_create — Generate OpenAL buffer
Returns an Open AL(Buffer) resource on success or
FALSE on failure.
(PECL openal >= 0.1.0)
openal_buffer_data — Load a buffer with data
$buffer
, int $format
, string $data
, int $freq
)bufferAn Open AL(Buffer) resource (previously created by openal_buffer_create()).
format
Format of data, one of:
AL_FORMAT_MONO8,
AL_FORMAT_MONO16,
AL_FORMAT_STEREO8 and
AL_FORMAT_STEREO16
data
Block of binary audio data in the format and
freq specified.
freq
Frequency of data given in Hz.
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_buffer_destroy — Destroys an OpenAL buffer
$buffer
)bufferAn Open AL(Buffer) resource (previously created by openal_buffer_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_buffer_get — Retrieve an OpenAL buffer property
$buffer
, int $property
)bufferAn Open AL(Buffer) resource (previously created by openal_buffer_create()).
property
Specific property, one of:
AL_FREQUENCY,
AL_BITS,
AL_CHANNELS and
AL_SIZE.
Returns an integer value appropriate to the property
requested or FALSE on failure.
(PECL openal >= 0.1.0)
openal_buffer_loadwav — Load a .wav file into a buffer
$buffer
, string $wavfile
)bufferAn Open AL(Buffer) resource (previously created by openal_buffer_create()).
wavfilePath to .wav file on local file system.
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_context_create — Create an audio processing context
$device
)deviceAn Open AL(Device) resource (previously created by openal_device_open()).
Returns an Open AL(Context) resource on success or
FALSE on failure.
(PECL openal >= 0.1.0)
openal_context_current — Make the specified context current
$context
)contextAn Open AL(Context) resource (previously created by openal_context_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_context_destroy — Destroys a context
$context
)contextAn Open AL(Context) resource (previously created by openal_context_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_context_process — Process the specified context
$context
)contextAn Open AL(Context) resource (previously created by openal_context_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_context_suspend — Suspend the specified context
$context
)contextAn Open AL(Context) resource (previously created by openal_context_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_device_close — Close an OpenAL device
$device
)deviceAn Open AL(Device) resource (previously created by openal_device_open()) to be closed.
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_device_open — Initialize the OpenAL audio layer
$device_desc
] )device_desc
Open an audio device optionally specified by device_desc.
If device_desc is not specified the first available audio
device will be used.
Returns an Open AL(Device) resource on success or
FALSE on failure.
(PECL openal >= 0.1.0)
openal_listener_get — Retrieve a listener property
property
Property to retrieve, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) and
AL_ORIENTATION (array(float,float,float)).
Returns a float or array of floats (as appropriate) or FALSE on failure.
(PECL openal >= 0.1.0)
openal_listener_set — Set a listener property
property
Property to set, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) and
AL_ORIENTATION (array(float,float,float)).
settingValue to set, either float, or an array of floats as appropriate.
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_create — Generate a source resource
Returns an Open AL(Source) resource on success or
FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_destroy — Destroy a source resource
$source
)sourceAn Open AL(Source) resource (previously created by openal_source_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_get — Retrieve an OpenAL source property
sourceAn Open AL(Source) resource (previously created by openal_source_create()).
property
Property to get, one of:
AL_SOURCE_RELATIVE (int),
AL_SOURCE_STATE (int),
AL_PITCH (float),
AL_GAIN (float),
AL_MIN_GAIN (float),
AL_MAX_GAIN (float),
AL_MAX_DISTANCE (float),
AL_ROLLOFF_FACTOR (float),
AL_CONE_OUTER_GAIN (float),
AL_CONE_INNER_ANGLE (float),
AL_CONE_OUTER_ANGLE (float),
AL_REFERENCE_DISTANCE (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)),
AL_DIRECTION (array(float,float,float)).
Returns the type associated with the property being retrieved
or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_pause — Pause the source
$source
)sourceAn Open AL(Source) resource (previously created by openal_source_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_play — Start playing the source
$source
)sourceAn Open AL(Source) resource (previously created by openal_source_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_rewind — Rewind the source
$source
)sourceAn Open AL(Source) resource (previously created by openal_source_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_set — Set source property
sourceAn Open AL(Source) resource (previously created by openal_source_create()).
property
Property to set, one of:
AL_BUFFER (OpenAL(Source)),
AL_LOOPING (bool),
AL_SOURCE_RELATIVE (int),
AL_SOURCE_STATE (int),
AL_PITCH (float),
AL_GAIN (float),
AL_MIN_GAIN (float),
AL_MAX_GAIN (float),
AL_MAX_DISTANCE (float),
AL_ROLLOFF_FACTOR (float),
AL_CONE_OUTER_GAIN (float),
AL_CONE_INNER_ANGLE (float),
AL_CONE_OUTER_ANGLE (float),
AL_REFERENCE_DISTANCE (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)),
AL_DIRECTION (array(float,float,float)).
setting
Value to assign to specified property.
Refer to the description of property
for a description of the value(s) expected.
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_stop — Stop playing the source
$source
)sourceAn Open AL(Source) resource (previously created by openal_source_create()).
Returns TRUE on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_stream — Begin streaming on a source
$source
, int $format
, int $rate
)sourceAn Open AL(Source) resource (previously created by openal_source_create()).
format
Format of data, one of:
AL_FORMAT_MONO8,
AL_FORMAT_MONO16,
AL_FORMAT_STEREO8 and
AL_FORMAT_STEREO16
rateFrequency of data to stream given in Hz.
Returns a stream resource on success or FALSE on failure.
These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.
More information about Kerberos can be found at » http://web.mit.edu/kerberos/www/.
Documentation for Kerberos and KADM5 can be found at » http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.
No external libraries are needed to build this extension.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/kadm5.
Note:
If this option is used without specifying the path to KADM5, PHP will use the built-in KADM5 client libraries. Users who run other applications that use KADM5 (for example, running PHP 4 and PHP 5 as concurrent apache modules, or auth-kadm5) should always specify the path to KADM5: --with-kadm5=/path/to/kadm5. This will force PHP to use the client libraries installed by KADM5, avoiding any conflicts.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_modify_principal() allow to specify special attributes using a bitfield. The symbols are defined below:
| constant |
|---|
| KRB5_KDB_DISALLOW_POSTDATED |
| KRB5_KDB_DISALLOW_FORWARDABLE |
| KRB5_KDB_DISALLOW_TGT_BASED |
| KRB5_KDB_DISALLOW_RENEWABLE |
| KRB5_KDB_DISALLOW_PROXIABLE |
| KRB5_KDB_DISALLOW_DUP_SKEY |
| KRB5_KDB_DISALLOW_ALL_TIX |
| KRB5_KDB_REQUIRES_PRE_AUTH |
| KRB5_KDB_REQUIRES_HW_AUTH |
| KRB5_KDB_REQUIRES_PWCHANGE |
| KRB5_KDB_DISALLOW_SVR |
| KRB5_KDB_PWCHANGE_SERVER |
| KRB5_KDB_SUPPORT_DESMD5 |
| KRB5_KDB_NEW_PRINC |
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_get_principal() allow to specify or return principal's options as an associative array. The keys for the associative array are defined as string constants below:
| constant | funcdef | description |
|---|---|---|
| KADM5_PRINCIPAL | long | The expire time of the princial as a Kerberos timestamp. |
| KADM5_PRINC_EXPIRE_TIME | long | The expire time of the princial as a Kerberos timestamp. |
| KADM5_LAST_PW_CHANGE | long | The time this principal's password was last changed. |
| KADM5_PW_EXPIRATION | long | The expire time of the principal's current password, as a Kerberos timestamp. |
| KADM5_MAX_LIFE | long | The maximum lifetime of any Kerberos ticket issued to this principal. |
| KADM5_MAX_RLIFE | long | The maximum renewable lifetime of any Kerberos ticket issued to or for this principal. |
| KADM5_MOD_NAME | string | The name of the Kerberos principal that most recently modified this principal. |
| KADM5_MOD_TIME | long | The time this principal was last modified, as a Kerberos timestamp. |
| KADM5_KVNO | long | The version of the principal's current key. |
| KADM5_POLICY | string | The name of the policy controlling this principal. |
| KADM5_CLEARPOLICY | long | Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour. |
| KADM5_LAST_SUCCESS | long | The KDC time of the last successfull AS_REQ. |
| KADM5_LAST_FAILED | long | The KDC time of the last failed AS_REQ. |
| KADM5_FAIL_AUTH_COUNT | long | The number of consecutive failed AS_REQs. |
| KADM5_RANDKEY | long |
Generates a random password for the principal. The parameter
password will be ignored.
|
| KADM5_ATTRIBUTES | long | A bitfield of attributes for use by the KDC. |
This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.
Example #1 KADM5 extension overview example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_principals</h1>\n";
$principals = kadm5_get_principals($handle);
for( $i=0; $i<count($principals); $i++)
print "$principals[$i]<br>\n";
print "<h1>get_policies</h1>\n";
$policies = kadm5_get_policies($handle);
for( $i=0; $i<count($policies); $i++)
print "$policies[$i]<br>\n";
print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";
$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
$keys = array_keys($options);
for( $i=0; $i<count($keys); $i++) {
$value = $options[$keys[$i]];
print "$keys[$i]: $value<br>\n";
}
$options = array(KADM5_PRINC_EXPIRE_TIME => 0);
kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_chpass_principal — Changes the principal's password
$handle
, string $principal
, string $password
)
kadm5_chpass_principal() sets the new password
password for the principal.
handleA KADM5 handle.
principalThe principal.
passwordThe new password.
Returns TRUE on success or FALSE on failure.
Example #1 Example of changing principal's password
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_create_principal — Creates a kerberos principal with the given parameters
$handle
, string $principal
[, string $password
[, array $options
]] )
Creates a principal with the given
password.
handleA KADM5 handle.
principalThe principal.
password
If password is omitted or is NULL, a random
key will be generated.
options
It is possible to specify several optional parameters within the
array options. Allowed are the following options:
KADM5_PRINC_EXPIRE_TIME,
KADM5_PW_EXPIRATION,
KADM5_ATTRIBUTES,
KADM5_MAX_LIFE,
KADM5_KVNO,
KADM5_POLICY,
KADM5_CLEARPOLICY,
KADM5_MAX_RLIFE.
Returns TRUE on success or FALSE on failure.
Example #1 Example of principal's creation
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
KADM5_POLICY => "default",
KADM5_ATTRIBUTES => $attributes);
kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_delete_principal — Deletes a kerberos principal
$handle
, string $principal
)
Removes the principal from the Kerberos database.
handleA KADM5 handle.
principalThe removed principal.
Returns TRUE on success or FALSE on failure.
Example #1 kadm5_delete_principal() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_destroy — Closes the connection to the admin server and releases all related resources
$handle
)Closes the connection to the admin server and releases all related resources.
handleA KADM5 handle.
Returns TRUE on success or FALSE on failure.
(PECL kadm5 >= 0.2.3)
kadm5_flush — Flush all changes to the Kerberos database
$handle
)Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.
handleA KADM5 handle.
Returns TRUE on success or FALSE on failure.
(PECL kadm5 >= 0.2.3)
kadm5_get_policies — Gets all policies from the Kerberos database
$handle
)Gets an array containing the policies's names.
handleA KADM5 handle.
Returns array of policies on success or FALSE on failure.
Example #1 kadm5_get_policies() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_policies</h1>\n";
foreach (kadm5_get_policies($handle) as $policy) {
echo "$policy<br />\n";
}
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_get_principal — Gets the principal's entries from the Kerberos database
$handle
, string $principal
)Gets the principal's entries from the Kerberos database.
handleA KADM5 handle.
principalThe principal.
Returns array of options containing the following keys: KADM5_PRINCIPAL,
KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES,
KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY,
KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED,
KADM5_FAIL_AUTH_COUNT on success or FALSE on failure.
Example #1 kadm5_get_principal() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";
$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
foreach ($options as $key => $value) {
echo "$key: $value<br />\n";
}
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_get_principals — Gets all principals from the Kerberos database
$handle
)kadm5_get_principals() returns an array containing the principals's names.
handleA KADM5 handle.
Returns array of principals on success or FALSE on failure.
Example #1 kadm5_get_principals() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_principals</h1>\n";
foreach (kadm5_get_principals($handle) as $principal) {
echo "$principal<br />\n";
}
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_init_with_password — Opens a connection to the KADM5 library
$admin_server
, string $realm
, string $principal
, string $password
)
Opens a connection with the KADM5 library using the
principal and the given
password to obtain initial credentials from the
admin_server.
admin_serverThe server.
realmDefines the authentication domain for the connection.
principalThe principal.
password
If password is omitted or is NULL, a random
key will be generated.
Returns a KADM5 handle on success or FALSE on failure.
Example #1 KADM5 initialization example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
KADM5_POLICY => "default",
KADM5_ATTRIBUTES => $attributes);
kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);
kadm5_destroy($handle);
?>
Note:
Connection should be closed after use with kadm5_destroy().
(PECL kadm5 >= 0.2.3)
kadm5_modify_principal — Modifies a kerberos principal with the given parameters
$handle
, string $principal
, array $options
)
Modifies a principal according to the given
options.
handleA KADM5 handle.
principalThe principal.
options
It is possible to specify several optional parameters within the
array options. Allowed are the following options:
KADM5_PRINC_EXPIRE_TIME,
KADM5_PW_EXPIRATION,
KADM5_ATTRIBUTES,
KADM5_MAX_LIFE,
KADM5_KVNO,
KADM5_POLICY,
KADM5_CLEARPOLICY,
KADM5_MAX_RLIFE.
KADM5_FAIL_AUTH_COUNT.
Returns TRUE on success or FALSE on failure.
Example #1 Example of modifying principal
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
$attributes = KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME => 3451234,
KADM5_POLICY => "gonicus",
KADM5_ATTRIBUTES => $attributes);
kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);
kadm5_destroy($handle);
?>
This package is based on the libradius (Remote Authentication Dial In User Service) of FreeBSD. It allows clients to perform authentication and accounting by means of network requests to remote servers.
This PECL extension adds full support for Radius Authentication (» RFC 2865) and Radius Accounting (» RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.
Note:
An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.
No external libraries are needed to build this extension.
This » PECL extension is not bundled with PHP.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/radius.
A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
RADIUS_MPPE_KEY_LEN
(integer)
Several RADIUS functions accept option flags as bitmasks. The constants representing those flags are listed below.
RADIUS packets, whether requests or responses, always include a type. These constants are provided to make it easier to specify types when using radius_create_request() and when comparing the result of radius_send_request().
RADIUS_ACCESS_REQUEST
(integer)
An Access-Request, used to authenticate a user against a RADIUS server.
Access request packets must include a
RADIUS_NAS_IP_ADDRESS
or a
RADIUS_NAS_IDENTIFIER
attribute, must also include a
RADIUS_USER_PASSWORD,
RADIUS_CHAP_PASSWORD
or a
RADIUS_STATE
attribute, and should include a
RADIUS_USER_NAME
attribute.
RADIUS_ACCESS_ACCEPT
(integer)
An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.
RADIUS_ACCESS_REJECT
(integer)
An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.
RADIUS_ACCESS_CHALLENGE
(integer)
An Access-Challenge response to an Access-Request indicating that the RADIUS server requires further information in another Access-Request before authenticating the user.
RADIUS_ACCOUNTING_REQUEST
(integer)
An Accounting-Request, used to convey accounting information for a service to the RADIUS server.
RADIUS_ACCOUNTING_RESPONSE
(integer)
An Accounting-Response response to an Accounting-Request.
RADIUS_COA_REQUEST
(integer)
A CoA-Request, sent from the RADIUS server to indicate that the authorisations within the user session have changed. A response must be sent in the form of a CoA-ACK or a CoA-NAK.
This constant is available in PECL radius 1.3.0 and later.
RADIUS_COA_ACK
(integer)
A CoA-ACK, sent to the RADIUS server to indicate that the user authorisations have been updated.
This constant is available in PECL radius 1.3.0 and later.
RADIUS_COA_NAK
(integer)
A CoA-NAK, sent to the RADIUS server to indicate that the user authorisations could not be updated.
This constant is available in PECL radius 1.3.0 and later.
RADIUS_DISCONNECT_REQUEST
(integer)
A Disconnect-Request, sent from the RADIUS server to indicate that the user session must be terminated.
This constant is available in PECL radius 1.3.0 and later.
RADIUS_DISCONNECT_ACK
(integer)
A Disconnect-ACK, sent to the RADIUS server to indicate that the user session has been terminated.
This constant is available in PECL radius 1.3.0 and later.
RADIUS_DISCONNECT_NAK
(integer)
A Disconnect-NAK, sent to the RADIUS server to indicate that the user session could not be terminated.
This constant is available in PECL radius 1.3.0 and later.
These constants define RADIUS attribute types that can be used with radius_put_addr(), radius_put_attr(), radius_put_int() and radius_put_string().
RADIUS_USER_NAME
(integer)
The User-Name attribute. The attribute value is expected to be a string containing the name of the user being authenticated, and can be set using radius_put_attr().
RADIUS_USER_PASSWORD
(integer)
The User-Password attribute. The attribute value is expected to be a string containing the user's password, and can be set using radius_put_attr(). This value will be obfuscated on transmission as described in » section 5.2 of RFC 2865.
RADIUS_CHAP_PASSWORD
(integer)
The Chap-Password attribute. The attribute value is expected to be a
string with the first byte containing the CHAP identifier,
and the subsequent 16 bytes containing the MD5 hash of the CHAP
identifier, the plaintext password and the CHAP challenge value
concatenated together. Note that the CHAP challenge value should also be
sent separately in a
RADIUS_CHAP_CHALLENGE
attribute.
Example #1 Using CHAP passwords
<?php
// Firstly, we'll create an authentication handle and request.
$radh = radius_auth_open();
radius_add_server($radh, $server, $port, $secret, 3, 3);
radius_create_request($radh, RADIUS_ACCESS_REQUEST);
// Assuming $password contains the plaintext password, we now:
// Generate a challenge.
$challenge = mt_rand();
// Specify a CHAP identifier.
$ident = 1;
// Add the Chap-Password attribute.
$cp = md5(pack('Ca*', $ident, $password.$challenge), true);
radius_put_attr($radh, RADIUS_CHAP_PASSWORD, pack('C', $ident).$cp);
// Add the Chap-Challenge attribute.
radius_put_attr($radh, RADIUS_CHAP_CHALLENGE, $challenge);
/* From here, you would add the remaining attributes and
* call radius_send_request(). */
?>
RADIUS_NAS_IP_ADDRESS
(integer)
The NAS-IP-Address attribute. The attribute value is expected to the IP address of the RADIUS client encoded as an integer, which can be set using radius_put_addr().
RADIUS_NAS_PORT
(integer)
The NAS-Port attribute. The attribute value is expected to be the physical port of the user on the RADIUS client encoded as an integer, which can be set using radius_put_int().
RADIUS_SERVICE_TYPE
(integer)
The Service-Type attribute. The attribute value indicates the service type the user is requesting, and is expected to be an integer, which can be set using radius_put_int().
A number of constants are provided to represent the possible values of this attribute. They include:
RADIUS_LOGINRADIUS_FRAMEDRADIUS_CALLBACK_LOGINRADIUS_CALLBACK_FRAMEDRADIUS_OUTBOUNDRADIUS_ADMINISTRATIVERADIUS_NAS_PROMPTRADIUS_AUTHENTICATE_ONLYRADIUS_CALLBACK_NAS_PROMPTRADIUS_FRAMED_PROTOCOL
(integer)
The Framed-Protocol attribute. The attribute value is expected to be an integer indicating the framing to be used for framed access, and can be set using radius_put_int(). The possible attribute values include these constants:
RADIUS_PPPRADIUS_SLIPRADIUS_ARAPRADIUS_GANDALFRADIUS_XYLOGICSRADIUS_FRAMED_IP_ADDRESS
(integer)
The Framed-IP-Address attribute. The attribute value is expected to be the address of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().
RADIUS_FRAMED_IP_NETMASK
(integer)
The Framed-IP-Netmask attribute. The attribute value is expected to be the netmask of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().
RADIUS_FRAMED_ROUTING
(integer)
The Framed-Routing attribute. The attribute value is expected to be an integer indicating the routing method for the user, which can be set using radius_put_int().
Possible values include:
RADIUS_FILTER_ID
(integer)
The Filter-ID attribute. The attribute value is expected to be an implementation-specific, human-readable string of filters, which can be set using radius_put_attr().
RADIUS_FRAMED_MTU
(integer)
The Framed-MTU attribute. The attribute value is expected to be an integer indicating the MTU to be configured for the user, and can be set using radius_put_int().
RADIUS_FRAMED_COMPRESSION
(integer)
The Framed-Compression attribute. The attribute value is expected to be an integer indicating the compression protocol to be used, and can be set using radius_put_int(). Possible values include these constants:
RADIUS_COMP_NONE: No compressionRADIUS_COMP_VJ: VJ TCP/IP header compressionRADIUS_COMP_IPXHDR: IPX header compressionRADIUS_COMP_STAC_LZS:
Stac-LZS compression (added in PECL radius 1.3.0b2)
RADIUS_LOGIN_IP_HOST
(integer)
The Login-IP-Host attribute. The attribute value is expected to the IP address to connect the user to, encoded as an integer, which can be set using radius_put_addr().
RADIUS_LOGIN_SERVICE
(integer)
The Login-Service attribute. The attribute value is an integer indicating the service to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().
RADIUS_LOGIN_TCP_PORT
(integer)
The Login-TCP-Port attribute. The attribute value is an integer indicating the port to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().
RADIUS_REPLY_MESSAGE
(integer)
The Reply-Message attribute. The attribute value is a string containing text that may be displayed to the user in response to an access request.
RADIUS_CALLBACK_NUMBER
(integer)
The Callback-Number attribute. The attribute value is a string containing the dialing string to use for callback.
RADIUS_CALLBACK_ID
(integer)
The Callback-Id attribute. The attribute value is a string containing an implementation-specific name of the place to be called.
RADIUS_FRAMED_ROUTE
(integer)
The Framed-Route attribute. The attribute value is a string containing an implementation-specific set of routes to be configured for the user.
RADIUS_FRAMED_IPX_NETWORK
(integer)
The Framed-IPX-Network attribute. The attribute value is an integer containing the IPX network to be configured for the user, or 0xFFFFFFFE to indicate that the RADIUS client should select the network, and can be accessed via radius_cvt_int().
RADIUS_STATE
(integer)
The State attribute. The attribute value is an implementation-defined string included in an Access-Challenge from a server that must be included in the subsequent Access-Request, and can be set using radius_put_attr().
RADIUS_CLASS
(integer)
The Class attribute. The attribute value is an arbitrary string included in an Access-Accept message that should then be sent to the accounting server in Accounting-Request messages, and can be set using radius_put_attr().
RADIUS_VENDOR_SPECIFIC
(integer)
The Vendor-Specific attribute. In general, vendor attribute values should be set using radius_put_vendor_addr(), radius_put_vendor_attr(), radius_put_vendor_int() and radius_put_vendor_string(), rather than directly.
This constant is mostly useful when interpreting vendor specific attributes in responses from a RADIUS server; when a vendor specific attribute is received, the radius_get_vendor_attr() function should be used to access the vendor ID, attribute type and attribute value.
RADIUS_SESSION_TIMEOUT
(integer)
Session timeout
RADIUS_IDLE_TIMEOUT
(integer)
Idle timeout
RADIUS_TERMINATION_ACTION
(integer)
Termination action
RADIUS_CALLED_STATION_ID
(integer)
Called Station Id
RADIUS_CALLING_STATION_ID
(integer)
Calling Station Id
RADIUS_NAS_IDENTIFIER
(integer)
NAS ID
RADIUS_PROXY_STATE
(integer)
Proxy State
RADIUS_LOGIN_LAT_SERVICE
(integer)
Login LAT Service
RADIUS_LOGIN_LAT_NODE
(integer)
Login LAT Node
RADIUS_LOGIN_LAT_GROUP
(integer)
Login LAT Group
RADIUS_FRAMED_APPLETALK_LINK
(integer)
Framed Appletalk Link
RADIUS_FRAMED_APPLETALK_NETWORK
(integer)
Framed Appletalk Network
RADIUS_FRAMED_APPLETALK_ZONE
(integer)
Framed Appletalk Zone
RADIUS_CHAP_CHALLENGE
(integer)
Challenge
RADIUS_NAS_PORT_TYPE
(integer)
NAS port type, one of:
RADIUS_ASYNCRADIUS_SYNCRADIUS_ISDN_SYNCRADIUS_ISDN_ASYNC_V120RADIUS_ISDN_ASYNC_V110RADIUS_VIRTUALRADIUS_PIAFSRADIUS_HDLC_CLEAR_CHANNELRADIUS_X_25RADIUS_X_75RADIUS_G_3_FAXRADIUS_SDSLRADIUS_ADSL_CAPRADIUS_ADSL_DMTRADIUS_IDSLRADIUS_ETHERNETRADIUS_XDSLRADIUS_CABLERADIUS_WIRELESS_OTHERRADIUS_WIRELESS_IEEE_802_11RADIUS_PORT_LIMIT
(integer)
Port Limit
RADIUS_LOGIN_LAT_PORT
(integer)
Login LAT Port
RADIUS_CONNECT_INFO
(integer)
Connect info
RADIUS_ACCT_STATUS_TYPE
(integer)
Accounting status type, one of:
RADIUS_STARTRADIUS_STOPRADIUS_ACCOUNTING_ONRADIUS_ACCOUNTING_OFFRADIUS_ACCT_DELAY_TIME
(integer)
Accounting delay time
RADIUS_ACCT_INPUT_OCTETS
(integer)
Accounting input bytes
RADIUS_ACCT_OUTPUT_OCTETS
(integer)
Accounting output bytes
RADIUS_ACCT_SESSION_ID
(integer)
Accounting session ID
RADIUS_ACCT_AUTHENTIC
(integer)
Accounting authentic, one of:
RADIUS_AUTH_RADIUSRADIUS_AUTH_LOCALRADIUS_AUTH_REMOTERADIUS_ACCT_SESSION_TIME
(integer)
Accounting session time
RADIUS_ACCT_INPUT_PACKETS
(integer)
Accounting input packets
RADIUS_ACCT_OUTPUT_PACKETS
(integer)
Accounting output packets
RADIUS_ACCT_TERMINATE_CAUSE
(integer)
Accounting terminate cause, one of:
RADIUS_TERM_USER_REQUESTRADIUS_TERM_LOST_CARRIERRADIUS_TERM_LOST_SERVICERADIUS_TERM_IDLE_TIMEOUTRADIUS_TERM_SESSION_TIMEOUTRADIUS_TERM_ADMIN_RESETRADIUS_TERM_ADMIN_REBOOTRADIUS_TERM_PORT_ERRORRADIUS_TERM_NAS_ERRORRADIUS_TERM_NAS_REQUESTRADIUS_TERM_NAS_REBOOTRADIUS_TERM_PORT_UNNEEDEDRADIUS_TERM_PORT_PREEMPTEDRADIUS_TERM_PORT_SUSPENDEDRADIUS_TERM_SERVICE_UNAVAILABLERADIUS_TERM_CALLBACKRADIUS_TERM_USER_ERRORRADIUS_TERM_HOST_REQUESTRADIUS_ACCT_MULTI_SESSION_ID
(integer)
Accounting multi session ID
RADIUS_ACCT_LINK_COUNT
(integer)
Accounting link count
RADIUS_VENDOR_MICROSOFT
(integer)
Microsoft specific vendor attributes (» RFC 2548), one of:
RADIUS_MICROSOFT_MS_CHAP_RESPONSERADIUS_MICROSOFT_MS_CHAP_ERRORRADIUS_MICROSOFT_MS_CHAP_PW_1RADIUS_MICROSOFT_MS_CHAP_PW_2RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PWRADIUS_MICROSOFT_MS_CHAP_NT_ENC_PWRADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICYRADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPESRADIUS_MICROSOFT_MS_RAS_VENDORRADIUS_MICROSOFT_MS_CHAP_DOMAINRADIUS_MICROSOFT_MS_CHAP_CHALLENGERADIUS_MICROSOFT_MS_CHAP_MPPE_KEYSRADIUS_MICROSOFT_MS_BAP_USAGERADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLDRADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMITRADIUS_MICROSOFT_MS_MPPE_SEND_KEYRADIUS_MICROSOFT_MS_MPPE_RECV_KEYRADIUS_MICROSOFT_MS_RAS_VERSIONRADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORDRADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORDRADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASONRADIUS_MICROSOFT_MS_FILTERRADIUS_MICROSOFT_MS_ACCT_AUTH_TYPERADIUS_MICROSOFT_MS_ACCT_EAP_TYPERADIUS_MICROSOFT_MS_CHAP2_RESPONSERADIUS_MICROSOFT_MS_CHAP2_SUCCESSRADIUS_MICROSOFT_MS_CHAP2_PWRADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVERRADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVERRADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVERRADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVERRADIUS_MICROSOFT_MS_ARAP_CHALLENGEHowto start?
The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.
(PECL radius >= 1.1.0)
radius_acct_open — Creates a Radius handle for accounting
Returns a handle on success, FALSE on error. This function only fails if
insufficient memory is available.
Example #1 radius_acct_open() example
<?php
$res = radius_acct_open ()
or die ("Could not create handle");
print("Handle successfully created");
?>
(PECL radius >= 1.1.0)
radius_add_server — Adds a server
$radius_handle
, string $hostname
, int $port
, string $secret
, int $timeout
, int $max_tries
)
radius_add_server() may be called multiple times, and it
may be used together with radius_config(). At most 10
servers may be specified. When multiple servers are given, they are tried
in round-robin fashion until a valid response is received, or until each
server's max_tries limit has been reached.
radius_handle
hostname
The hostname parameter specifies the server host,
either as a fully qualified domain name or as a dotted-quad IP address
in text form.
port
The port specifies the UDP port to contact on
the server. If port is given as 0, the library looks up the
radius/udp or
radacct/udp service in the
network services database, and uses the port found there. If no entry
is found, the library uses the standard Radius ports, 1812 for
authentication and 1813 for accounting.
secret
The shared secret for the server host is passed to the
secret parameter. The Radius protocol ignores
all but the leading 128 bytes of the shared secret.
timeout
The timeout for receiving replies from the server is passed to the
timeout parameter, in units of seconds.
max_tries
The maximum number of repeated requests to make before giving up is
passed into the max_tries.
Returns TRUE on success or FALSE on failure.
Example #1 radius_add_server() example
<?php
if (!radius_add_server($res, 'radius.example.com', 1812, 'testing123', 3, 3)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br>";
exit;
}
?>
(PECL radius >= 1.1.0)
radius_auth_open — Creates a Radius handle for authentication
Returns a handle on success, FALSE on error. This function only fails if
insufficient memory is available.
Example #1 radius_auth_open() example
<?php
$radh = radius_auth_open()
or die ("Could not create handle");
echo "Handle successfully created";
?>
(PECL radius >= 1.1.0)
radius_close — Frees all ressources
$radius_handle
)It is not needed to call this function because php frees all resources at the end of each request.
Returns TRUE on success or FALSE on failure.
(PECL radius >= 1.1.0)
radius_config — Causes the library to read the given configuration file
$radius_handle
, string $file
)Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in » radius.conf.
radius_handle
fileThe pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().
Returns TRUE on success or FALSE on failure.
(PECL radius >= 1.1.0)
radius_create_request — Create accounting or authentication request
$radius_handle
, int $type
)A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().
Note: Attention: You must call this function, before you can put any attribute!
radius_handle
type
Type is RADIUS_ACCESS_REQUEST or
RADIUS_ACCOUNTING_REQUEST.
Returns TRUE on success or FALSE on failure.
Example #1 radius_create_request() example
<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>
(PECL radius >= 1.1.0)
radius_cvt_addr — Converts raw data to IP-Address
$data
)
Example #1 radius_cvt_addr() example
<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}
$attr = $resa['attr'];
$data = $resa['data'];
switch ($attr) {
case RADIUS_FRAMED_IP_ADDRESS:
$ip = radius_cvt_addr($data);
echo "IP: $ip<br>\n";
break;
case RADIUS_FRAMED_IP_NETMASK:
$mask = radius_cvt_addr($data);
echo "MASK: $mask<br>\n";
break;
}
}
?>
(PECL radius >= 1.1.0)
radius_cvt_int — Converts raw data to integer
$data
)
Example #1 radius_cvt_int() example
<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}
$attr = $resa['attr'];
$data = $resa['data'];
switch ($attr) {
case RADIUS_FRAMED_MTU:
$mtu = radius_cvt_int($data);
echo "MTU: $mtu<br>\n";
break;
}
}
?>
(PECL radius >= 1.1.0)
radius_cvt_string — Converts raw data to string
$data
)
Example #1 radius_cvt_string() example
<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}
$attr = $resa['attr'];
$data = $resa['data'];
switch ($attr) {
case RADIUS_FILTER_ID:
$id = radius_cvt_string($data);
echo "Filter ID: $id<br>\n";
break;
}
}
?>
(PECL radius >= 1.2.0)
radius_demangle_mppe_key — Derives mppe-keys from mangled data
$radius_handle
, string $mangled
)When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see » RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.
Returns the demangled string, or FALSE on error.
(PECL radius >= 1.2.0)
radius_demangle — Demangles data
$radius_handle
, string $mangled
)Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.
Returns the demangled string, or FALSE on error.
(PECL radius >= 1.1.0)
radius_get_attr — Extracts an attribute
Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.
Returns an associative array containing the attribute-type and the data, or error number <= 0.
Example #1 radius_get_attr() example
<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf("Error getting attribute: %s\n", radius_strerror($res));
exit;
}
$attr = $resa['attr'];
$data = $resa['data'];
printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
}
?>
(PECL radius >= 1.3.0)
radius_get_tagged_attr_data — Extracts the data from a tagged attribute
$data
)If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the data from the attribute.
dataThe tagged attribute to be decoded.
Returns the data from the tagged attribute or FALSE on failure.
Example #1 radius_get_tagged_attr_data() example
<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}
$attr = $resa['attr'];
$data = $resa['data'];
$tag = radius_get_tagged_attr_tag($data);
$value = radius_get_tagged_attr_data($data);
printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>
(PECL radius >= 1.3.0)
radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute
$data
)If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the tag from the attribute.
dataThe tagged attribute to be decoded.
Returns the tag from the tagged attribute or FALSE on failure.
Example #1 radius_get_tagged_attr_tag() example
<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}
$attr = $resa['attr'];
$data = $resa['data'];
$tag = radius_get_tagged_attr_tag($data);
$value = radius_get_tagged_attr_data($data);
printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>
(PECL radius >= 1.1.0)
radius_get_vendor_attr — Extracts a vendor specific attribute
$data
)
If radius_get_attr() returns
RADIUS_VENDOR_SPECIFIC,
radius_get_vendor_attr() may be called to determine the
vendor.
Returns an associative array containing the attribute-type, vendor and the
data, or FALSE on error.
Example #1 radius_get_vendor_attr() example
<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}
$attr = $resa['attr'];
$data = $resa['data'];
printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
if ($attr == RADIUS_VENDOR_SPECIFIC) {
$resv = radius_get_vendor_attr($data);
if (is_array($resv)) {
$vendor = $resv['vendor'];
$attrv = $resv['attr'];
$datav = $resv['data'];
printf("Got Vendor Attr:%d %d Bytes %s\n", $attrv, strlen($datav), bin2hex($datav));
}
}
}
?>
(PECL radius >= 1.1.0)
radius_put_addr — Attaches an IP address attribute
$radius_handle
, int $type
, string $addr
[, int $options = 0
[, int $tag
]] )Attaches an IP address attribute to the current RADIUS request.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
typeThe attribute type.
addrAn IPv4 address in string form, such as 10.0.0.1.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
(PECL radius >= 1.1.0)
radius_put_attr — Attaches a binary attribute
$radius_handle
, int $type
, string $value
[, int $options = 0
[, int $tag
]] )Attaches a binary attribute to the current RADIUS request.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
typeThe attribute type.
valueThe attribute value, which will be treated as a raw binary string.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
Example #1 radius_put_attr() example
<?php
mt_srand(time());
$chall = mt_rand();
$chapval = md5(pack('Ca*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
(PECL radius >= 1.1.0)
radius_put_int — Attaches an integer attribute
$radius_handle
, int $type
, int $value
[, int $options = 0
[, int $tag
]] )Attaches an integer attribute to the current RADIUS request.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
typeThe attribute type.
valueThe attribute value.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
Example #1 radius_put_int() example
<?php
if (!radius_put_int($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>
(PECL radius >= 1.1.0)
radius_put_string — Attaches a string attribute
$radius_handle
, int $type
, string $value
[, int $options = 0
[, int $tag
]] )Attaches a string attribute to the current RADIUS request. In general, radius_put_attr() is a more useful function for attaching string attributes, as it is binary safe.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
typeThe attribute type.
valueThe attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
Example #1 radius_put_string() example
<?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>
(PECL radius >= 1.1.0)
radius_put_vendor_addr — Attaches a vendor specific IP address attribute
$radius_handle
, int $vendor
, int $type
, string $addr
)Attaches an IP address vendor specific attribute to the current RADIUS request.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
vendorThe vendor ID.
typeThe attribute type.
addrAn IPv4 address in string form, such as 10.0.0.1.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
(PECL radius >= 1.1.0)
radius_put_vendor_attr — Attaches a vendor specific binary attribute
$radius_handle
, int $vendor
, int $type
, string $value
[, int $options = 0
[, int $tag
]] )Attaches a vendor specific binary attribute to the current RADIUS request.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
vendorThe vendor ID.
typeThe attribute type.
valueThe attribute value, which will be treated as a raw binary string.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
Example #1 radius_put_vendor_attr() example
<?php
if (!radius_put_vendor_attr($res, RADIUS_VENDOR_MICROSOFT, RAD_MICROSOFT_MS_CHAP_CHALLENGE, $challenge)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>
(PECL radius >= 1.1.0)
radius_put_vendor_int — Attaches a vendor specific integer attribute
$radius_handle
, int $vendor
, int $type
, int $value
[, int $options = 0
[, int $tag
]] )Attaches a vendor specific integer attribute to the current RADIUS request.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
vendorThe vendor ID.
typeThe attribute type.
valueThe attribute value.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
(PECL radius >= 1.1.0)
radius_put_vendor_string — Attaches a vendor specific string attribute
$radius_handle
, int $vendor
, int $type
, string $value
[, int $options = 0
[, int $tag
]] )Attaches a vendor specific string attribute to the current RADIUS request. In general, radius_put_vendor_attr() is a more useful function for attaching string attributes, as it is binary safe.
Note:
A request must be created via radius_create_request() before this function can be called.
radius_handleThe RADIUS resource.
vendorThe vendor ID.
typeThe attribute type.
valueThe attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.
optionsA bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.
tagThe attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.
Returns TRUE on success or FALSE on failure.
| Version | Description |
|---|---|
| PECL radius 1.3.0 |
The options and tag
parameters were added.
|
(PECL radius >= 1.1.0)
radius_request_authenticator — Returns the request authenticator
$radius_handle
)The request authenticator is needed for demangling mangled data like passwords and encryption-keys.
Returns the request authenticator as string, or FALSE on error.
(PECL radius >= 1.3.0)
radius_salt_encrypt_attr — Salt-encrypts a value
$radius_handle
, string $data
)Applies the RADIUS salt-encryption algorithm to the given value.
In general, this is achieved automatically by providing the
RADIUS_OPTION_SALT option to an attribute setter
function, but this function can be used if low-level request construction
is required.
dataThe data to be salt-encrypted.
Returns the salt-encrypted data or FALSE on failure.
(PECL radius >= 1.1.0)
radius_send_request — Sends the request and waites for a reply
$radius_handle
)After the Radius request has been constructed, it is sent by radius_send_request().
The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.
If a valid response is received, radius_send_request()
returns the Radius code which specifies the type of the response. This will
typically be RADIUS_ACCESS_ACCEPT,
RADIUS_ACCESS_REJECT, or
RADIUS_ACCESS_CHALLENGE. If no valid response is
received, radius_send_request() returns FALSE.
(PECL radius >= 1.1.0)
radius_server_secret — Returns the shared secret
$radius_handle
)The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.
Returns the server's shared secret as string, or FALSE on error.
(PECL radius >= 1.1.0)
radius_strerror — Returns an error message
$radius_handle
)If Radius-functions fail then they record an error message. This error message can be retrieved with this function.
Returns error messages as string from failed radius functions.
ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.
The features available, such as colors, depend on the terminal that you are using. Use functions such as ncurses_has_colors(), ncurses_can_change_color(), and ncurses_has_ic() to check for individual capabilities.
Note:
This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.
ncurses is available for the following platforms:
You need the ncurses libraries and headerfiles. Download the latest version from the » ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.
Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/ncurses.
Wide character CRT screen handling (ncursesw) support was added in version 1.0.1 of this PECL extension.
This extension has no configuration directives defined in php.ini.
This extension defines window, panel and pad resources.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
On error ncurses functions return -1. Some functions return 0 on success. See the relevant pages in the documentation for actual return values.
| constant | meaning |
|---|---|
NCURSES_COLOR_BLACK |
no color (black) |
NCURSES_COLOR_WHITE |
white |
NCURSES_COLOR_RED |
red - supported when terminal is in color mode |
NCURSES_COLOR_GREEN |
green - supported when terminal is in color mode |
NCURSES_COLOR_YELLOW |
yellow - supported when terminal is in color mode |
NCURSES_COLOR_BLUE |
blue - supported when terminal is in color mode |
NCURSES_COLOR_CYAN |
cyan - supported when terminal is in color mode |
NCURSES_COLOR_MAGENTA |
magenta - supported when terminal is in color mode |
| constant | meaning |
|---|---|
NCURSES_KEY_F0 - NCURSES_KEY_F64 |
function keys F1 - F64 |
NCURSES_KEY_DOWN |
down arrow |
NCURSES_KEY_UP |
up arrow |
NCURSES_KEY_LEFT |
left arrow |
NCURSES_KEY_RIGHT |
right arrow |
NCURSES_KEY_HOME |
home key (upward+left arrow) |
NCURSES_KEY_BACKSPACE |
backspace |
NCURSES_KEY_DL |
delete line |
NCURSES_KEY_IL |
insert line |
NCURSES_KEY_DC |
delete character |
NCURSES_KEY_IC |
insert char or enter insert mode |
NCURSES_KEY_EIC |
exit insert char mode |
NCURSES_KEY_CLEAR |
clear screen |
NCURSES_KEY_EOS |
clear to end of screen |
NCURSES_KEY_EOL |
clear to end of line |
NCURSES_KEY_SF |
scroll one line forward |
NCURSES_KEY_SR |
scroll one line backward |
NCURSES_KEY_NPAGE |
next page |
NCURSES_KEY_PPAGE |
previous page |
NCURSES_KEY_STAB |
set tab |
NCURSES_KEY_CTAB |
clear tab |
NCURSES_KEY_CATAB |
clear all tabs |
NCURSES_KEY_SRESET |
soft (partial) reset |
NCURSES_KEY_RESET |
reset or hard reset |
NCURSES_KEY_PRINT |
|
NCURSES_KEY_LL |
lower left |
NCURSES_KEY_A1 |
upper left of keypad |
NCURSES_KEY_A3 |
upper right of keypad |
NCURSES_KEY_B2 |
center of keypad |
NCURSES_KEY_C1 |
lower left of keypad |
NCURSES_KEY_C3 |
lower right of keypad |
NCURSES_KEY_BTAB |
back tab |
NCURSES_KEY_BEG |
beginning |
NCURSES_KEY_CANCEL |
cancel |
NCURSES_KEY_CLOSE |
close |
NCURSES_KEY_COMMAND |
cmd (command) |
NCURSES_KEY_COPY |
copy |
NCURSES_KEY_CREATE |
create |
NCURSES_KEY_END |
end |
NCURSES_KEY_EXIT |
exit |
NCURSES_KEY_FIND |
find |
NCURSES_KEY_HELP |
help |
NCURSES_KEY_MARK |
mark |
NCURSES_KEY_MESSAGE |
message |
NCURSES_KEY_MOVE |
move |
NCURSES_KEY_NEXT |
next |
NCURSES_KEY_OPEN |
open |
NCURSES_KEY_OPTIONS |
options |
NCURSES_KEY_PREVIOUS |
previous |
NCURSES_KEY_REDO |
redo |
NCURSES_KEY_REFERENCE |
ref (reference) |
NCURSES_KEY_REFRESH |
refresh |
NCURSES_KEY_REPLACE |
replace |
NCURSES_KEY_RESTART |
restart |
NCURSES_KEY_RESUME |
resume |
NCURSES_KEY_SAVE |
save |
NCURSES_KEY_SBEG |
shiftet beg (beginning) |
NCURSES_KEY_SCANCEL |
shifted cancel |
NCURSES_KEY_SCOMMAND |
shifted command |
NCURSES_KEY_SCOPY |
shifted copy |
NCURSES_KEY_SCREATE |
shifted create |
NCURSES_KEY_SDC |
shifted delete char |
NCURSES_KEY_SDL |
shifted delete line |
NCURSES_KEY_SELECT |
select |
NCURSES_KEY_SEND |
shifted end |
NCURSES_KEY_SEOL |
shifted end of line |
NCURSES_KEY_SEXIT |
shifted exit |
NCURSES_KEY_SFIND |
shifted find |
NCURSES_KEY_SHELP |
shifted help |
NCURSES_KEY_SHOME |
shifted home |
NCURSES_KEY_SIC |
shifted input |
NCURSES_KEY_SLEFT |
shifted left arrow |
NCURSES_KEY_SMESSAGE |
shifted message |
NCURSES_KEY_SMOVE |
shifted move |
NCURSES_KEY_SNEXT |
shifted next |
NCURSES_KEY_SOPTIONS |
shifted options |
NCURSES_KEY_SPREVIOUS |
shifted previous |
NCURSES_KEY_SPRINT |
shifted print |
NCURSES_KEY_SREDO |
shifted redo |
NCURSES_KEY_SREPLACE |
shifted replace |
NCURSES_KEY_SRIGHT |
shifted right arrow |
NCURSES_KEY_SRSUME |
shifted resume |
NCURSES_KEY_SSAVE |
shifted save |
NCURSES_KEY_SSUSPEND |
shifted suspend |
NCURSES_KEY_UNDO |
undo |
NCURSES_KEY_MOUSE |
mouse event has occurred |
NCURSES_KEY_MAX |
maximum key value |
| Constant | meaning |
|---|---|
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED |
button (1-4) released |
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED |
button (1-4) pressed |
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED |
button (1-4) clicked |
NCURSES_BUTTON1_DOUBLE_CLICKED -
NCURSES_BUTTON4_DOUBLE_CLICKED |
button (1-4) double clicked |
NCURSES_BUTTON1_TRIPLE_CLICKED -
NCURSES_BUTTON4_TRIPLE_CLICKED |
button (1-4) triple clicked |
NCURSES_BUTTON_CTRL |
ctrl pressed during click |
NCURSES_BUTTON_SHIFT |
shift pressed during click |
NCURSES_BUTTON_ALT |
alt pressed during click |
NCURSES_ALL_MOUSE_EVENTS |
report all mouse events |
NCURSES_REPORT_MOUSE_POSITION |
report mouse position |
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addch — Add character at current position and advance cursor
$ch
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
ch
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addchnstr — Add attributed string with specified length at current position
$s
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
s
n
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addchstr — Add attributed string at current position
$s
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
s
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addnstr — Add string with specified length at current position
$s
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
s
n
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_addstr — Output text at current position
$text
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
text
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_assume_default_colors — Define default colors for color 0
$fg
, int $bg
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
fg
bg
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_attroff — Turn off the given attributes
$attributes
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
attributes
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_attron — Turn on the given attributes
$attributes
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
attributes
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_attrset — Set given attributes
$attributes
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
attributes
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_baudrate — Returns baudrate of terminal
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_beep — Let the terminal beep
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_bkgd — Set background property for terminal screen
$attrchar
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
attrchar
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_bkgdset — Control screen background
$attrchar
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
attrchar
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_border — Draw a border around the screen using attributed characters
$left
, int $right
, int $top
, int $bottom
, int $tl_corner
, int $tr_corner
, int $bl_corner
, int $br_corner
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Draws the specified lines and corners around the main window.
Use ncurses_wborder() for borders around subwindows!
Every parameter expects 0 to draw a line or 1 to skip it.
left
right
top
bottom
tl_cornerTop left corner
tr_cornerTop right corner
bl_cornerBottom left corner
br_cornerBottom right corner
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_bottom_panel — Moves a visible panel to the bottom of the stack
$panel
)This function is currently not documented; only its argument list is available.
panel
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_can_change_color — Checks if terminal color definitions can be changed
Checks whether the terminal has color capabilities and whether the programmer can change color definitions using ncurses_init_color(). ncurses must be initialized using ncurses_init() before calling this function.
This function has no parameters.
Return TRUE if the programmer can change color definitions,
FALSE otherwise.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_cbreak — Switch of input buffering
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.
Returns TRUE or NCURSES_ERR if any error occurred.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_clear — Clear screen
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Clears the screen completely without setting blanks.
Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_clrtobot — Clear screen from current position to bottom
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition.
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_clrtoeol — Clear screen from current position to end of line
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition.
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_color_content — Retrieves RGB components of a color
$color
, int &$r
, int &$g
, int &$b
)Retrieves the red, green, and blue components for the given color definition. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.
colorThe number of the color to retrieve information for. May be one of the pre-defined color constants.
rA reference to which to return the red component of the color. The value returned to the reference will be between 0 and 1000.
gA reference to which to return the green component of the color. The value returned to the reference will be between 0 and 1000.
bA reference to which to return the blue component of the color. The value returned to the reference will be between 0 and 1000.
Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_color_set — Set active foreground and background colors
$pair
)Sets the active foreground and background colors. Any characters written after this function is invoked will have these colors. This function requires terminal colors to be supported and initialized using ncurses_start_color() beforehand.
ncurses uses color pairs to specify both foreground and background colors. Use ncurses_init_pair() to define a color pair.
pairThe color pair from which to get the foreground and background colors to set as the active colors.
Returns -1 on success, and 0 on failure.
Example #1 Writing a string with a specified color to the screen
<?php
ncurses_init();
// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
ncurses_start_color();
ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
ncurses_color_set(1);
}
// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");
// Flush output to screen
ncurses_refresh();
ncurses_end();
?>
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_curs_set — Set cursor state
$visibility
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
visibility
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_def_prog_mode — Saves terminals (program) mode
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode().
Returns FALSE on success, otherwise TRUE.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_def_shell_mode — Saves terminals (shell) mode
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode().
Returns FALSE on success, TRUE otherwise.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_define_key — Define a keycode
$definition
, int $keycode
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
definition
keycode
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)
$panel
)This function is currently not documented; only its argument list is available.
panel
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_delay_output — Delay output on terminal using padding characters
$milliseconds
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
milliseconds
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_delch — Delete character at current position, move rest of line left
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change.
Returns FALSE on success, TRUE otherwise.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_deleteln — Delete line at current position, move rest of screen up
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change.
Returns FALSE on success, otherwise TRUE.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_delwin — Delete a ncurses window
$window
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_doupdate — Write all prepared refreshes to terminal
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls.
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_echo — Activate keyboard input echo
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Enables echo mode. All characters typed by user are echoed by ncurses_getch().
Returns FALSE on success, TRUE if any error occurred.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_echochar — Single character output including refresh
$character
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
character
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_end — Stop using ncurses, clean up the screen
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_erase — Erase terminal screen
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Fills the terminal screen with blanks.
Created blanks have the current background rendition, set by ncurses_bkgd().
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_erasechar — Returns current erase character
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Returns the current erase character.
The current erase char, as a string.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_filter — Set LINES for iniscr() and newterm() to 1
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_flash — Flash terminal screen (visual bell)
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Flashes the screen, and if its not possible, sends an audible alert (bell).
Returns FALSE on success, otherwise TRUE.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_flushinp — Flush keyboard input buffer
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Throws away any typeahead that has been typed and has not yet been read by your program.
Returns FALSE on success, otherwise TRUE.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getch — Read a character from keyboard
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getmaxyx — Returns the size of a window
$window
, int &$y
, int &$x
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Gets the horizontal and vertical size of the given
window into the given variables.
Variables must be passed as reference, so they are updated when the user changes the terminal size.
windowThe measured window
yThis will be set to the window height
xThis will be set to the window width
No value is returned.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getmouse — Reads mouse event
&$mevent
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
ncurses_getmouse() reads mouse event out of queue.
meventEvent options will be delivered in this parameter which has to be an array, passed by reference (see example below).
On success an associative array with following keys will be delivered:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
Returns FALSE if a mouse event is actually visible in the given window,
otherwise returns TRUE.
Example #1 ncurses_getmouse() example
<?php
switch (ncurses_getch()){
case NCURSES_KEY_MOUSE:
if (!ncurses_getmouse($mevent)){
if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
$mouse_x = $mevent["x"]; // Save mouse position
$mouse_y = $mevent["y"];
}
}
break;
default:
/* .... */
}
?>
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_getyx — Returns the current cursor position for a window
$window
, int &$y
, int &$x
)This function is currently not documented; only its argument list is available.
window
y
x
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_halfdelay — Put terminal into halfdelay mode
$tenth
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
tenth
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_colors — Checks if terminal has color capabilities
Checks whether the terminal has color capabilities. This function can be used to write terminal-independent programs. ncurses must be initialized using ncurses_init() before calling this function.
This function has no parameters.
Return TRUE if the terminal has color capabilities, FALSE otherwise.
Example #1 Writing a string with a specified color to the screen
<?php
ncurses_init();
// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
ncurses_start_color();
ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
ncurses_color_set(1);
}
// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");
// Flush output to screen
ncurses_refresh();
ncurses_end();
?>
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_ic — Check for insert- and delete-capabilities
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Checks whether the terminal has insert and delete capabilities.
Returns TRUE if the terminal has insert/delete-capabilities, FALSE
otherwise.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_il — Check for line insert- and delete-capabilities
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Checks whether the terminal has insert- and delete-line-capabilities.
Returns TRUE if the terminal has insert/delete-line capabilities,
FALSE otherwise.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_has_key — Check for presence of a function key on terminal keyboard
$keycode
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
keycode
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_hide_panel — Remove panel from the stack, making it invisible
$panel
)This function is currently not documented; only its argument list is available.
panel
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
$charattr
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
charattr
n
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_inch — Get character and attribute at current position
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Returns the character from the current position.
Returns the character, as a string.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_init_color — Define a terminal color
$color
, int $r
, int $g
, int $b
)Defines or redefines the given color. When this function is called, all occurrences of the given color on the screen, if any, immediately change to the new definition.
Color capabilities must be supported by the terminal and initialized using ncurses_start_color() prior to calling this function. In addition, the terminal must have color changing capabilities; use ncurses_can_change_color() to check for this.
colorThe identification number of the color to redefine. It may be one of the default color constants.
rA color value, between 0 and 1000, for the red component.
gA color value, between 0 and 1000, for the green component.
bA color value, between 0 and 1000, for the blue component.
Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized or the terminal does not have color changing capabilities.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_init_pair — Define a color pair
$pair
, int $fg
, int $bg
)Defines or redefines the given color pair to have the given foreground and background colors. If the color pair was previously initialized, the screen is refreshed and all occurrences of it are changed to reflect the new definition.
Color capabilities must be initialized using ncurses_start_color() before calling this function. The first color pair (color pair 0) is assumed to be white on black by default, but can be changed using ncurses_assume_default_colors().
pairThe number of the color pair to define.
fgThe foreground color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.
bgThe background color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.
Returns -1 if the function was successful, and 0 if ncurses or color support were not initialized.
Note that color changing capabilities are not required for defining color pairs of pre-existing colors, but only for changing definitions (red, green, and blue components) of colors themselves per ncurses_init_color().
Example #1 Writing a string with a specified color to the screen
<?php
ncurses_init();
// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
ncurses_start_color();
ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
ncurses_color_set(1);
}
// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");
// Flush output to screen
ncurses_refresh();
ncurses_end();
?>
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_init — Initialize ncurses
Initializes the ncurses interface. This function must be used before any other ncurses function call.
Note that ncurses_end() must be called before exiting from the program, or the terminal will not be restored to its proper non-visual mode.
This function has no parameters.
No value is returned.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insch — Insert character moving rest of line including character at current position
$character
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
character
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
$count
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
count
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insertln — Insert a line, move rest of screen down
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Inserts a new line above the current line. The bottom line will be lost.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_insstr — Insert string at current position, moving rest of line right
$text
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
text
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_instr — Reads string from terminal screen
&$buffer
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Reads a string from the terminal screen and returns the number of characters read from the current character position until end of line.
bufferThe characters. Attributes will be stripped.
Returns the number of characters.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Checks if ncurses is in endwin mode.
Returns TRUE, if ncurses_end() has been called
without any subsequent calls to ncurses_wrefresh(),
FALSE otherwise.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_keyok — Enable or disable a keycode
$keycode
, bool $enable
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
keycode
enable
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_keypad — Turns keypad on or off
$window
, bool $bf
)This function is currently not documented; only its argument list is available.
window
bf
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_killchar — Returns current line kill character
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Returns the current line kill character.
Returns the kill character, as a string.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_longname — Returns terminals description
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Returns a verbose description of the terminal.
Returns the description, as a string truncated to 128 characters.
On errors, returns NULL.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_meta — Enables/Disable 8-bit meta key information
$window
, bool $8bit
)This function is currently not documented; only its argument list is available.
window
8bit
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mouse_trafo — Transforms coordinates
&$y
, int &$x
, bool $toscreen
)This function is currently not documented; only its argument list is available.
y
x
toscreen
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mouseinterval — Set timeout for mouse button clicks
$milliseconds
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
milliseconds
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mousemask — Sets mouse options
$newmask
, int &$oldmask
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Sets mouse events to be reported. By default no mouse events will be reported.
Mouse events are represented by NCURSES_KEY_MOUSE in the
ncurses_wgetch() input stream. To read the event data
and pop the event of queue, call ncurses_getmouse().
newmaskMouse mask options can be set with the following predefined constants:
NCURSES_BUTTON1_PRESSED
NCURSES_BUTTON1_RELEASED
NCURSES_BUTTON1_CLICKED
NCURSES_BUTTON1_DOUBLE_CLICKED
NCURSES_BUTTON1_TRIPLE_CLICKED
NCURSES_BUTTON2_PRESSED
NCURSES_BUTTON2_RELEASED
NCURSES_BUTTON2_CLICKED
NCURSES_BUTTON2_DOUBLE_CLICKED
NCURSES_BUTTON2_TRIPLE_CLICKED
NCURSES_BUTTON3_PRESSED
NCURSES_BUTTON3_RELEASED
NCURSES_BUTTON3_CLICKED
NCURSES_BUTTON3_DOUBLE_CLICKED
NCURSES_BUTTON3_TRIPLE_CLICKED
NCURSES_BUTTON4_PRESSED
NCURSES_BUTTON4_RELEASED
NCURSES_BUTTON4_CLICKED
NCURSES_BUTTON4_DOUBLE_CLICKED
NCURSES_BUTTON4_TRIPLE_CLICKED
NCURSES_BUTTON_SHIFT>
NCURSES_BUTTON_CTRL
NCURSES_BUTTON_ALT
NCURSES_ALL_MOUSE_EVENTS
NCURSES_REPORT_MOUSE_POSITION
As a side effect, setting a zero mousemask in
newmask turns off the mouse
pointer. Setting a non zero value turns mouse pointer on.
oldmaskThis will be set to the previous value of the mouse event mask.
Returns a mask to indicated which of the in parameter
newmask specified mouse events can be reported. On
complete failure, it returns 0.
Example #1 ncurses_mousemask() example
<?php
$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, $oldmask);
if ($mask & $newmask){
printf("All specified mouse options will be supported\n");
}
?>
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]
$panel
, int $startx
, int $starty
)This function is currently not documented; only its argument list is available.
panel
startx
starty
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_move — Move output position
$y
, int $x
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddch — Move current position and add character
$y
, int $x
, int $c
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
c
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddchnstr — Move position and add attributed string with specified length
$y
, int $x
, string $s
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
s
n
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddchstr — Move position and add attributed string
$y
, int $x
, string $s
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
s
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddnstr — Move position and add string with specified length
$y
, int $x
, string $s
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
s
n
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvaddstr — Move position and add string
$y
, int $x
, string $s
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
s
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvcur — Move cursor immediately
$old_y
, int $old_x
, int $new_y
, int $new_x
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
old_y
old_x
new_y
new_x
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvdelch — Move position and delete character, shift rest of line left
$y
, int $x
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvgetch — Move position and get character at new position
$y
, int $x
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
$y
, int $x
, int $attrchar
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
attrchar
n
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvinch — Move position and get attributed character at new position
$y
, int $x
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
$y
, int $x
, int $attrchar
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
y
x
attrchar
n
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_mvwaddstr — Add string at new position in window
$window
, int $y
, int $x
, string $text
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
window
y
x
text
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_napms — Sleep
$milliseconds
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
milliseconds
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_new_panel — Create a new panel and associate it with window
$window
)This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_newpad — Creates a new pad (window)
$rows
, int $cols
)This function is currently not documented; only its argument list is available.
rows
cols
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_newwin — Create a new window
$rows
, int $cols
, int $y
, int $x
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Creates a new window to draw elements in.
When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary.
rowsNumber of rows
colsNumber of columns
yy-coordinate of the origin
xx-coordinate of the origin
Returns a resource ID for the new window.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_nl — Translate newline and carriage return / line feed
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_nocbreak — Switch terminal to cooked mode
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly.
Returns TRUE if any error occurred, otherwise FALSE.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_noecho — Switch off keyboard input echo
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Prevents echoing of user typed characters.
Returns TRUE if any error occurred, FALSE otherwise.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_nonl — Do not translate newline and carriage return / line feed
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_noqiflush — Do not flush on signal characters
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_noraw — Switch terminal out of raw mode
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.
Returns TRUE if any error occurred, otherwise FALSE.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_pair_content — Retrieves foreground and background colors of a color pair
$pair
, int &$f
, int &$b
)Retrieves the foreground and background colors that constitute the given color pair. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.
pairThe number of the color pair to retrieve information for.
fA reference to which to return the foreground color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.
bA reference to which to return the background color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.
Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_panel_above — Returns the panel above panel
$panel
)This function is currently not documented; only its argument list is available.
panel
If panel is null, returns the bottom panel in the stack.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_panel_below — Returns the panel below panel
$panel
)This function is currently not documented; only its argument list is available.
panel
If panel is null, returns the top panel in the stack.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_panel_window — Returns the window associated with panel
$panel
)This function is currently not documented; only its argument list is available.
panel
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen
$pad
, int $pminrow
, int $pmincol
, int $sminrow
, int $smincol
, int $smaxrow
, int $smaxcol
)This function is currently not documented; only its argument list is available.
pad
pminrow
pmincol
sminrow
smincol
smaxrow
smaxcol
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_prefresh — Copies a region from a pad into the virtual screen
$pad
, int $pminrow
, int $pmincol
, int $sminrow
, int $smincol
, int $smaxrow
, int $smaxcol
)This function is currently not documented; only its argument list is available.
pad
pminrow
pmincol
sminrow
smincol
smaxrow
smaxcol
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_putp — Apply padding information to the string and output it
$text
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
text
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_qiflush — Flush on signal characters
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_raw — Switch terminal into raw mode
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.
Returns TRUE if any error occurred, otherwise FALSE.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_refresh — Refresh screen
$ch
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
ch
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_replace_panel — Replaces the window associated with panel
$panel
, resource $window
)This function is currently not documented; only its argument list is available.
panel
window
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_resetty — Restores saved terminal state
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Restores the terminal state, which was previously saved by calling ncurses_savetty().
Always returns FALSE.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_savetty — Saves terminal state
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Saves the current terminal state. The saved terminal state can be restored with ncurses_resetty().
Always returns FALSE.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_dump — Dump screen content to file
$filename
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
filename
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_init — Initialize screen from file dump
$filename
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
filename
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_restore — Restore screen from file dump
$filename
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
filename
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scr_set — Inherit screen from file dump
$filename
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
filename
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_scrl — Scroll window content up or down without changing current position
$count
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
count
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_show_panel — Places an invisible panel on top of the stack, making it visible
$panel
)This function is currently not documented; only its argument list is available.
panel
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attr — Returns current soft label key attribute
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Returns the current soft label key attribute.
The attribute, as an integer.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attroff — Turn off the given attributes for soft function-key labels
$intarg
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
intarg
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attron — Turn on the given attributes for soft function-key labels
$intarg
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
intarg
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_attrset — Set given attributes for soft function-key labels
$intarg
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
intarg
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_clear — Clears soft labels from screen
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
The function ncurses_slk_clear() clears soft label keys from screen.
Returns TRUE on errors, FALSE otherwise.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_color — Sets color for soft label keys
$intarg
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
intarg
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_init — Initializes soft label key functions
$format
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Initializes soft label key functions
This function must be called before ncurses_init() or ncurses_newwin() is called.
formatIf ncurses_init() eventually uses a line from stdscr to emulate the soft labels, then this parameter determines how the labels are arranged of the screen.
0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_refresh — Copies soft label keys to screen
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Copies soft label keys from virtual screen to physical screen.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_restore — Restores soft label keys
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Restores the soft label keys after ncurses_slk_clear() has been performed.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_set — Sets function key labels
$labelnr
, string $label
, int $format
)This function is currently not documented; only its argument list is available.
labelnr
label
format
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_standend — Stop using 'standout' attribute
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_standout — Start using 'standout' attribute
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_start_color — Initializes color functionality
Initializes color functionality in ncurses. This function must be called before any color manipulation functions are called and after ncurses_init() is called. It is good practice to call this function right after ncurses_init().
This function has no parameters.
Returns 0 on success, or -1 if the color table could not be allocated or ncurses was not initialized.
Example #1 Writing a string with a specified color to the screen
<?php
ncurses_init();
// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
ncurses_start_color();
ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
ncurses_color_set(1);
}
// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");
// Flush output to screen
ncurses_refresh();
ncurses_end();
?>
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_termname — Returns terminals (short)-name
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Returns terminals shortname.
Returns the shortname of the terminal, truncated to 14 characters.
On errors, returns NULL.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_timeout — Set timeout for special key sequences
$millisec
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
millisec
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_top_panel — Moves a visible panel to the top of the stack
$panel
)This function is currently not documented; only its argument list is available.
panel
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_typeahead — Specify different filedescriptor for typeahead checking
$fd
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
fd
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_ungetch — Put a character back into the input stream
$keycode
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
keycode
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_ungetmouse — Pushes mouse event to queue
$mevent
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Pushes a KEY_MOUSE event onto the unput queue and associates with this
event the given state sata and screen-relative character cell coordinates,
specified in mevent.
meventAn associative array specifying the event options:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
Returns FALSE on success, TRUE otherwise.
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_use_default_colors — Assign terminal default colors to color id -1
This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_use_env — Control use of environment information about terminal size
$flag
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
flag
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_use_extended_names — Control use of extended names in terminfo descriptions
$flag
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
flag
(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_vidattr — Display the string on the terminal in the video attribute mode
$intarg
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
intarg
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
$charattr
, int $n
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
charattr
n
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_waddch — Adds character at current position in a window and advance cursor
$window
, int $ch
)This function is currently not documented; only its argument list is available.
window
ch
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_waddstr — Outputs text at current postion in window
$window
, string $str
[, int $n
] )This function is currently not documented; only its argument list is available.
window
str
n
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wattroff — Turns off attributes for a window
$window
, int $attrs
)This function is currently not documented; only its argument list is available.
window
attrs
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wattron — Turns on attributes for a window
$window
, int $attrs
)This function is currently not documented; only its argument list is available.
window
attrs
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wattrset — Set the attributes for a window
$window
, int $attrs
)This function is currently not documented; only its argument list is available.
window
attrs
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wborder — Draws a border around the window using attributed characters
$window
, int $left
, int $right
, int $top
, int $bottom
, int $tl_corner
, int $tr_corner
, int $bl_corner
, int $br_corner
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
Draws the specified lines and corners around the passed
window.
Use ncurses_border() for borders around the main window.
Each parameter expects 0 to draw a line and 1 to skip it.
windowThe window on which we operate
left
right
top
bottom
tl_cornerTop left corner
tr_cornerTop right corner
bl_cornerBottom left corner
br_cornerBottom right corner
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wclear — Clears window
$window
)This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wcolor_set — Sets windows color pairings
$window
, int $color_pair
)This function is currently not documented; only its argument list is available.
window
color_pair
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_werase — Erase window contents
$window
)This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wgetch — Reads a character from keyboard (window)
$window
)This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long
$window
, int $charattr
, int $n
)This function is currently not documented; only its argument list is available.
window
charattr
n
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wmouse_trafo — Transforms window/stdscr coordinates
$window
, int &$y
, int &$x
, bool $toscreen
)This function is currently not documented; only its argument list is available.
window
x
y
toscreen
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wmove — Moves windows output position
$window
, int $y
, int $x
)This function is currently not documented; only its argument list is available.
window
y
x
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wnoutrefresh — Copies window to virtual screen
$window
)This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wrefresh — Refresh window on terminal screen
$window
)This function is EXPERIMENTAL. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wstandend — End standout mode for a window
$window
)This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wstandout — Enter standout mode for a window
$window
)This function is currently not documented; only its argument list is available.
window
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)
ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long
$window
, int $charattr
, int $n
)This function is currently not documented; only its argument list is available.
window
charattr
n
This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension is very similar to the original Newt API of C programming language.
This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.
This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/newt.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.
Note:
This extension is not available for Windows platform.
You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the following configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang
This extension has no configuration directives defined in php.ini.
This extension uses two resource types: "newt component" and "newt grid".
Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button())
Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
| constant | meaning |
|---|---|
NEWT_EXIT_HOTKEY |
hotkey defined by newt_form_add_hot_key() was pressed |
NEWT_EXIT_COMPONENT |
some component has caused form to exit |
NEWT_EXIT_FDREADY |
file descriptor specified in newt_form_watch_fd() is ready to be read or written to |
NEWT_EXIT_TIMER |
time specified in newt_form_set_timer() has elapsed |
| constant | meaning |
|---|---|
NEWT_COLORSET_ROOT |
|
NEWT_COLORSET_BORDER |
|
NEWT_COLORSET_WINDOW |
|
NEWT_COLORSET_SHADOW |
|
NEWT_COLORSET_TITLE |
|
NEWT_COLORSET_BUTTON |
|
NEWT_COLORSET_ACTBUTTON |
|
NEWT_COLORSET_CHECKBOX |
|
NEWT_COLORSET_ACTCHECKBOX |
|
NEWT_COLORSET_ENTRY |
|
NEWT_COLORSET_LABEL |
|
NEWT_COLORSET_LISTBOX |
|
NEWT_COLORSET_ACTLISTBOX |
|
NEWT_COLORSET_TEXTBOX |
|
NEWT_COLORSET_ACTTEXTBOX |
|
NEWT_COLORSET_HELPLINE |
|
NEWT_COLORSET_ROOTTEXT |
|
NEWT_COLORSET_EMPTYSCALE |
|
NEWT_COLORSET_FULLSCALE |
|
NEWT_COLORSET_DISENTRY |
|
NEWT_COLORSET_COMPACTBUTTON |
|
NEWT_COLORSET_ACTSELLISTBOX |
|
NEWT_COLORSET_SELLISTBOX |
| constant | meaning |
|---|---|
NEWT_ARG_LAST |
|
NEWT_ARG_APPEND |
| constant | meaning |
|---|---|
NEWT_FLAGS_SET |
|
NEWT_FLAGS_RESET |
|
NEWT_FLAGS_TOGGLE |
| constant | meaning |
|---|---|
NEWT_FLAG_RETURNEXIT |
Exit form, when component is activated |
NEWT_FLAG_SCROLL |
Component is scrollable |
NEWT_FLAG_DISABLED |
Component is disabled |
NEWT_FLAG_BORDER |
|
NEWT_FLAG_WRAP |
Wrap text |
NEWT_FLAG_NOF12 |
Don't exit form on pressing F12 |
NEWT_FLAG_MULTIPLE |
|
NEWT_FLAG_SELECTED |
Component is selected |
NEWT_FLAG_CHECKBOX |
Component is checkbox |
NEWT_FLAG_PASSWORD |
Entry component is password entry |
NEWT_FLAG_SHOWCURSOR |
Show cursor |
| constant | meaning |
|---|---|
NEWT_FD_READ |
|
NEWT_FD_WRITE |
|
NEWT_FD_EXCEPT |
| constant | meaning |
|---|---|
NEWT_CHECKBOXTREE_UNSELECTABLE |
|
NEWT_CHECKBOXTREE_HIDE_BOX |
|
NEWT_CHECKBOXTREE_COLLAPSED |
|
NEWT_CHECKBOXTREE_EXPANDED |
|
NEWT_CHECKBOXTREE_UNSELECTED |
|
NEWT_CHECKBOXTREE_SELECTED |
| constant | meaning |
|---|---|
NEWT_ENTRY_SCROLL |
|
NEWT_ENTRY_RETURNEXIT |
|
NEWT_ENTRY_DISABLED |
| constant | meaning |
|---|---|
NEWT_LISTBOX_RETURNEXIT |
| constant | meaning |
|---|---|
NEWT_TEXTBOX_WRAP |
Wrap text in the textbox |
NEWT_TEXTBOX_SCROLL |
Scroll text in the textbox |
| constant | meaning |
|---|---|
NEWT_FORM_NOF12 |
Don't exit form on F12 press |
| constant | meaning |
|---|---|
NEWT_KEY_TAB |
|
NEWT_KEY_ENTER |
|
NEWT_KEY_SUSPEND |
|
NEWT_KEY_ESCAPE |
|
NEWT_KEY_RETURN |
|
NEWT_KEY_EXTRA_BASE |
|
NEWT_KEY_UP |
|
NEWT_KEY_DOWN |
|
NEWT_KEY_LEFT |
|
NEWT_KEY_RIGHT |
|
NEWT_KEY_BKSPC |
|
NEWT_KEY_DELETE |
|
NEWT_KEY_HOME |
|
NEWT_KEY_END |
|
NEWT_KEY_UNTAB |
|
NEWT_KEY_PGUP |
|
NEWT_KEY_PGDN |
|
NEWT_KEY_INSERT |
|
NEWT_KEY_F1 |
|
NEWT_KEY_F2 |
|
NEWT_KEY_F3 |
|
NEWT_KEY_F4 |
|
NEWT_KEY_F5 |
|
NEWT_KEY_F6 |
|
NEWT_KEY_F7 |
|
NEWT_KEY_F8 |
|
NEWT_KEY_F9 |
|
NEWT_KEY_F10 |
|
NEWT_KEY_F11 |
|
NEWT_KEY_F12 |
|
NEWT_KEY_RESIZE |
| constant | meaning |
|---|---|
NEWT_ANCHOR_LEFT |
|
NEWT_ANCHOR_RIGHT |
|
NEWT_ANCHOR_TOP |
|
NEWT_ANCHOR_BOTTOM |
| constant | meaning |
|---|---|
NEWT_GRID_FLAG_GROWX |
|
NEWT_GRID_FLAG_GROWY |
|
NEWT_GRID_EMPTY |
|
NEWT_GRID_COMPONENT |
|
NEWT_GRID_SUBGRID |
This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.
Example #1 Newt Usage Example
<?php
newt_init ();
newt_cls ();
newt_draw_root_text (0, 0, "Test Mode Setup Utility 1.12");
newt_push_help_line (null);
newt_draw_root_text (-30, 0, "(c) 1999-2002 RedHat, Inc");
newt_get_screen_size ($rows, $cols);
newt_open_window ($rows/2-17, $cols/2-10, 34, 17, "Choose a Tool");
$form = newt_form ();
$list = newt_listbox (3, 2, 10);
foreach (array (
"Authentication configuration",
"Firewall configuration",
"Mouse configuration",
"Network configuration",
"Printer configuration",
"System services") as $l_item)
{
newt_listbox_add_entry ($list, $l_item, $l_item);
}
$b1 = newt_button (5, 12, "Run Tool");
$b2 = newt_button (21, 12, "Quit");
newt_form_add_component ($form, $list);
newt_form_add_components ($form, array($b1, $b2));
newt_refresh ();
newt_run_form ($form);
newt_pop_window ();
newt_pop_help_line ();
newt_finished ();
newt_form_destroy ($form);
?>
(PECL newt >= 0.1)
newt_bell — Send a beep to the terminal
This function sends a beep to the terminal.
Note:
Depending on the terminal's settings, this beep may or may not be audible.
No value is returned.
(PECL newt >= 0.1)
newt_centered_window — Open a centered window of the specified size
$width
, int $height
[, string $title
] )Open a centered window of the specified size.
widthWindow width
heightWindow height
titleWindow title
Undefined value.
(PECL newt >= 0.1)
newt_checkbox_get_value — Retreives value of checkox resource
$checkbox
)This function returns the character in the sequence which indicates the current value of the checkbox.
checkbox
Returns character indicating the value of the checkbox.
(PECL newt >= 0.1)
newt_checkbox_set_flags — Configures checkbox resource
$checkbox
, int $flags
, int $sense
)This function allows to set various flags on checkbox resource.
checkbox
flags
sense
No value is returned.
(PECL newt >= 0.1)
newt_checkbox_set_value — Sets the value of the checkbox
$checkbox
, string $value
)This function allows to set the current value of the checkbox resource.
checkbox
value
No value is returned.
(PECL newt >= 0.1)
newt_checkbox_tree_add_item — Adds new item to the checkbox tree
$checkboxtree
, string $text
, mixed $data
, int $flags
, int $index
[, int $...
] )This function allows to add new item to the checkbox tree.
checkboxtree
text
data
flags
index
No value is returned.
(PECL newt >= 0.1)
newt_checkbox_tree_find_item — Finds an item in the checkbox tree
Finds an item in the checkbox tree by item's data.
checkboxtree
data
Returns checkbox tree item resource, or NULL if it wasn't found.
(PECL newt >= 0.1)
newt_checkbox_tree_get_current — Returns checkbox tree selected item
This method returns checkbox tree selected tem.
checkboxtree
Returns current (selected) checkbox tree item.
(PECL newt >= 0.1)
newt_checkbox_tree_get_entry_value —
This function is currently not documented; only its argument list is available.
checkboxtree
data
(PECL newt >= 0.1)
newt_checkbox_tree_get_multi_selection —
$checkboxtree
, string $seqnum
)This function is currently not documented; only its argument list is available.
checkboxtree
seqnum
(PECL newt >= 0.1)
newt_checkbox_tree_get_selection —
$checkboxtree
)This function is currently not documented; only its argument list is available.
checkboxtree
(PECL newt >= 0.1)
newt_checkbox_tree_multi —
$left
, int $top
, int $height
, string $seq
[, int $flags
] )This function is currently not documented; only its argument list is available.
left
top
height
seq
flags
(PECL newt >= 0.1)
newt_checkbox_tree_set_current —
This function is currently not documented; only its argument list is available.
checkboxtree
data
No value is returned.
(PECL newt >= 0.1)
newt_checkbox_tree_set_entry_value —
This function is currently not documented; only its argument list is available.
checkboxtree
data
value
No value is returned.
(PECL newt >= 0.1)
newt_checkbox_tree_set_entry —
This function is currently not documented; only its argument list is available.
checkboxtree
data
text
No value is returned.
(PECL newt >= 0.1)
newt_checkbox_tree_set_width —
$checkbox_tree
, int $width
)This function is currently not documented; only its argument list is available.
checkbox_tree
width
No value is returned.
(PECL newt >= 0.1)
newt_checkbox_tree —
$left
, int $top
, int $height
[, int $flags
] )This function is currently not documented; only its argument list is available.
left
top
height
flags
(PECL newt >= 0.1)
newt_checkbox —
$left
, int $top
, string $text
, string $def_value
[, string $seq
] )This function is currently not documented; only its argument list is available.
left
top
text
def_value
seq
(PECL newt >= 0.1)
newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
Discards the contents of the terminal's input buffer without waiting for additional input.
No value is returned.
(PECL newt >= 0.1)
newt_cls —
This function is currently not documented; only its argument list is available.
No value is returned.
(PECL newt >= 0.1)
newt_component_add_callback —
This function is currently not documented; only its argument list is available.
component
func_name
data
No value is returned.
(PECL newt >= 0.1)
newt_component_takes_focus —
$component
, bool $takes_focus
)This function is currently not documented; only its argument list is available.
component
takes_focus
No value is returned.
(PECL newt >= 0.1)
newt_create_grid —
$cols
, int $rows
)This function is currently not documented; only its argument list is available.
cols
rows
(PECL newt >= 0.1)
newt_cursor_off —
This function is currently not documented; only its argument list is available.
No value is returned.
(PECL newt >= 0.1)
newt_cursor_on —
This function is currently not documented; only its argument list is available.
No value is returned.
(PECL newt >= 0.1)
newt_delay —
$microseconds
)This function is currently not documented; only its argument list is available.
microseconds
No value is returned.
(PECL newt >= 0.1)
newt_draw_form —
$form
)This function is currently not documented; only its argument list is available.
form
No value is returned.
(PECL newt >= 0.1)
newt_draw_root_text — Displays the string text at the position indicated
$left
, int $top
, string $text
)Displays the string text at the position indicated.
leftColumn number
Note:
If left is negative, the position is measured from the opposite side of the screen.
topLine number
Note:
If top is negative, the position is measured from the opposite side of the screen.
textText to display.
No value is returned.
Example #1 A newt_draw_root_text() example
This code demonstrates drawing of titles in the both corners of the screen.
<?php
newt_init();
newt_cls();
newt_draw_root_text (2, 0, "Some root text");
newt_refresh();
sleep(1);
newt_draw_root_text (-30, 0, "Root text in the other corner");
newt_refresh();
sleep(1);
newt_finished();
?>
(PECL newt >= 0.1)
newt_entry_get_value —
$entry
)This function is currently not documented; only its argument list is available.
entry
(PECL newt >= 0.1)
newt_entry_set_filter —
This function is currently not documented; only its argument list is available.
entry
filter
data
No value is returned.
(PECL newt >= 0.1)
newt_entry_set_flags —
$entry
, int $flags
, int $sense
)This function is currently not documented; only its argument list is available.
entry
flags
sense
No value is returned.
(PECL newt >= 0.1)
newt_entry_set —
$entry
, string $value
[, bool $cursor_at_end
] )This function is currently not documented; only its argument list is available.
entry
value
cursor_at_end
No value is returned.
(PECL newt >= 0.1)
newt_entry —
$left
, int $top
, int $width
[, string $init_value
[, int $flags
]] )This function is currently not documented; only its argument list is available.
left
top
width
init_value
flags
(PECL newt >= 0.1)
newt_finished — Uninitializes newt interface
Uninitializes newt interface. This function be called, when program is ready to exit.
Returns 1 on success, 0 on failure.
(PECL newt >= 0.1)
newt_form_add_component — Adds a single component to the form
$form
, resource $component
)
Adds a single component to the form.
formForm to which component will be added
componentComponent to add to the form
No value is returned.
Example #1 A newt_form_add_component() example
<?php
$form = newt_form();
$options = array("Authentication configuration", "Firewall configuration",
"Mouse configuration", "Network configuration", "Printer configuration",
"System services");
$list = newt_listbox(3, 2, 10);
foreach ($options as $l_item) {
newt_listbox_add_entry($list, $l_item, $l_item);
}
newt_form_add_component($form, $list);
?>
(PECL newt >= 0.1)
newt_form_add_components — Add several components to the form
$form
, array $components
)
Adds several components to the form.
formForm to which components will be added
componentsArray of components to add to the form
No value is returned.
Example #1 A newt_form_add_components() example
<?php
$form = newt_form();
$b1 = newt_button(5, 12, "Run Tool");
$b2 = newt_button(21, 12, "Quit");
newt_form_add_components($form, array($b1, $b2));
?>
(PECL newt >= 0.1)
newt_form_add_hot_key —
$form
, int $key
)This function is currently not documented; only its argument list is available.
form
key
No value is returned.
(PECL newt >= 0.1)
newt_form_destroy — Destroys a form
$form
)This function frees the memory resources used by the form and all of the components which have been added to the form (including those components which are on subforms). Once a form has been destroyed, none of the form's components can be used.
formForm component, which is going to be destroyed
No value is returned.
(PECL newt >= 0.1)
newt_form_get_current —
$form
)This function is currently not documented; only its argument list is available.
form
(PECL newt >= 0.1)
newt_form_run — Runs a form
$form
, array &$exit_struct
)This function runs the form passed to it.
formForm component
exit_structArray, used for returning information after running the form component. Keys and values are described in the following table:
| Index Key | Value Type | Description |
|---|---|---|
| reason | integer | The reason, why the form has been exited. Possible values are defined here. |
| watch | resource | Resource link, specified in newt_form_watch_fd() |
| key | integer | Hotkey |
| component | resource | Component, which caused the form to exit |
No value is returned.
(PECL newt >= 0.1)
newt_form_set_background —
$from
, int $background
)This function is currently not documented; only its argument list is available.
from
background
No value is returned.
(PECL newt >= 0.1)
newt_form_set_height —
$form
, int $height
)This function is currently not documented; only its argument list is available.
form
height
No value is returned.
(PECL newt >= 0.1)
newt_form_set_size —
$form
)This function is currently not documented; only its argument list is available.
form
No value is returned.
(PECL newt >= 0.1)
newt_form_set_timer —
$form
, int $milliseconds
)This function is currently not documented; only its argument list is available.
form
milliseconds
No value is returned.
(PECL newt >= 0.1)
newt_form_set_width —
$form
, int $width
)This function is currently not documented; only its argument list is available.
form
width
No value is returned.
(PECL newt >= 0.1)
newt_form_watch_fd —
$form
, resource $stream
[, int $flags
] )This function is currently not documented; only its argument list is available.
form
stream
flags
No value is returned.
(PECL newt >= 0.1)
newt_form — Create a form
$vert_bar
[, string $help
[, int $flags
]]] )Create a new form.
vert_barVertical scrollbar which should be associated with the form
helpHelp text string
flagsVarious flags
Returns a resource link to the created form component, or FALSE on
error.
Example #1 A newt_form() example
Displays a single button "Quit", which closes the application once it's pressed.
<?php
newt_init();
newt_cls();
$myform = newt_form();
$button = newt_button (5, 12, "Quit");
newt_form_add_component ($myform, $button);
newt_refresh ();
newt_run_form ($myform);
newt_finished ();
newt_form_destroy ($myform);
?>
(PECL newt >= 0.1)
newt_get_screen_size — Fills in the passed references with the current size of the terminal
&$cols
, int &$rows
)Fills in the passed references with the current size of the terminal.
colsNumber of columns in the terminal
rowsNumber of rows in the terminal
No value is returned.
Example #1 A newt_get_screen_size() example
This code prints out the screen size of your terminal.
<?php
newt_init();
newt_get_screen_size (&$cols, &$rows);
newt_finished();
print "Your terminal size is: {$cols}x{$rows}\n";
?>
The above example will output:
Your terminal size is: 138x47
(PECL newt >= 0.1)
newt_grid_add_components_to_form —
$grid
, resource $form
, bool $recurse
)This function is currently not documented; only its argument list is available.
grid
form
recurse
No value is returned.
(PECL newt >= 0.1)
newt_grid_basic_window —
$text
, resource $middle
, resource $buttons
)This function is currently not documented; only its argument list is available.
text
middle
buttons
(PECL newt >= 0.1)
newt_grid_free —
$grid
, bool $recurse
)This function is currently not documented; only its argument list is available.
grid
recurse
No value is returned.
(PECL newt >= 0.1)
newt_grid_get_size —
$grid
, int &$width
, int &$height
)This function is currently not documented; only its argument list is available.
grid
width
height
No value is returned.
(PECL newt >= 0.1)
newt_grid_h_close_stacked —
$element1_type
, resource $element1
[, int $...
[, resource $...
]] )This function is currently not documented; only its argument list is available.
element1_type
element1
(PECL newt >= 0.1)
newt_grid_h_stacked —
$element1_type
, resource $element1
[, int $...
[, resource $...
]] )This function is currently not documented; only its argument list is available.
element1_type
element1
(PECL newt >= 0.1)
newt_grid_place —
$grid
, int $left
, int $top
)This function is currently not documented; only its argument list is available.
grid
left
top
No value is returned.
(PECL newt >= 0.1)
newt_grid_set_field —
$grid
, int $col
, int $row
, int $type
, resource $val
, int $pad_left
, int $pad_top
, int $pad_right
, int $pad_bottom
, int $anchor
[, int $flags
] )This function is currently not documented; only its argument list is available.
grid
col
row
type
val
pad_left
pad_top
pad_right
pad_bottom
anchor
flags
No value is returned.
(PECL newt >= 0.1)
newt_grid_simple_window —
$text
, resource $middle
, resource $buttons
)This function is currently not documented; only its argument list is available.
text
middle
buttons
(PECL newt >= 0.1)
newt_grid_v_close_stacked —
$element1_type
, resource $element1
[, int $...
[, resource $...
]] )This function is currently not documented; only its argument list is available.
element1_type
element1
(PECL newt >= 0.1)
newt_grid_v_stacked —
$element1_type
, resource $element1
[, int $...
[, resource $...
]] )This function is currently not documented; only its argument list is available.
element1_type
element1
(PECL newt >= 0.1)
newt_grid_wrapped_window_at —
$grid
, string $title
, int $left
, int $top
)This function is currently not documented; only its argument list is available.
grid
title
left
top
No value is returned.
(PECL newt >= 0.1)
newt_grid_wrapped_window —
$grid
, string $title
)This function is currently not documented; only its argument list is available.
grid
title
No value is returned.
(PECL newt >= 0.1)
newt_init — Initialize newt
Initializes the newt interface. This function must be called before any other newt function.
Returns 1 on success, 0 on failure.
(PECL newt >= 0.1)
newt_label_set_text —
$label
, string $text
)This function is currently not documented; only its argument list is available.
label
text
No value is returned.
(PECL newt >= 0.1)
newt_label —
$left
, int $top
, string $text
)This function is currently not documented; only its argument list is available.
left
top
text
(PECL newt >= 0.1)
newt_listbox_append_entry —
This function is currently not documented; only its argument list is available.
listbox
text
data
No value is returned.
(PECL newt >= 0.1)
newt_listbox_clear_selection —
$listbox
)This function is currently not documented; only its argument list is available.
listbox
No value is returned.
(PECL newt >= 0.1)
newt_listbox_clear —
$listobx
)This function is currently not documented; only its argument list is available.
listobx
No value is returned.
(PECL newt >= 0.1)
newt_listbox_delete_entry —
This function is currently not documented; only its argument list is available.
listbox
key
No value is returned.
(PECL newt >= 0.1)
newt_listbox_get_current —
$listbox
)This function is currently not documented; only its argument list is available.
listbox
(PECL newt >= 0.1)
newt_listbox_get_selection —
$listbox
)This function is currently not documented; only its argument list is available.
listbox
(PECL newt >= 0.1)
newt_listbox_insert_entry —
This function is currently not documented; only its argument list is available.
listbox
text
data
key
No value is returned.
(PECL newt >= 0.1)
newt_listbox_item_count —
$listbox
)This function is currently not documented; only its argument list is available.
listbox
(PECL newt >= 0.1)
newt_listbox_select_item —
This function is currently not documented; only its argument list is available.
listbox
key
sense
No value is returned.
(PECL newt >= 0.1)
newt_listbox_set_current_by_key —
This function is currently not documented; only its argument list is available.
listbox
key
No value is returned.
(PECL newt >= 0.1)
newt_listbox_set_current —
$listbox
, int $num
)This function is currently not documented; only its argument list is available.
listbox
num
No value is returned.
(PECL newt >= 0.1)
newt_listbox_set_data —
This function is currently not documented; only its argument list is available.
listbox
num
data
No value is returned.
(PECL newt >= 0.1)
newt_listbox_set_entry —
$listbox
, int $num
, string $text
)This function is currently not documented; only its argument list is available.
listbox
num
text
No value is returned.
(PECL newt >= 0.1)
newt_listbox_set_width —
$listbox
, int $width
)This function is currently not documented; only its argument list is available.
listbox
width
No value is returned.
(PECL newt >= 0.1)
newt_listbox —
$left
, int $top
, int $height
[, int $flags
] )This function is currently not documented; only its argument list is available.
left
top
height
flags
(PECL newt >= 0.1)
newt_listitem_get_data —
This function is currently not documented; only its argument list is available.
item
(PECL newt >= 0.1)
newt_listitem_set —
$item
, string $text
)This function is currently not documented; only its argument list is available.
item
text
No value is returned.
(PECL newt >= 0.1)
newt_listitem —
$left
, int $top
, string $text
, bool $is_default
, resouce $prev_item
, mixed $data
[, int $flags
] )This function is currently not documented; only its argument list is available.
left
top
text
is_default
prev_item
data
flags
(PECL newt >= 0.1)
newt_open_window — Open a window of the specified size and position
$left
, int $top
, int $width
, int $height
[, string $title
] )Open a window of the specified size and position.
leftLocation of the upper left-hand corner of the window (column number)
topLocation of the upper left-hand corner of the window (row number)
widthWindow width
heightWindow height
titleWindow title
Returns 1 on success, 0 on failure.
(PECL newt >= 0.1)
newt_pop_help_line — Replaces the current help line with the one from the stack
Replaces the current help line with the one from the stack.
Note:
It's important not to call to newt_pop_help_line() more than newt_push_help_line().
No value is returned.
(PECL newt >= 0.1)
newt_pop_window — Removes the top window from the display
Removes the top window from the display, and redraws the display areas which the window overwrote.
No value is returned.
(PECL newt >= 0.1)
newt_push_help_line — Saves the current help line on a stack, and displays the new line
$text
] )Saves the current help line on a stack, and displays the new line.
textNew help text message
Note:
If not specified, the help line is cleared.
No value is returned.
(PECL newt >= 0.1)
newt_radio_get_current —
$set_member
)This function is currently not documented; only its argument list is available.
set_member
(PECL newt >= 0.1)
newt_redraw_help_line —
This function is currently not documented; only its argument list is available.
No value is returned.
(PECL newt >= 0.1)
newt_reflow_text —
$text
, int $width
, int $flex_down
, int $flex_up
, int &$actual_width
, int &$actual_height
)This function is currently not documented; only its argument list is available.
text
width
flex_down
flex_up
actual_width
actual_height
(PECL newt >= 0.1)
newt_refresh — Updates modified portions of the screen
To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.
No value is returned.
(PECL newt >= 0.1)
newt_resize_screen —
$redraw
] )This function is currently not documented; only its argument list is available.
redraw
No value is returned.
(PECL newt >= 0.1)
newt_resume — Resume using the newt interface after calling newt_suspend()
No value is returned.
(PECL newt >= 0.1)
newt_run_form — Runs a form
$form
)This function runs the form passed to it.
formForm component
The component which caused the form to stop running.
Note:
Notice that this function doesn't fit in with newt's normal naming convention. It is an older interface which will not work for all forms. It was left in newt only for legacy applications. It is a simpler interface than the new newt_form_run() though, and is still used quite often as a result. When an application is done with a form, it destroys the form and all of the components the form contains.
(PECL newt >= 0.1)
newt_scale_set —
$scale
, int $amount
)This function is currently not documented; only its argument list is available.
scale
amount
No value is returned.
(PECL newt >= 0.1)
newt_scale —
$left
, int $top
, int $width
, int $full_value
)This function is currently not documented; only its argument list is available.
left
top
width
full_value
(PECL newt >= 0.1)
newt_scrollbar_set —
$scrollbar
, int $where
, int $total
)This function is currently not documented; only its argument list is available.
scrollbar
where
total
No value is returned.
(PECL newt >= 0.1)
newt_set_help_callback —
This function is currently not documented; only its argument list is available.
function
No value is returned.
(PECL newt >= 0.1)
newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key
Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.
functionA callback function, which accepts one argument: data
dataThis data is been passed to the callback function
No value is returned.
(PECL newt >= 0.1)
newt_suspend — Tells newt to return the terminal to its initial state
Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes).
No value is returned.
(PECL newt >= 0.1)
newt_textbox_get_num_lines —
$textbox
)This function is currently not documented; only its argument list is available.
textbox
(PECL newt >= 0.1)
newt_textbox_reflowed —
$left
, int $top
, char $*text
, int $width
, int $flex_down
, int $flex_up
[, int $flags
] )This function is currently not documented; only its argument list is available.
left
top
*text
width
flex_down
flex_up
flags
(PECL newt >= 0.1)
newt_textbox_set_height —
$textbox
, int $height
)This function is currently not documented; only its argument list is available.
textbox
height
No value is returned.
(PECL newt >= 0.1)
newt_textbox_set_text —
$textbox
, string $text
)This function is currently not documented; only its argument list is available.
textbox
text
No value is returned.
(PECL newt >= 0.1)
newt_textbox —
$left
, int $top
, int $width
, int $height
[, int $flags
] )This function is currently not documented; only its argument list is available.
left
top
width
height
flags
(PECL newt >= 0.1)
newt_vertical_scrollbar —
$left
, int $top
, int $height
[, int $normal_colorset
[, int $thumb_colorset
]] )This function is currently not documented; only its argument list is available.
left
top
height
normal_colorset
thumb_colorset
(PECL newt >= 0.1)
newt_wait_for_key — Doesn't return until a key has been pressed
This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.
No value is returned.
(PECL newt >= 0.1)
newt_win_choice —
$title
, string $button1_text
, string $button2_text
, string $format
[, mixed $args
[, mixed $...
]] )This function is currently not documented; only its argument list is available.
title
button1_text
button2_text
format
args
(PECL newt >= 0.1)
newt_win_entries —
$title
, string $text
, int $suggested_width
, int $flex_down
, int $flex_up
, int $data_width
, array &$items
, string $button1
[, string $...
] )This function is currently not documented; only its argument list is available.
title
text
suggested_width
flex_down
flex_up
data_width
items
button1
button2
Example #1 A newt_win_entries() example
<?php
newt_init();
newt_cls();
$entries[] = array('text' => 'First name:', 'value' => &$f_name);
$entries[] = array('text' => 'Last name:', 'value' => &$l_name);
$rc = newt_win_entries("User information", "Please enter your credentials:", 50, 7, 7, 30, $entries, "Ok", "Back");
newt_finished ();
if ($rc != 2) {
echo "Your name is: $f_name $l_name\n";
}
?>
(PECL newt >= 0.1)
newt_win_message —
$title
, string $button_text
, string $format
[, mixed $args
[, mixed $...
]] )This function is currently not documented; only its argument list is available.
title
button_text
format
args
No value is returned.
(PECL newt >= 0.1)
newt_win_messagev —
$title
, string $button_text
, string $format
, array $args
)This function is currently not documented; only its argument list is available.
title
button_text
format
args
No value is returned.
(PECL newt >= 0.1)
newt_win_ternary —
$title
, string $button1_text
, string $button2_text
, string $button3_text
, string $format
[, mixed $args
[, mixed $...
]] )This function is currently not documented; only its argument list is available.
titleIts description
button1_textIts description
button2_textIts description
button3_textIts description
formatIts description
argsIts description
What the function returns, first on success, then on failure. See also the &return.success; entity
The readline functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts used from a command line.
Note: This extension is not available on Windows platforms.
To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at » http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.
You can also use these functions with the libedit library, a non-GPL replacement for the readline library. The libedit library is BSD licensed and available for download from » http://www.thrysoee.dk/editline/.
To use these functions you must compile the CGI or CLI version of PHP with readline support. You need to configure PHP --with-readline[=DIR] . If you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR] .
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| cli.pager | "" | PHP_INI_ALL | Available since PHP 5.4.0. |
| cli.prompt | "\\b \\> " | PHP_INI_ALL | Available since PHP 5.4.0. |
Here's a short explanation of the configuration directives.
cli.pager
string
External tool to display output from command line.
cli.prompt
string
Command line prompt.
This extension has no resource types defined.
This extension has no constants defined.
(PHP 4, PHP 5)
readline_add_history — Adds a line to the history
$line
)This function adds a line to the command line history.
lineThe line to be added in the history.
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.1.0)
readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately
Sets up a readline callback interface then prints
prompt and immediately returns.
Calling this function twice without removing the previous
callback interface will automatically and conveniently overwrite the old
interface.
The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().
promptThe prompt message.
callback
The callback function takes one parameter; the
user input returned.
Returns TRUE on success or FALSE on failure.
Example #1 Readline Callback Interface Example
<?php
function rl_callback($ret)
{
global $c, $prompting;
echo "You entered: $ret\n";
$c++;
if ($c > 10) {
$prompting = false;
readline_callback_handler_remove();
} else {
readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
}
}
$c = 1;
$prompting = true;
readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
while ($prompting) {
$w = NULL;
$e = NULL;
$n = stream_select($r = array(STDIN), $w, $e, null);
if ($n && in_array(STDIN, $r)) {
// read a character, will call the callback when a newline is entered
readline_callback_read_char();
}
}
echo "Prompting disabled. All done.\n";
?>
(PHP 5 >= 5.1.0)
readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings
Removes a previously installed callback handler and restores terminal settings.
Returns TRUE if a previously installed callback handler was removed, or
FALSE if one could not be found.
See readline_callback_handler_install() for an example of how to use the readline callback interface.
(PHP 5 >= 5.1.0)
readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received
Reads a character of user input. When a line is received, this function informs the readline callback interface installed using readline_callback_handler_install() that a line is ready for input.
No value is returned.
See readline_callback_handler_install() for an example of how to use the readline callback interface.
(PHP 4, PHP 5)
readline_clear_history — Clears the history
This function clears the entire command line history.
Returns TRUE on success or FALSE on failure.
(PHP 4, PHP 5)
readline_completion_function — Registers a completion function
This function registers a completion function. This is the same kind of functionality you'd get if you hit your tab key while using Bash.
functionYou must supply the name of an existing function which accepts a partial command line and returns an array of possible matches.
Returns TRUE on success or FALSE on failure.
(PHP 4, PHP 5)
readline_info — Gets/sets various internal readline variables
Gets or sets various internal readline variables.
varnameA variable name.
newvalueIf provided, this will be the new value of the setting.
If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.
If called with one or two parameters, the old value is returned.
(PHP 4, PHP 5)
readline_list_history — Lists the history
Gets the entire command line history.
Returns an array of the entire command line history. The elements are indexed by integers starting at zero.
(PHP 5 >= 5.1.0)
readline_on_new_line — Inform readline that the cursor has moved to a new line
Tells readline that the cursor has moved to a new line.
No value is returned.
(PHP 4, PHP 5)
readline_read_history — Reads the history
$filename
] )This function reads a command history from a file.
filenamePath to the filename containing the command history.
Returns TRUE on success or FALSE on failure.
(PHP 5 >= 5.1.0)
readline_redisplay — Redraws the display
Redraws readline to redraw the display.
No value is returned.
(PHP 4, PHP 5)
readline_write_history — Writes the history
$filename
] )This function writes the command history to a file.
filenamePath to the saved file.
Returns TRUE on success or FALSE on failure.
(PHP 4, PHP 5)
readline — Reads a line
$prompt
] )Reads a single line from the user. You must add this line to the history yourself using readline_add_history().
promptYou may specify a string with which to prompt the user.
Returns a single string from the user. The line returned has the ending newline removed.
Example #1 readline() Example
<?php
//get 3 commands from user
for ($i=0; $i < 3; $i++) {
$line = readline("Command: ");
readline_add_history($line);
}
//dump history
print_r(readline_list_history());
//dump variables
print_r(readline_info());
?>
The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.
This module uses the functions of the » bzip2 library by Julian Seward. This module requires bzip2/libbzip2 version >= 1.0.x.
Bzip2 support in PHP is not enabled by default. You will need to use the --with-bz2[=DIR] configuration option when compiling PHP to enable bzip2 support.
This extension has no configuration directives defined in php.ini.
This extension defines one resource type: a file pointer identifying the bz2-file to work on.
This extension has no constants defined.
This example opens a temporary file and writes a test string to it, then prints out the contents of the file.
Example #1 Small bzip2 Example
<?php
$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";
// open file for writing
$bz = bzopen($filename, "w");
// write string to file
bzwrite($bz, $str);
// close file
bzclose($bz);
// open file for reading
$bz = bzopen($filename, "r");
// read 10 characters
echo bzread($bz, 10);
// output until end of the file (or the next 1024 char) and close it.
echo bzread($bz);
bzclose($bz);
?>
(PHP 4 >= 4.0.4, PHP 5)
bzclose — Close a bzip2 file
$bz
)Closes the given bzip2 file pointer.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.0.4, PHP 5)
bzcompress — Compress a string into bzip2 encoded data
bzcompress() compresses the given string and returns it as bzip2 encoded data.
sourceThe string to compress.
blocksizeSpecifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so.
workfactorControls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case.
Regardless of the workfactor, the generated
output is the same.
The compressed string, or an error number if an error occurred.
Example #1 Compressing data
<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>
(PHP 4 >= 4.0.4, PHP 5)
bzdecompress — Decompresses bzip2 encoded data
bzdecompress() decompresses the given string containing bzip2 encoded data.
sourceThe string to decompress.
small
If TRUE, an alternative decompression algorithm will be used which
uses less memory (the maximum memory requirement drops to around 2300K)
but works at roughly half the speed.
See the » bzip2 documentation for more information about this feature.
The decompressed string, or an error number if an error occurred.
Example #1 Decompressing a String
<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);
echo "Compressed String: ";
echo $bzstr;
echo "\n<br />\n";
$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n<br />\n";
?>
(PHP 4 >= 4.0.4, PHP 5)
bzerrno — Returns a bzip2 error number
$bz
)Returns the error number of any bzip2 error returned by the given file pointer.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Returns the error number as an integer.
(PHP 4 >= 4.0.4, PHP 5)
bzerror — Returns the bzip2 error number and error string in an array
$bz
)Returns the error number and error string of any bzip2 error returned by the given file pointer.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Returns an associative array, with the error code in the errno entry, and the error message in the errstr entry.
Example #1 bzerror() example
<?php
$error = bzerror($bz);
echo $error["errno"];
echo $error["errstr"];
?>
(PHP 4 >= 4.0.4, PHP 5)
bzerrstr — Returns a bzip2 error string
$bz
)Gets the error string of any bzip2 error returned by the given file pointer.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Returns a string containing the error message.
(PHP 4 >= 4.0.4, PHP 5)
bzflush — Force a write of all buffered data
$bz
)
Forces a write of all buffered bzip2 data for the file pointer
bz.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
Returns TRUE on success or FALSE on failure.
(PHP 4 >= 4.0.4, PHP 5)
bzopen — Opens a bzip2 compressed file
$filename
, string $mode
)bzopen() opens a bzip2 (.bz2) file for reading or writing.
filenameThe name of the file to open, or an existing stream resource.
mode
Similar to the fopen() function, only 'r' (read)
and 'w' (write) are supported. Everything else will cause bzopen
to return FALSE.
If the open fails, bzopen() returns FALSE, otherwise
it returns a pointer to the newly opened file.
Example #1 bzopen() example
<?php
$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");
bzclose($bz);
?>
(PHP 4 >= 4.0.4, PHP 5)
bzread — Binary safe bzip2 file read
$bz
[, int $length = 1024
] )bzread() reads from the given bzip2 file pointer.
Reading stops when length (uncompressed) bytes have
been read or EOF is reached, whichever comes first.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
lengthIf not specified, bzread() will read 1024 (uncompressed) bytes at a time. A maximum of 8192 uncompressed bytes will be read at a time.
Returns the uncompressed data, or FALSE on error.
Example #1 bzread() example
<?php
$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file");
$decompressed_file = '';
while (!feof($bz)) {
$decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);
echo "The contents of $file are: <br />\n";
echo $decompressed_file;
?>
(PHP 4 >= 4.0.4, PHP 5)
bzwrite — Binary safe bzip2 file write
$bz
, string $data
[, int $length
] )bzwrite() writes a string into the given bzip2 file stream.
bzThe file pointer. It must be valid and must point to a file successfully opened by bzopen().
dataThe written data.
length
If supplied, writing will stop after length
(uncompressed) bytes have been written or the end of
data is reached, whichever comes first.
Returns the number of bytes written, or FALSE on error.
Example #1 bzwrite() example
<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>
LZF is a very fast compression algorithm, ideal for saving space with only slight speed cost. It can be optimized for speed or space at the time of compilation. This extension is using » liblzf library by Marc Lehmann for its operations.
No external libraries are needed to build this extension.
This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » http://pecl.php.net/package/lzf.
In order to use these functions you must compile PHP with lzf support by using the --with-lzf[=DIR] configure option. You may also pass --enable-lzf-better-compression to optimize LZF for space rather than speed.
Windows users will enable php_lzf.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.
This extension has no configuration directives defined in php.ini.
This extension has no resource types defined.
This extension has no constants defined.
(PECL lzf >= 0.1.0)
lzf_compress — LZF compression
$data
)
lzf_compress() compresses the given
data string using LZF encoding.
dataThe string to compress.
Returns the compressed data or FALSE if an error occurred.
(PECL lzf >= 0.1.0)
lzf_decompress — LZF decompression
$data
)
lzf_compress() decompresses the given
data string containing lzf encoded data.
dataThe compressed string.
Returns the decompressed data or FALSE if an error occurred.
(PECL lzf >= 1.0.0)
lzf_optimized_for — Determines what LZF extension was optimized for
Determines what was LZF extension optimized for during compilation.
Returns 1 if LZF was optimized for speed, 0 for compression.
The phar extension provides a way to put entire PHP applications into a single file called a "phar" (PHP Archive) for easy distribution and installation. In addition to providing this service, the phar extension also provides a file-format abstraction method for creating and manipulating tar and zip files through the PharData class, much as PDO provides a unified interface for accessing different databases. Unlike PDO, which cannot convert between different databases, Phar also can convert between tar, zip and phar file formats with a single line of code. see Phar::convertToExecutable() for one example.
What is phar? Phar archives are best characterized as a convenient way to group several files into a single file. As such, a phar archive provides a way to distribute a complete PHP application in a single file and run it from that file without the need to extract it to disk. Additionally, phar archives can be executed by PHP as easily as any other file, both on the commandline and from a web server. Phar is kind of like a thumb drive for PHP applications.
Phar implements this functionality through a Stream Wrapper. Normally, to use an external file within a PHP script, you would use include
Example #1 Using an external file
<?php
include '/path/to/external/file.php';
?>
PHP can be thought of as actually translating /path/to/external/file.php into a stream wrapper as file:///path/to/external/file.php, and under the hood it does in fact use the plain file stream wrapper stream functions to access all local files.
To use a file named file.php contained with a phar archive /path/to/myphar.phar, the syntax is very similar to the file:// syntax above.
Example #2 Using a file within a phar archive
<?php
include 'phar:///path/to/myphar.phar/file.php';
?>
In fact, one can treat a phar archive exactly as if it were an external disk, using any of fopen()-related functions, opendir() and mkdir()-related functions to read, change, or create new files and directories within the phar archive. This allows complete PHP applications to be distributed in a single file and run directly from that file.
The most common usage for a phar archive is to distribute a complete application in a single file. For instance, the PEAR Installer that is bundled with PHP versions is distributed as a phar archive. To use a phar archive distributed in this way, the archive can be executed on the command-line or via a web server.
Phar archives can be distributed as tar archives, zip archives, or as the custom phar file format designed specifically for the phar extension. Each file format has advantages and disadvantages. The tar and zip file formats can be read or extracted by any third-party tool that can read the format, but require the phar extension in order to run with PHP. The phar file format is customized and unique to the phar extension, and can only be created by the phar extension or the PEAR package » PHP_Archive, but has the advantage that applications created in this format will run even if the phar extension is not enabled.
In other words, even with the phar extension disabled, one can execute or include a phar-based archive. Accessing individual files within a phar archive is only possible with the phar extension unless the phar archive was created by PHP_Archive.
The phar extension is also capable of converting a phar archive from tar to zip or to phar file format in a single command:
Example #3 Converting a phar archive from phar to tar file format
<?php
$phar = new Phar('myphar.phar');
$pgz = $phar->convertToExecutable(Phar::TAR, Phar::GZ); // makes myphar.phar.tar.gz
?>
Phar can compress individual files or an entire archive using gzip compression or bzip2 compression, and can verify archive integrity automatically through the use of MD5, SHA-1, SHA-256 or SHA-512 signatures.
Lastly, the Phar extension is security-conscious, and disables write access to executable phar archives by default, and requires system-level disabling of the phar.readonly php.ini setting in order to create or modify phar archives. Normal tar and zip archives without an executable stub can always be created or modified using the PharData class.
If you are creating applications for distribution, you will want to read How to create Phar Archives. If you want more information on the differences between the three file formats that phar supports, you should read Phar, Tar and Zip.
If you are using phar applications, there are helpful tips in How to use Phar Archives
The word phar is a contraction of PHP and Archive and is based loosely on the jar (Java Archive) familiar to Java developers.
The implementation for Phar archives is based on the PEAR package » PHP_Archive, and the implementation details are similar, although the Phar extension is much more powerful. In addition, the Phar extension allows most PHP applications to be run unmodified while PHP_Archive-based phar archives often require extensive modification in order to work.
Phar requires PHP 5.2.0 or newer. Additional features require the SPL extension in order to take advantage of iteration and array access to a Phar's file contents. The phar stream does not require any additional extensions to function.
You may optionally wish to enable the zlib and bzip2 extensions to take advantage of compressed phar support. In addition, to take advantage of OpenSSL signing, the OpenSSL extension must be enabled.
Note that a bug in the zlib.deflate stream filter fixed in PHP version 5.2.6 and newer may cause truncation of gzip and bzip2-compressed phar archives.
PHP 5.3 configured with --enable-zend-multibyte makes phar dependant on the ini option detect_unicode.
The Phar extension is built into PHP as of PHP version 5.3.0. Phar may be installed via the PECL extension with previous PHP versions, and the » Phar PECL page contains further information and history.
The behaviour of these functions is affected by settings in php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| phar.readonly | "1" | PHP_INI_ALL | |
| phar.require_hash | "1" | PHP_INI_ALL | |
| phar.extract_list | "" | PHP_INI_ALL | Available from phar 1.1.0 to 1.2.3, removed in 2.0.0. |
| phar.cache_list | "" | PHP_INI_SYSTEM | Available from phar 2.0.0. |
Here's a short explanation of the configuration directives.
phar.readonly
boolean
This option disables creation or modification of Phar archives using the phar stream or Phar object's write support. This setting should always be enabled on production machines, as the phar extension's convenient write support could allow straightforward creation of a php-based virus when coupled with other common security vulnerabilities.
Note:
This setting can only be unset in php.ini due to security reasons. If phar.readonly is disabled in php.ini, the user may enable phar.readonly in a script or disable it later. If phar.readonly is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.
phar.require_hash
boolean
This option will force all opened Phar archives to contain some kind of signature (currently MD5, SHA1, SHA256 and SHA512 are supported), and will refuse to process any Phar archive that does not contain a signature.
Note:
This setting can only be unset in php.ini due to security reasons. If phar.require_hash is disabled in php.ini, the user may enable phar.require_hash in a script or disable it later. If phar.require_hash is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.
This setting does not affect reading plain tar files with the PharData class.
phar.extract_list
string
This INI setting has been removed as of phar 2.0.0
Allows mappings from a full path to a phar archive or its alias to the location of its extracted files. The format of the parameter is name=archive,name2=archive2. This allows extraction of phar files to disk, and allows phar to act as a kind of mapper to extracted disk files. This is often done for performance reasons, or to assist with debugging a phar.
Example #1 phar.extract_list usage example
in php.ini:
phar.extract_list = archive=/full/path/to/archive/,arch2=/full/path/to/arch2
<?php
include "phar://archive/content.php";
include "phar://arch2/foo.php";
?>
phar.cache_list
string
This INI setting was added in phar 2.0.0
Allows mapping phar archives to be pre-parsed at web server startup, providing a performance improvement that brings running files out of a phar archive very close to the speed of running those files from a traditional disk-based installation.
Example #2 phar.cache_list usage example
in php.ini (windows): phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar in php.ini (unix): phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar
The Phar extension provides the phar stream, which allows accessing files contained within a phar transparently. See also the description of the Phar file format.
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
| Constant | Value | Description |
|---|---|---|
Phar::NONE
(integer)
|
0x00000000 | no compression |
Phar::COMPRESSED
(integer)
|
0x0000F000 | bitmask that can be used with file flags to determine if any compression is present |
Phar::GZ
(integer)
|
0x00001000 | zlib (gzip) compression |
Phar::BZ2
(integer)
|
0x00002000 | bzip2 compression |
| Constant | Value | Description |
|---|---|---|
Phar::SAME
(integer)
|
0 | retain the same file format |
Phar::PHAR
(integer)
|
1 | phar file format |
Phar::TAR
(integer)
|
2 | tar file format |
Phar::ZIP
(integer)
|
3 | zip file format |
| Constant | Value | Description |
|---|---|---|
Phar::MD5
(integer)
|
0x0001 | signature with md5 hash algorithm |
Phar::SHA1
(integer)
|
0x0002 | signature with sha1 hash algorithm |
Phar::SHA256
(integer)
|
0x0003 | signature with sha256 hash algorithm (requires hash extension) |
Phar::SHA512
(integer)
|
0x0004 | signature with sha512 hash algorithm (requires hash extension) |
Phar::OPENSSL
(integer)
|
0x0010 | signature with OpenSSL public/private key pair. This is a true, asymmetric key signature. |
| Constant | Value | Description |
|---|---|---|
Phar::PHP
(integer)
|
1 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP file |
Phar::PHPS
(integer)
|
2 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP source file through highlight_file() |
Phar archives are similar in concept to Java JAR archives, but are tailored to the needs and to the flexibility of PHP applications. A Phar archive is used to distribute a complete PHP application or library in a single file. A Phar archive application is used exactly like any other PHP application:
php coolapplication.phar
Using a Phar archive library is identical to using any other PHP library:
<?php
include 'coollibrary.phar';
?>
The phar stream wrapper provides the core of the phar extension, and is explained in detail here. The phar stream wrapper allows accessing the files within a phar archive using PHP's standard file functions fopen(), opendir(), and others that work on regular files. The phar stream wrapper supports all read/write operations on both files and directories.
<?php
include 'phar://coollibrary.phar/internal/file.php';
header('Content-type: image/jpeg');
// phars can be accessed by full path or by alias
echo file_get_contents('phar:///fullpath/to/coollibrary.phar/images/wow.jpg');
?>
The Phar class implements advanced functionality for accessing files and for creating phar archives. The Phar class is explained in detail here.
<?php
try {
// open an existing phar
$p = new Phar('coollibrary.phar', 0);
// Phar extends SPL's DirectoryIterator class
foreach (new RecursiveIteratorIterator($p) as $file) {
// $file is a PharFileInfo class, and inherits from SplFileInfo
echo $file->getFileName() . "\n";
echo file_get_contents($file->getPathName()) . "\n"; // display contents;
}
if (isset($p['internal/file.php'])) {
var_dump($p['internal/file.php']->getMetadata());
}
// create a new phar - phar.readonly must be 0 in php.ini
// phar.readonly is enabled by default for security reasons.
// On production servers, Phars need never be created,
// only executed.
if (Phar::canWrite()) {
$p = new Phar('newphar.tar.phar', 0, 'newphar.tar.phar');
// make this a tar-based phar archive, compressed with gzip compression (.tar.gz)
$p = $p->convertToExecutable(Phar::TAR, Phar::GZ);
// create transaction - nothing is written to newphar.phar
// until stopBuffering() is called, although temporary storage is needed
$p->startBuffering();
// add all files in /path/to/project, saving in the phar with the prefix "project"
$p->buildFromIterator(new RecursiveIteratorIterator(new DirectoryIterator('/path/to/project')), '/path/to/');
// add a new file via the array access API
$p['file1.txt'] = 'Information';
$fp = fopen('hugefile.dat', 'rb');
// copy all data from the stream
$p['data/hugefile.dat'] = $fp;
if (Phar::canCompress(Phar::GZ)) {
$p['data/hugefile.dat']->compress(Phar::GZ);
}
$p['images/wow.jpg'] = file_get_contents('images/wow.jpg');
// any value can be saved as file-specific meta-data
$p['images/wow.jpg']->setMetadata(array('mime-type' => 'image/jpeg'));
$p['index.php'] = file_get_contents('index.php');
$p->setMetadata(array('bootstrap' => 'index.php'));
// save the phar archive to disk
$p->stopBuffering();
}
} catch (Exception $e) {
echo 'Could not open Phar: ', $e;
}
?>
In addition, verification of phar file contents can be done using any of the supported symmetric hash algorithms (MD5, SHA1, SHA256 and SHA512 if ext/hash is enabled) and using asymmetric public/private key signing using OpenSSL (new in Phar 2.0.0). To take advantage of OpenSSL signing, you need to generate a public/private key pair, and use the private key to set the signature using Phar::setSignatureAlgorithm(). In addition, the public key as extracted using this code:
<?php
$public = openssl_get_publickey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($public, $pkey);
?>
As of version 2.0.0, The Phar class also provides 3 static methods, Phar::webPhar(), Phar::mungServer() and Phar::interceptFileFuncs() that are crucial to packaging up PHP applications designed for usage on regular filesystems and for web-based applications. Phar::webPhar() implements a front controller that routes HTTP calls to the correct location within the phar archive. Phar::mungServer() is used to modify the values of the $_SERVER array to trick applications that process these values. Phar::interceptFileFuncs() instructs Phar to intercept calls to fopen(), file_get_contents(), opendir(), and all of the stat-based functions (file_exists(), is_readable() and so on) and route all relative paths to locations within the phar archive.
As an example, packaging up a release of the popular phpMyAdmin application for use as a phar archive requires only this simple script and then phpMyAdmin.phar.tar.php can be accessed as a regular file from your web server after modifying the user/password:
<?php
@unlink('phpMyAdmin.phar.tar.php');
copy('phpMyAdmin-2.11.3-english.tar.gz', 'phpMyAdmin.phar.tar.php');
$a = new Phar('phpMyAdmin.phar.tar.php');
$a->startBuffering();
$a["phpMyAdmin-2.11.3-english/config.inc.php"] = '<?php
/* Servers configuration */
$i = 0;
/* Server localhost (config:root) [1] */
$i++;
$cfg[\'Servers\'][$i][\'host\'] = \'localhost\';
$cfg[\'Servers\'][$i][\'extension\'] = \'mysqli\';
$cfg[\'Servers\'][$i][\'connect_type\'] = \'tcp\';
$cfg[\'Servers\'][$i][\'compress\'] = false;
$cfg[\'Servers\'][$i][\'auth_type\'] = \'config\';
$cfg[\'Servers\'][$i][\'user\'] = \'root\';
$cfg[\'Servers\'][$i][\'password\'] = \'\';
/* End of servers configuration */
if (strpos(PHP_OS, \'WIN\') !== false) {
$cfg[\'UploadDir\'] = getcwd();
} else {
$cfg[\'UploadDir\'] = \'/tmp/pharphpmyadmin\';
@mkdir(\'/tmp/pharphpmyadmin\');
@chmod(\'/tmp/pharphpmyadmin\', 0777);
}';
$a->setStub('<?php
Phar::interceptFileFuncs();
Phar::webPhar("phpMyAdmin.phar", "phpMyAdmin-2.11.3-english/index.php");
echo "phpMyAdmin is intended to be executed from a web browser\n";
exit -1;
__HALT_COMPILER();
');
$a->stopBuffering();
?>
The Phar stream wrapper fully supports fopen() for read and write (not append), unlink(), stat(), fstat(), fseek(), rename() and directory stream operations opendir() and as of version 2.0.0, rmdir() and mkdir().
Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:
<?php
$context = stream_context_create(array('phar' =>
array('compress' => Phar::GZ)),
array('metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?>
The phar stream wrapper does not operate on remote files, and cannot operate on remote files, and so is allowed even when the allow_url_fopen and allow_url_include INI options are disabled.
Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read-only operations.
The Phar class supports reading and manipulation of Phar archives, as well as iteration through inherited functionality of the RecursiveDirectoryIterator class. With support for the ArrayAccess interface, files inside a Phar archive can be accessed as if they were part of an associative array.
The PharData class extends the Phar, and allows creating and modifying non-executable (data) tar and zip archives even if phar.readonly=1 in php.ini. As such, PharData::setAlias() and PharData::setStub() are both disabled as the concept of alias and stub are unique to executable phar archives.
It is important to note that when creating a Phar archive, the full path should be passed to the Phar object constructor. Relative paths will fail to initialize.
Assuming that $p is a Phar object initialized as follows:
<?php
$p = new Phar('/path/to/myphar.phar', 0, 'myphar.phar');
?>
An empty Phar archive will be created at /path/to/myphar.phar, or if /path/to/myphar.phar already exists, it will be opened again. The literal myphar.phar demonstrates the concept of an alias that can be used to reference /path/to/myphar.phar in URLs as in:
<?php
// these two calls to file_get_contents() are equivalent if
// /path/to/myphar.phar has an explicit alias of "myphar.phar"
// in its manifest, or if the phar was initialized with the
// previous example's Phar object setup
$f = file_get_contents('phar:///path/to/myphar.phar/whatever.txt');
$f = file_get_contents('phar://myphar.phar/whatever.txt');
?>
With the newly created $p Phar object, the following is possible:
In addition, the Phar object is the only way to access Phar-specific metadata, through Phar::getMetadata(), and the only way to set or retrieve a Phar archive's PHP loader stub through Phar::getStub() and Phar::setStub(). Additionally, compression for the entire Phar archive at once can only be manipulated using the Phar class.
The full list of Phar object functionality is documented below.
The PharFileInfo class extends the SplFileInfo class, and adds several methods for manipulating Phar-specific details of a file contained within a Phar, such as manipulating compression and metadata.
To be written fully in the near future. Before reading this, be sure to read How to use Phar Archives.
A great place to start is by reading about Phar::buildFromIterator(), and the specifics of the file format choices available for archives. A healthy understanding of what a stub is and does is crucial to phar archive creation, and so Phar::setStub() and Phar::createDefaultStub() are good places to start as well. If you are distributing a web-based application, it is crucial to know about Phar::webPhar() and related method Phar::mungServer(). Any application that accesses its own files should also consider using Phar::interceptFileFuncs().
All Phar archives contain three to four sections:
a stub
a manifest describing the contents
the file contents
[optional] a signature for verifying Phar integrity (phar file format only)
A Phar's stub is a simple PHP file. The smallest possible stub follows:
<?php __HALT_COMPILER();
A stub must contain as a minimum, the __HALT_COMPILER(); token at its conclusion. Typically, a stub will contain loader functionality like so:
<?php
Phar::mapPhar();
include 'phar://myphar.phar/index.php';
__HALT_COMPILER();
There are no restrictions on the contents of a Phar stub, except for the requirement
that it conclude with __HALT_COMPILER();. The closing PHP tag
?>
?>
In a tar or zip-based phar archive, the stub is stored in the .phar/stub.php file. The default stub for phar-based Phar archives contains approximately 7k of code to extract the contents of the phar and execute them. See Phar::createDefaultStub() for more detail.
The phar alias is stored in a tar or zip-based phar archive in the .phar/alias.txt file as plain text.
What are the good and the bad things about the three supported file formats in the phar extension? This table attempts to address that question.
| Feature | Phar | Tar | Zip |
|---|---|---|---|
| Standard File Format | No | Yes | Yes |
| Can be executed without the Phar Extension [1] | Yes | No | No |
| Per-file compression | Yes | No | Yes |
| Whole-archive compression | Yes | Yes | No |
| Whole-archive signature validation | Yes | Yes | Yes (PHP 5.3.1+) |
| Web-specific application support | Yes | Yes | Yes |
| Per-file Meta-data | Yes | Yes | Yes |
| Whole-Archive Meta-data | Yes | Yes | Yes |
| Archive creation/modification [2] | Yes | Yes | Yes |
| Full support for all stream wrapper functions | Yes | Yes | Yes |
| Can be created/modified even if phar.readonly=1 [3] | No | Yes | Yes |
[1] PHP can only directly access the contents of a Phar archive without the Phar extension if it is using a stub that extracts the contents of the phar archive. The stub created by Phar::createDefaultStub() extracts the phar archive and runs its contents from a temporary directory if no phar extension is found.
[2] All write access requires phar.readonly to be disabled in php.ini or on the command-line directly.
[3] Only tar and zip archives without .phar in their filename and without an executable stub .phar/stub.php can be created if phar.readonly=1.
Archives based on the tar file format follow the more modern USTAR file format. The design of the tar file header makes them more efficient to access than the zip file format, and almost as efficient as the phar file format. File names are limited to 255 bytes, including full path within the phar archive. There is no limit on the number of files within a tar-based phar archive. These archives can fully compressed in gzip or bzip2 format and still be executed by the Phar extension.
To compress an entire archive, use Phar::compress(). To decompress an entire archive, use Phar::decompress().
Archives based on the zip file format support several features built into the zip file format. Per-file and whole-archive metadata is stored in the zip file comment and zip archive comment as a serialized string. Pre-existing zip comments will be successfully read as a string. Per-file compression read/write is supported with zlib compression, and read access is supported with bzip2 compression. There is no limit on the number of files within a zip-based phar archive. Empty directories are stored in the zip archive as files with a trailing slash like my/directory/
The phar file format is literally laid out as stub/manifest/contents/signature, and stores the crucial information of what is included in the phar archive in its manifest.
The Phar manifest is a highly optimized format that allows per-file specification of file compression, file permissions, and even user-defined meta-data such as file user or group. All values greater than 1 byte are stored in little-endian byte order, with the exception of the API version, which for historical reasons is stored as 3 nibbles in big-endian order.
All unused flags are reserved for future use, and must not be used to store custom information. Use the per-file meta-data facility to store customized information about particular files.
The basic file format of a Phar archive manifest is as follows:
| Size in bytes | Description |
|---|---|
| 4 bytes | Length of manifest in bytes (1 MB limit) |
| 4 bytes | Number of files in the Phar |
| 2 bytes | API version of the Phar manifest (currently 1.0.0) |
| 4 bytes | Global Phar bitmapped flags |
| 4 bytes | Length of Phar alias |
| ?? | Phar alias (length based on previous) |
| 4 bytes | Length of Phar metadata (0 for none) |
| ?? | Serialized Phar Meta-data, stored in serialize() format |
| at least 24 * number of entries bytes | entries for each file |
Here are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap:
| Value | Description |
|---|---|
| 0x00010000 | If set, this Phar contains a verification signature |
| 0x00001000 | If set, this Phar contains at least 1 file that is compressed with zlib compression |
| 0x00002000 | If set, this Phar contains at least 1 file that is compressed with bzip compression |
Each file in the manifest contains the following information:
| Size in bytes | Description |
|---|---|
| 4 bytes | Filename length in bytes |
| ?? | Filename (length specified in previous) |
| 4 bytes | Un-compressed file size in bytes |
| 4 bytes | Unix timestamp of file |
| 4 bytes | Compressed file size in bytes |
| 4 bytes | CRC32 checksum of un-compressed file contents |
| 4 bytes | Bit-mapped File-specific flags |
| 4 bytes | Serialized File Meta-data length (0 for none) |
| ?? | Serialized File Meta-data, stored in serialize() format |
Note that as of API version 1.1.1, empty directories are stored as filenames with a trailing slash like my/directory/
The File-specific bitmap values recognized are:
| Value | Description |
|---|---|
| 0x000001FF | These bits are reserved for defining specific file permissions of a file. Permissions are used for fstat() and can be used to recreate desired permissions upon extraction. |
| 0x00001000 | If set, this file is compressed with zlib compression |
| 0x00002000 | If set, this file is compressed with bzip compression |
Phars containing a signature always have the signature appended to the end of the Phar archive after the loader, manifest, and file contents. The two signature formats supported at this time are MD5 and SHA1.
| Length in bytes | Description |
|---|---|
| 16 or 20 bytes | The actual signature, 20 bytes for an SHA1 signature, 16 bytes for an MD5 signature, 32 bytes for an SHA256 signature, and 64 bytes for an SHA512 signature. |
| 4 bytes | Signature flags. 0x0001 is used to define an MD5 signature, 0x0002 is used to define an SHA1 signature, 0x0004 is used to define an SHA256 signature, and 0x0008 is used to define an SHA512 signature. The SHA256 and SHA512 signature support was introduced with API version 1.1.0. |
| 4 bytes | Magic GBMB used to define the presence of a signature. |
(PHP >= 5.3.0, PECL phar >= 1.0.0)
The Phar class provides a high-level interface to accessing and creating phar archives.
$format = 9021976
[, int $compression = 9021976
[, string $extension
]]] )$format = 9021976
[, int $compression = 9021976
[, string $extension
]]] )(Unknown)
Phar::addEmptyDir — Add an empty directory to the phar archive
$dirname
)Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().
dirnameThe name of the empty directory to create in the phar archive
no return value, exception is thrown on failure.
Example #1 A Phar::addEmptyDir() example
<?php
try {
$a = new Phar('/path/to/phar.phar');
$a->addEmptyDir('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
// handle errors here
}
?>
(Unknown)
Phar::addFile — Add a file from the filesystem to the phar archive
$file
[, string $localname
] )Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
With this method, any file or URL can be added to the phar archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().
fileFull or relative path to a file on disk to be added to the phar archive.
localnamePath that the file will be stored in the archive.
no return value, exception is thrown on failure.
Example #1 A Phar::addFile() example
<?php
try {
$a = new Phar('/path/to/phar.phar');
$a->addFile('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->getContent();
$a->addFile('/full/path/to/file', 'my/file.txt');
$c = $a['my/file.txt']->getContent();
// demonstrate URL usage
$a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
// handle errors here
}
?>
(Unknown)
Phar::addFromString — Add a file from the filesystem to the phar archive
$localname
, string $contents
)Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
With this method, any string can be added to the phar archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().
localnamePath that the file will be stored in the archive.
contentsThe file contents to store
no return value, exception is thrown on failure.
Example #1 A Phar::addFromString() example
<?php
try {
$a = new Phar('/path/to/phar.phar');
$a->addFromString('path/to/file.txt', 'my simple file');
$b = $a['path/to/file.txt']->getContent();
// to add contents from a stream handle for large files, use offsetSet()
$c = fopen('/path/to/hugefile.bin');
$a['largefile.bin'] = $c;
fclose($c);
} catch (Exception $e) {
// handle errors here
}
?>
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::apiVersion — Returns the api version
Return the API version of the phar file format that will be used when creating phars. The Phar extension supports reading API version 1.0.0 or newer. API version 1.1.0 is required for SHA-256 and SHA-512 hash, and API version 1.1.1 is required to store empty directories.
The API version string as in "1.0.0".
Example #1 A Phar::apiVersion() example
<?php
echo Phar::apiVersion();
?>
The above example will output:
1.1.1
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
$base_dir
[, string $regex
] )Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
Populate a phar archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use Phar::buildFromIterator().
base_dirThe full or relative path to the directory that contains all files to add to the archive.
regexAn optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.
Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.
This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.
Example #1 A Phar::buildFromDirectory() example
<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::buildFromIterator — Construct a phar archive from an iterator.
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
Populate a phar archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the phar to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.
iterAny iterator that either associatively maps phar file to location or returns SplFileInfo objects
base_directoryFor iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive
Phar::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.
Example #1 A Phar::buildFromIterator() with SplFileInfo
For most phar archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a phar archive containing the files in this sample directory layout:
/path/to/project/
config/
dist.xml
debug.xml
lib/
file1.php
file2.php
src/
processthing.php
www/
index.php
cli/
index.php
This code could be used to add these files to the "project.phar" phar archive:
<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/project')),
'/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
The file project.phar can then be used immediately. Phar::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the phar archive.
As an interesting note, Phar::buildFromIterator() can also be used to copy the contents of an existing phar archive, as the Phar object descends from DirectoryIterator:
<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
new RecursiveIteratorIterator(
new Phar('/path/to/anotherphar.phar')),
'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
Example #2 A Phar::buildFromIterator() with other iterators
The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:
<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
new ArrayIterator(
array(
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
)));
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>
This method returns UnexpectedValueException when the
iterator returns incorrect values, such as an integer key instead of a
string, a BadMethodCallException when an
SplFileInfo-based iterator is passed without a base_directory
parameter, or a PharException if there were errors
saving the phar archive.
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
$type = 0
] )This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.
typeEither Phar::GZ or Phar::BZ2 can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).
TRUE if compression/decompression is available, FALSE if not.
Example #1 A Phar::canCompress() example
<?php
if (Phar::canCompress()) {
echo file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
echo 'no compression available';
}
?>
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::canWrite — Returns whether phar extension supports writing and creating phars
This static method determines whether write access has been disabled in the system php.ini via the phar.readonly ini variable.
TRUE if write access is enabled, FALSE if it is disabled.
Example #1 A Phar::canWrite() example
<?php
if (Phar::canWrite()) {
file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?>
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
$compression
[, string $extension
] )Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
For tar-based and phar-based phar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.
For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.
In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.
compressionCompression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.
extensionBy default, the extension is .phar.gz or .phar.bz2 for compressing phar archives, and .phar.tar.gz or .phar.tar.bz2 for compressing tar archives. For decompressing, the default file extensions are .phar and .phar.tar.
Returns a Phar object.
Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.
Example #1 A Phar::compress() example
<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
Note:
This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using Phar::compress(), Phar::decompress(), Phar::compressFiles() and Phar::decompressFiles().
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
This method compresses all files in the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files prior to re-compressing with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.
Returns TRUE on success or FALSE on failure.
Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not available, or if any files are compressed using gzip compression and the zlib extension is not enabled.
Example #1 A Phar::compressAllFilesBZIP2() example
<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
$p->compressAllFilesBZIP2();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
?>
The above example will output:
string(10) "myfile.txt" bool(false) bool(false) bool(false) string(11) "myfile2.txt" bool(false) bool(false) bool(false) string(10) "myfile.txt" bool(true) bool(true) bool(false) string(11) "myfile2.txt" bool(true) bool(true) bool(false)
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression
Note:
This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using Phar::compress(), Phar::decompress(), Phar::compressFiles() and Phar::decompressFiles().
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
For tar-based phar archives, this method compresses the entire archive using gzip compression. The resulting file can be processed with the gunzip command, or accessed directly and transparently with the Phar extension.
For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the files prior to re-compressing with gzip compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.
Returns TRUE on success or FALSE on failure.
Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.
Example #1 A Phar::compressAllFilesGZ() example
<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
$p->compressAllFilesGZ();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressedBZIP2());
var_dump($file->isCompressedGZ());
}
?>
The above example will output:
string(10) "myfile.txt" bool(false) bool(false) bool(false) string(11) "myfile2.txt" bool(false) bool(false) bool(false) string(10) "myfile.txt" bool(true) bool(false) bool(true) string(11) "myfile2.txt" bool(true) bool(false) bool(true)
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::compressFiles — Compresses all files in the current Phar archive
$compression
)Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.
For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.
compressionCompression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.
No value is returned.
Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.
Example #1 A Phar::compressFiles() example
<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>
The above example will output:
string(10) "myfile.txt" bool(false) bool(false) bool(false) string(11) "myfile2.txt" bool(false) bool(false) bool(false) string(10) "myfile.txt" int(4096) bool(false) bool(true) string(11) "myfile2.txt" int(4096) bool(false) bool(true)
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::__construct — Construct a Phar archive object
$fname
[, int $flags
[, string $alias
]] )
fnamePath to an existing Phar archive or to-be-created archive. The file name's extension must contain .phar.
flagsFlags to pass to parent class RecursiveDirectoryIterator.
aliasAlias with which this Phar archive should be referred to in calls to stream functionality.
Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.
Example #1 A Phar::__construct() example
<?php
try {
$p = new Phar('/path/to/my.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME,
'my.phar');
} catch (UnexpectedValueException $e) {
die('Could not open my.phar');
} catch (BadMethodCallException $e) {
echo 'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?>
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
$format = 9021976
[, int $compression = 9021976
[, string $extension
]]] )This method is used to convert an executable phar archive to either a tar or zip file. To make the tar or zip non-executable, the phar stub and phar alias files are removed from the newly created archive.
If no changes are specified, this method throws a BadMethodCallException if the archive is in phar file format. For archives in tar or zip file format, this method converts the archive to a non-executable archive.
If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.
format
This should be one of Phar::TAR
or Phar::ZIP. If set to NULL, the existing file format
will be preserved.
compressionThis should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.
extensionThis parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.
If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.
The method returns a PharData object on success and throws an exception on failure.
This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.
Example #1 A Phar::convertToData() example
Using Phar::convertToData():
<?php
try {
$tarphar = new Phar('myphar.phar.tar');
// note that myphar.phar.tar is *not* unlinked
// convert it to the non-executable tar file format
// creates myphar.tar
$tar = $tarphar->convertToData();
// convert to non-executable zip format, creates myphar.zip
$zip = $tarphar->convertToData(Phar::ZIP);
// create myphar.tbz
$tgz = $tarphar->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
// creates myphar.phar.tgz
$phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
// handle the error here
}
?>
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
$format = 9021976
[, int $compression = 9021976
[, string $extension
]]] )Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
This method is used to convert a phar archive to another file format. For instance, it can be used to create a tar-based executable phar archive from a zip-based executable phar archive, or from an executable phar archive in the phar file format. In addition, it can be used to apply whole-archive compression to a tar or phar-based archive.
If no changes are specified, this method throws a BadMethodCallException.
If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.
format
This should be one of Phar::PHAR, Phar::TAR,
or Phar::ZIP. If set to NULL, the existing file format
will be preserved.
compressionThis should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.
extensionThis parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.
If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.
The method returns a Phar object on success and throws an exception on failure.
This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.
Example #1 A Phar::convertToExecutable() example
Using Phar::convertToExecutable():
<?php
try {
$tarphar = new Phar('myphar.phar.tar');
// convert it to the phar file format
// note that myphar.phar.tar is *not* unlinked
$phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
// creates myphar.phar.tgz
$compressed = $phar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::copy — Copy a file internal to the phar archive to another new file within the phar
$oldfile
, string $newfile
)Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
Copy a file internal to the phar archive to another new file within the phar. This is an object-oriented alternative to using copy() with the phar stream wrapper.
oldfile
newfile
returns TRUE on success, but it is safer to encase method call in a
try/catch block and assume success if no exception is thrown.
throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.
Example #1 A Phar::copy() example
This example shows using Phar::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All Phar methods throw exceptions, whereas the stream wrapper uses trigger_error().
<?php
try {
$phar = new Phar('myphar.phar');
$phar['a'] = 'hi';
$phar->copy('a', 'b');
echo $phar['b']; // outputs "hi"
} catch (Exception $e) {
// handle error
}
// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a', 'phar//myphar.phar/c');
echo file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::count — Returns the number of entries (files) in the Phar archive
The number of files contained within this phar, or 0 (the number zero) if none.
Example #1 A Phar::count() example
<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p['file.txt'] = 'hi';
echo 'The new phar has ' . $p->count() . " entries\n";
?>
The above example will output:
The new phar has 0 entries The new phar has 1 entries
(Unknown)
Phar::createDefaultStub — Create a phar-file format specific stub
$indexfile
[, string $webindexfile
]] )This method is intended for creation of phar-file format-specific stubs, and is not intended for use with tar- or zip-based phar archives.
Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:
<?php
include 'myphar.phar';
?>
php myphar.phar
This method provides a simple and easy method to create a stub that will run a startup file from the phar archive. In addition, different files can be specified for running the phar archive from the command line versus through a web server. The loader stub also calls Phar::interceptFileFuncs() to allow easy bundling of a PHP application that accesses the file system. If the phar extension is not present, the loader stub will extract the phar archive to a temporary directory and then operate on the files. A shutdown function erases the temporary files on exit.
Returns a string containing the contents of a customized bootstrap loader (stub) that allows the created Phar archive to work with or without the Phar extension enabled.
Throws UnexpectedValueException if either parameter is longer than 400 bytes.
Example #1 A Phar::createDefaultStub() example
<?php
try {
$phar = new Phar('myphar.phar');
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
// handle errors
}
?>
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::decompress — Decompresses the entire Phar archive
$extension
] )Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
For tar-based and phar-based phar archives, this method decompresses the entire archive.
For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.
In addition, this method automatically changes the file extension of the archive, .phar by default for phar archives, or .phar.tar for tar-based phar archives. Alternatively, a file extension may be specified with the second parameter.
extensionFor decompressing, the default file extensions are .phar and .phar.tar. Use this parameter to specify another file extension. Be aware that all executable phar archives must contain .phar in their filename.
A Phar object is returned.
Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.
Example #1 A Phar::decompress() example
<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 = $p2->decompress(); // creates /path/to/my.phar
?>
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::decompressFiles — Decompresses all files in the current Phar archive
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.
For Zip-based and phar-based phar archives, this method decompresses all files in the Phar archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.
Returns TRUE on success or FALSE on failure.
Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.
Example #1 A Phar::decompressFiles() example
<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>
The above example will output:
string(10) "myfile.txt" int(4096) bool(false) bool(true) string(11) "myfile2.txt" int(4096) bool(false) bool(true) string(10) "myfile.txt" bool(false) bool(false) bool(false) string(11) "myfile2.txt" bool(false) bool(false) bool(false)
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::delMetadata — Deletes the global metadata of the phar
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
Deletes the global metadata of the phar
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Throws PharException if errors occur while flushing changes to disk.
Example #1 A Phar::delMetaData() example
<?php
try {
$phar = new Phar('myphar.phar');
var_dump($phar->getMetadata());
$phar->setMetadata("hi there");
var_dump($phar->getMetadata());
$phar->delMetadata();
var_dump($phar->getMetadata());
} catch (Exception $e) {
// handle errors
}
?>
The above example will output:
NULL string(8) "hi there" NULL
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::delete — Delete a file within a phar archive
$entry
)Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.
entryPath within an archive to the file to delete.
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Throws PharException if errors occur while flushing changes to disk.
Example #1 A Phar::delete() example
<?php
try {
$phar = new Phar('myphar.phar');
$phar->delete('unlink/me.php');
// this is equivalent to:
unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
// handle errors
}
?>
(Unknown)
Phar::extractTo — Extract the contents of a phar archive to a directory
$pathto
[, string|array $files
[, bool $overwrite = false
]] )Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
Extract all files within a phar archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().
pathtoPath within an archive to the file to delete.
filesThe name of a file or directory to extract, or an array of files/directories to extract
overwrite
Set to TRUE to enable overwriting existing files
returns TRUE on success, but it is better to check for thrown exception,
and assume success if none is thrown.
Throws PharException if errors occur while flushing changes to disk.
Example #1 A Phar::extractTo() example
<?php
try {
$phar = new Phar('myphar.phar');
$phar->extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
?>
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getMetadata — Returns phar archive meta-data
Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.
No parameters.
any PHP variable that can be serialized and is stored as meta-data for the Phar archive,
or NULL if no meta-data is stored.
Example #1 A Phar::getMetadata() example
<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.php'] = '<?php echo "hello";';
$p->setMetadata(array('bootstrap' => 'file.php'));
var_dump($p->getMetadata());
} catch (Exception $e) {
echo 'Could not modify phar:', $e;
}
?>
The above example will output:
array(1) {
["bootstrap"]=>
string(8) "file.php"
}
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getModified — Return whether phar was modified
This method can be used to determine whether a phar has either had an internal file deleted, or contents of a file changed in some way.
No parameters.
TRUE if the phar has been modified since opened, FALSE if not.
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
Returns the verification signature of a phar archive in a hexadecimal string.
Array with the opened archive's signature in hash key and MD5, SHA-1, SHA-256, SHA-512, or OpenSSL in hash_type. This signature is a hash calculated on the entire phar's contents, and may be used to verify the integrity of the archive. A valid signature is absolutely required of all executable phar archives if the phar.require_hash INI variable is set to true.
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:
<?php
include 'myphar.phar';
?>
php myphar.phar
Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.
Throws RuntimeException if it is not possible to read the stub from the Phar archive.
Example #1 A Phar::getStub() example
<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
echo $p->getStub();
echo "==NEXT==\n";
$p->setStub("<?php
function __autoload($class)
{
include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>");
echo $p->getStub();
?>
The above example will output:
<?php __HALT_COMPILER(); ?>
==NEXT==
<?php
function __autoload($class)
{
include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::getSupportedCompression — Return array of supported compression algorithms
No parameters.
Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the availability of the zlib extension or the bz2 extension.
(PHP >= 5.3.0, PECL phar >= 1.1.0)
Phar::getSupportedSignatures — Return array of supported signature types
Return array of supported signature types
No parameters.
Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or OpenSSL.
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::getVersion — Return version info of Phar archive
Returns the API version of an opened Phar archive.
The opened archive's API version. This is not to be confused with the API version that the loaded phar extension will use to create new phars. Each Phar archive has the API version hard-coded into its manifest. See Phar file format documentation for more information.
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::hasMetadata — Returns whether phar has global meta-data
Returns whether phar has global meta-data set.
No parameters.
Returns TRUE if meta-data has been set, and FALSE if not.
Example #1 A Phar::hasMetadata() example
<?php
try {
$phar = new Phar('myphar.phar');
var_dump($phar->hasMetadata());
$phar->setMetadata(array('thing' => 'hi'));
var_dump($phar->hasMetadata());
$phar->delMetadata();
var_dump($phar->hasMetadata());
} catch (Exception $e) {
// handle error
}
?>
The above example will output:
bool(false) bool(true) bool(false)
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
instructs phar to intercept fopen(), readfile(), file_get_contents(), opendir(), and all of the stat-related functions. If any of these functions is called from within a phar archive with a relative path, the call is modified to access a file within the phar archive. Absolute paths are assumed to be attempts to load external files from the filesystem.
This function makes it possible to run PHP applications designed to run off of a hard disk as a phar application.
No parameters.
Example #1 A Phar::interceptFileFuncs() example
<?php
Phar::interceptFileFuncs();
include 'phar://' . __FILE__ . '/file.php';
?>
Assuming that this phar is at /path/to/myphar.phar and it contains file.php and file2.txt, if file.php contains this code:
Example #2 A Phar::interceptFileFuncs() example
<?php
echo file_get_contents('file2.txt');
?>
Normally PHP would search the current directory for file2.txt, which would translate as the directory of file.php, or the current directory of a command-line user. Phar::interceptFileFuncs() instructs PHP to consider the current directory to be phar:///path/to/myphar.phar/ and so opens phar:///path/to/myphar.phar/file2.txt in the above example code.
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to Phar::stopBuffering() is needed to enable saving changes.
Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.
Returns TRUE if the write operations are being buffer, FALSE otherwise.
Example #1 A Phar::isBuffering() example
<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p2 = new Phar('existingphar.phar');
$p['file1.txt'] = 'hi';
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>
=2=
<?php
$p->startBuffering();
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
$p->stopBuffering();
?>
=3=
<?php
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>
The above example will output:
bool(false) bool(false) =2= bool(true) bool(false) =3= bool(false) bool(false)
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
Note:
This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.
Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed
(.tar.gz/tar.bz and so on). Zip-based phar archives cannot be compressed as a
file, and so this method will always return FALSE if a zip-based phar archive is queried.
No parameters.
Phar::GZ, Phar::BZ2 or FALSE
Example #1 A Phar::isCompressed() example
<?php
try {
$phar1 = new Phar('myphar.zip.phar');
var_dump($phar1->isCompressed());
$phar2 = new Phar('myuncompressed.tar.phar');
var_dump($phar2->isCompressed());
$phar2->compressAllFilesGZ();
var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>
The above example will output:
bool(false) bool(false) bool(true)
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
$format
)
formatEither Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format of the archive.
Returns TRUE if the phar archive matches the file format requested by the parameter
PharException is thrown if the parameter is an unknown file format specifier.
(PHP >= 5.3.0, PECL phar >= 1.2.0)
Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
$filename
[, bool $executable = true
] )Returns whether the given filename is a valid phar filename that will be recognized as a phar archive by the phar extension. This can be used to test a name without having to instantiate a phar archive and catch the inevitable Exception that will be thrown if an invalid name is specified.
filenameThe name or full path to a phar archive not yet created
executableThis parameter determines whether the filename should be treated as a phar executable archive, or a data non-executable archive
Returns TRUE if the filename is valid, FALSE if not.
(Unknown)
Phar::isWritable — Returns true if the phar archive can be modified
This method returns TRUE if phar.readonly is 0,
and the actual phar archive on disk is not read-only.
No parameters.
Returns TRUE if the phar archive can be modified
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::loadPhar — Loads any phar archive with an alias
$filename
[, string $alias
] )This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts.
filenamethe full or relative path to the phar archive to open
aliasThe alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a PharException will be thrown if a new alias is specified in this case.
Returns TRUE on success or FALSE on failure.
PharException is thrown if an alias is passed in and the phar archive already has an explicit alias
Example #1 A Phar::loadPhar() example
Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar.
<?php
try {
Phar::loadPhar('/path/to/phar.phar', 'my.phar');
echo file_get_contents('phar://my.phar/file.txt');
} catch (PharException $e) {
echo $e;
}
?>
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
$alias
[, int $dataoffset = 0
]] )This static method can only be used inside a Phar archive's loader stub in order to initialize the phar when it is directly executed, or when it is included in another script.
aliasThe alias that can be used in phar:// URLs to refer to this archive, rather than its full path.
dataoffsetUnused variable, here for compatibility with PEAR's PHP_Archive.
Returns TRUE on success or FALSE on failure.
PharException is thrown if not called directly within PHP execution, if no __HALT_COMPILER(); token is found in the current source file, or if the file cannot be opened for reading.
Example #1 A Phar::mapPhar() example
mapPhar should be used only inside a phar's loader stub. Use loadPhar to load an external phar into memory.
Here is a sample Phar loader stub that uses mapPhar.
<?php
function __autoload($class)
{
include 'phar://me.phar/' . str_replace('_', '/', $class) . '.php';
}
try {
Phar::mapPhar('me.phar');
include 'phar://me.phar/startup.php';
} catch (PharException $e) {
echo $e->getMessage();
die('Cannot initialize Phar');
}
__HALT_COMPILER();
(PHP >= 5.3.0, PECL phar >= 2.0.0)
Phar::mount — Mount an external path or file to a virtual location within the phar archive
$pharpath
, string $externalpath
)Much like the unix file system concept of mounting external devices to paths within the directory tree, Phar::mount() allows referring to external files and directories as if they were inside of an archive. This allows powerful abstraction such as referring to external configuration files as if they were inside the archive.
pharpathThe internal path within the phar archive to use as the mounted path location. This must be a relative path within the phar archive, and must not already exist.
externalpathA path or URL to an external file or directory to mount within the phar archive
No return. PharException is thrown on failure.
Throws PharException if any problems occur mounting the path.
Example #1 A Phar::mount() example
The following example shows accessing an external configuration file as if it were a path within a phar archive.
First, the code inside of a phar archive:
<?php
$configuration = simplexml_load_string(file_get_contents(
Phar::running(false) . '/config.xml'));
?>
Next the external code used to mount the configuration file:
<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
Phar::mount('phar://config.xml', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>
Another method is to put the mounting code inside the stub of the phar archive. Here is an example of setting up a default configuration file if no user configuration is specified:
<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
if (defined('EXTERNAL_CONFIG')) {
Phar::mount('config.xml', EXTERNAL_CONFIG);
if (file_exists(__DIR__ . '/extra_config.xml')) {
Phar::mount('extra.xml', __DIR__ . '/extra_config.xml');
}
} else {
Phar::mount('config.xml', 'phar://' . __FILE__ . '/default_config.xml');
Phar::mount('extra.xml', 'phar://' . __FILE__ . '/default_extra.xml');
}
// now run the application
include 'phar://' . __FILE__ . '/index.php';
__HALT_COMPILER();
?>
...and the code externally to load this phar archive:
<?php
define('EXTERNAL_CONFIG', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>
(Unknown)
Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
$munglist
)Phar::mungServer() should only be called within the stub of a phar archive.
Defines a list of up to 4 $_SERVER variables that should be modified for execution. Variables that can be modified to remove traces of phar execution are REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME.
On its own, this method does nothing. Only when combined with Phar::webPhar() does it take effect, and only when the requested file is a PHP file to be parsed. Note that the PATH_INFO and PATH_TRANSLATED variables are always modified.
The original values of variables that are modified are stored in the SERVER array with PHAR_ prepended, so for instance SCRIPT_NAME would be saved as PHAR_SCRIPT_NAME.
munglistan array containing as string indices any of REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an exception, and Phar::mungServer() is case-sensitive.
No return.
Throws UnexpectedValueException if any problems are found with the passed in data.
Example #1 A Phar::mungServer() example
<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::offsetExists — determines whether a file exists in the phar
$offset
)This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets.
offsetExists() is called whenever isset() is called.
offsetThe filename (relative path) to look for in a Phar.
Returns TRUE if the file exists within the phar, or FALSE if not.
Example #1 A Phar::offsetExists() example
<?php
$p = new Phar(dirname(__FILE__) . '/my.phar', 0, 'my.phar');
$p['firstfile.txt'] = 'first file';
$p['secondfile.txt'] = 'second file';
// the next set of lines call offsetExists() indirectly
var_dump(isset($p['firstfile.txt']));
var_dump(isset($p['nothere.txt']));
?>
The above example will output:
bool(true) bool(false)
(PHP >= 5.3.0, PECL phar >= 1.0.0)
Phar::offsetGet — Gets a PharFileInfo object for a specific file
$offset
)This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. Phar::offsetGet() is used for retrieving files from a Phar archive.
offsetThe filename (relative path) to look for in a Phar.
A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.
This method throws BadMethodCallException if the file does not exist in the Phar archive.
Example #1 Phar::offsetGet() example
As with all cla